func (oa OAuthenticator) RequireAuth(w http.ResponseWriter, r *http.Request) { sess, err := gothic.Store.Get(r, gothic.SessionName) if err != nil { if _, ok := err.(securecookie.Error); ok { r.Header.Set("Cookie", "") sess, err = gothic.Store.New(r, gothic.SessionName) if err != nil { w.WriteHeader(500) w.Write([]byte("Failure generating a new session: " + err.Error())) return } } else { log.Errorf("%s", err) w.WriteHeader(500) w.Write([]byte("Unexpected error retrieving session data")) return } } sess.AddFlash(r.URL.Path) sess.Save(r, w) // only start oauth redirection if we're hitting the auth APIs, or web UI if ShouldOAuthRedirect(r.URL.Path) { log.Debugf("Starting OAuth Process for request: %s", r) gothic.BeginAuthHandler(w, r) } else { // otherwise set auth header for api clients to understand oauth is needed log.Debugf("Unauthenticated API Request received, OAuth required, sending 401") w.Header().Set("WWW-Authenticate", "Bearer") w.WriteHeader(401) w.Write([]byte("Unauthorized")) } }
// loginHandlerはサードパーティへのログインの処理を受け持ちます // パスの形式: /auth/{action}/{provider} func loginHandler(w http.ResponseWriter, r *http.Request) { action := r.URL.Query().Get(":action") provider := r.URL.Query().Get(":provider") switch action { case "login": gothic.BeginAuthHandler(w, r) log.Println("TODO: ログイン処理", provider) case "callback": // print our state string to the console. Ideally, you should verify // that it's the same string as the one you set in `setState` fmt.Println("State: ", gothic.GetState(r)) user, err := gothic.CompleteUserAuth(w, r) if err != nil { log.Fatal("CompleteUserAuth error: ", err) return } authCookieValue := base64.StdEncoding.EncodeToString([]byte(user.Name)) http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) fmt.Println(user) w.Header().Set("Location", "/chat") w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "アクション%sには非対応です", action) } }
func (c *LoginController) Authenticate() { c.mapUrl() if c.isLoggedIn() { log.Print("Yes a token exist") c.Ctx.Redirect(301, "/secure") return } gothic.BeginAuthHandler(c.Ctx.ResponseWriter, c.Ctx.Request) }
// loginHandlerはサードパーティへのログインの処理を受け持ちます // パスの形式: /auth/{action}/{provider} func loginHandler(w http.ResponseWriter, r *http.Request) { action := r.URL.Query().Get(":action") // provider := r.URL.Query().Get(":provider") switch action { case "login": gothic.BeginAuthHandler(w, r) case "callback": // print our state string to the console. Ideally, you should verify // that it's the same string as the one you set in `setState` fmt.Println("State: ", gothic.GetState(r)) githubUser, err := gothic.CompleteUserAuth(w, r) if err != nil { log.Fatal("CompleteUserAuth error: ", err) return } // ユーザーの保存 var user User err = mapstructure.Decode(githubUser.RawData, &user) if err != nil { log.Fatal("mapstructure error: ", err) return } session, err := mgo.Dial("mongodb://localhost") if err != nil { log.Fatal("mgo database dial error:", err) return } defer session.Close() session.SetMode(mgo.Monotonic, true) c := session.DB("donuts_tech_calendar").C("users") err = user.FindOrCreate(c) if err != nil { log.Fatal("user.FindOrCreate error:", err) return } authCookieValue := base64.StdEncoding.EncodeToString([]byte(user.UserName)) http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) w.Header().Set("Location", "/index#/chat") w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "アクション%sには非対応です", action) } }
func AuthProvider(c *gin.Context) { fn := gothic.GetProviderName gothic.GetProviderName = func(req *http.Request) (string, error) { provider := c.Params.ByName("provider") if provider == "" { return fn(req) } return provider, nil } gothic.BeginAuthHandler(c.Writer, c.Request) }
func auth(res http.ResponseWriter, req *http.Request) { gothic.BeginAuthHandler(res, req) }
func startAuthHandler(res http.ResponseWriter, req *http.Request) { fmt.Println("Start Auth Handler: " + gothic.GetState(req)) gothic.BeginAuthHandler(res, req) }
func providerAuth(c *gin.Context) { gothic.GetProviderName = getProviderName gothic.BeginAuthHandler(c.Writer, c.Request) }
// BeginAuth begins the authentication process, redirecting the user to some // OAuth2 API depending upon the provider specified in the request path func BeginAuth(w rest.ResponseWriter, req *rest.Request) { setProvider(req) gothic.BeginAuthHandler(w.(http.ResponseWriter), req.Request) }
func (ah *AuthHandler) FacebookAuth(c *gin.Context) { gothic.BeginAuthHandler(c.Writer, c.Request) }
func redirectHandler(c *echo.Context) error { gothic.BeginAuthHandler(c.Response(), c.Request()) return nil }
func providerAuth(c *gin.Context) { gothic.GetProviderName = func(req *http.Request) (string, error) { return "github", nil } gothic.BeginAuthHandler(c.Writer, c.Request) }
func main() { getPathFromParameterAndLoadConfigFile() goth.UseProviders( facebook.New("870850926323133", "54c9687312192961b6e2b5caa319db4b", "http://localhost:8081/auth/facebook/callback"), ) gothic.GetState = func(req *http.Request) string { return req.URL.Query().Get("state") } router := gin.New() router.Use(cors.Middleware(cors.Options{ AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization", "Access-Control-Allow-Headers", "Access-Control-Allow-Methods", "Access-Control-Allow-Origin"}, })) // Set Logger gin.DefaultWriter = config.GetLogFile() router.Use(gin.Logger()) router.Use(gin.Recovery()) tasks.SetRoutes(router) public := router.Group("/api") public.GET("/", func(c *gin.Context) { tokenString, err := createJWTToken("AnonymousUser") if err != nil { c.JSON(500, gin.H{"message": "Could not generate token"}) return } c.JSON(200, gin.H{"accessToken": tokenString}) }) private := router.Group("/api/private") private.Use(jwt.Auth(config.TokenSecret)) /* Set this header in your request to get here. Authorization: Bearer `token` */ private.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello from private"}) }) authRoute := router.Group("/auth") authRoute.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Go to /auth/facebook"}) }) authRoute.GET("/facebook", func(c *gin.Context) { gothic.GetProviderName = getProviderFacebook gothic.BeginAuthHandler(c.Writer, c.Request) }) authRoute.GET("/facebook/callback", func(c *gin.Context) { user, err := gothic.CompleteUserAuth(c.Writer, c.Request) if err != nil { fmt.Fprintln(c.Writer, err) return } tokenString, err := createJWTToken(user.Email) if err != nil { c.JSON(500, gin.H{"message": "Could not generate token"}) } c.JSON(200, gin.H{ "name": user.Name, "email": user.Email, "userId": user.UserID, "facebookAccessToken": user.AccessToken, "accessToken": tokenString, }) }) router.Run(config.Settings["ListenAddress"].(string)) }