func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error while getting provider:", provider, " : ", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("Error while getting GetBeginAuthURL for", provider, " : ", err) } w.Header().Set("Location", loginUrl) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error while getting provider:", provider, " : ", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("Error while completing auth for", provider, " : ", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("Error while getting user for", provider) } // User Id is a md5 of the name m := md5.New() io.WriteString(m, strings.ToLower(user.Email())) userId := fmt.Sprintf("%x", m.Sum(nil)) // save some data authCookieValue := objx.New(map[string]interface{}{ "userid": userId, "name": user.Name(), "avatar_url": user.AvatarURL(), "email": user.Email(), }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Auth action %s not supported", action) } }
func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("Error when trying to get GetBeginAuthUrl for", provider, "-", err) } w.Header().Set("Location", loginUrl) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Auth action %s not supported", action) } }
// loginHandlerはサードパーティーへのログインの処理を受け持ちます // パスの形式: /auth/{action}/{provider} func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("認証プロバイダーの取得に失敗しました:", provider, "-", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("GetBeginAuthURL の呼び出し中にエラーが発生しました:", provider, "-", err) } w.Header().Set("Location", loginUrl) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("認証プロバイダーの取得に失敗しました", provider, "-", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("認証を完了できませんでした", provider, "-", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("ユーザーの取得に失敗しました", provider, "-", err) } chatUser := &chatUser{User: user} m := md5.New() io.WriteString(m, strings.ToLower(user.Name())) chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil)) avatarURL, err := avatars.GetAvatarURL(chatUser) if err != nil { log.Fatalln("GetAvatarURLに失敗しました", "-", err) } // データを保存します authCookieValue := objx.New(map[string]interface{}{ "userid": chatUser.uniqueID, "name": user.Name(), "avatar_url": avatarURL, }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/"}) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "アクション%sには非対応です", action) } }
//loginHandler handle the third party login process //format: /auth/{action}/{provider} func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") if len(segs) != 4 { w.WriteHeader(http.StatusBadRequest) fmt.Fprintf(w, "Invalid URL path %s", r.URL.Path) return } action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } loginURL, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err) } w.Header().Set("Location", loginURL) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("Error when trying to complete auth for", provider, "-", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("Error when trying to get user creds for", provider, "-", err) } chatUser := &chatUser{User: user} m := md5.New() io.WriteString(m, strings.ToLower(user.Email())) userid := fmt.Sprintf("%x", m.Sum(nil)) chatUser.uniqueID = userid avatarURL, err := avatars.GetAvatarURL(chatUser) if err != nil { log.Fatalln("Error when trying to getAvatarURL", "-", err) } authCookieValue := objx.New(map[string]interface{}{ "userID": userid, "name": user.Name(), "avatar_url": avatarURL, }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/"}) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Auth action %s not supported", action) } }
// loginHandler handles the third-party login process. func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err) } w.Header()["Location"] = []string{loginUrl} w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } // get the credentials creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("Error when trying to complete auth for", provider, "-", err) } // get the user user, err := provider.GetUser(creds) if err != nil { log.Fatalln("Error when trying to get user from", provider, "-", err) } // save some data authCookieValue := objx.New(map[string]interface{}{ "name": user.Name(), }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/"}) w.Header().Set("Location", "/chat") w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Auth action %s not supported", action) } }
func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatal("Failed autorizatoin: ", provider, "-", err) } loginURL, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("Had error during calling GetBeginAuthURL:", provider, "-", err) } w.Header().Set("Location", loginURL) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("failed to get authorization from auth provider", provider, "-", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("Could not finish authorization", provider, "-", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("failed get user", provider, "-", err) } authCookieValue := objx.New(map[string]interface{}{ "name": user.Name(), "avatar_url": user.AvatarURL(), }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/"}) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "can't handle action: %s", action) } }
func generateAuthRoutes() { /* Perform the auth */ goweb.Map("/auth/{provider}", func(c context.Context) error { log.Println("Starting authentication") provider, err := gomniauth.Provider(c.PathValue("provider")) log.Println("Created new provider") if err != nil { return err } state := gomniauth.NewState("after", "success") log.Println("Set to new state") authUrl, err := provider.GetBeginAuthURL(state, nil) log.Println("Getting auth url") if err != nil { return err } log.Println("Responding with redirect") return goweb.Respond.WithRedirect(c, authUrl) }) /* Callback from auth */ goweb.Map("/auth/{provider}/callback", func(c context.Context) error { log.Println("Authentication response") provider, err := gomniauth.Provider(c.PathValue("provider")) if err != nil { log.Fatalf("Error with provider") return goweb.Respond.WithRedirect(c, "/auth/status/failed") } creds, err := provider.CompleteAuth(c.QueryParams()) log.Println("Completing authentication") if err != nil { log.Fatalf("Error completing authentication") return goweb.Respond.WithRedirect(c, "/auth/status/failed") } log.Println("Getting user credentials") user, userErr := provider.GetUser(creds) if userErr != nil { log.Fatalf("Get user error") return goweb.Respond.WithRedirect(c, "/auth/status/failed") } log.Println("Authenticated successfully!") log.Println("Username: %s User email: %s", user.Name(), user.Email()) return goweb.Respond.WithRedirect(c, "/auth/status/successful") }) /* Complete auth notification */ goweb.Map("/auth/status/successful", func(c context.Context) error { return goweb.Respond.With(c, 200, []byte("Authentication completed successfully")) }) /* Failed auth notification */ goweb.Map("/auth/status/failed", func(c context.Context) error { return goweb.Respond.With(c, 400, []byte("Authentication failed")) }) }
func loginHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { action := ps.ByName("action") provider := ps.ByName("provider") s := sessions.GetSession(r) switch action { case "login": // gomniauth Provider의 login 페이지로 이동 p, err := gomniauth.Provider(provider) if err != nil { log.Fatalln(err) } loginUrl, err := p.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln(err) } http.Redirect(w, r, loginUrl, http.StatusFound) case "callback": // gomniauth 콜백 처리 p, err := gomniauth.Provider(provider) if err != nil { log.Fatalln(err) } creds, err := p.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln(err) } // 콜백 결과로 부터 사용자 정보 확인 user, err := p.GetUser(creds) if err != nil { log.Fatalln(err) } if err != nil { log.Fatalln(err) } u := &User{ Uid: user.Data().Get("id").MustStr(), Name: user.Name(), Email: user.Email(), AvatarUrl: user.AvatarURL(), } SetCurrentUser(r, u) // 사용자 정보를 세션에 저장 http.Redirect(w, r, s.Get(nextPageKey).(string), http.StatusFound) default: http.Error(w, "Auth action '"+action+"' is not supported", http.StatusNotFound) } }
func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Failed to get authentication provider from ", provider, " - ", err) } loginURL, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("Failed in GetBeginAuthURL for ", provider, " - ", err) } w.Header().Set("Location", loginURL) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Failed to get authentication provider from ", provider, " - ", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("Failed in authentication for ", provider, " - ", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("Failed to get user from ", provider, " - ", err) } authCookieValue := objx.New(map[string]interface{}{ "name": user.Name(), "email": user.Email(), }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "action %s is not supported", action) } }
func loginHandler(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("認証プロバイダーの取得に失敗しました:", provider, "-", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("GetBeginAuthURLの呼び出し中にエラーが発生しました", provider, "-", err) } w.Header().Set("Location", loginUrl) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("認証プロバイダーの取得に失敗しました。", provider, "-", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("認証を完了できませんでした", provider, "-", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("ユーザーの取得に失敗しました", provider, "-", err) } authCookieValue := objx.New(map[string]interface{}{ "name": user.Name(), }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) w.Header().Set("Location", "/chat") w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "アクション%sには非対応です", action) } }
func getUser(r *http.Request) (user common.User, target string, err error) { provider, err := gomniauth.Provider("google") if err != nil { log.Fatal(err) } omap, err := objx.FromURLQuery(r.URL.RawQuery) if err != nil { return } creds, err := provider.CompleteAuth(omap) if err != nil { return } state, err := gomniauth.StateFromParam(omap.Get("state").String()) if err != nil { return } target = state.Get("redirect").String() user, err = provider.GetUser(creds) return }
func callbackHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { providerName := kami.Param(ctx, "provider") provider, err := gomniauth.Provider(providerName) if err != nil { log.Fatalln("認証プロバイダーの取得に失敗しました", provider, "-", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("認証を完了できませんでした", provider, "-", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("ユーザーの取得に失敗しました", provider, "- ", err) } authCookieValue := objx.New(map[string]interface{}{ "name": user.Name(), }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/"}) log.Println("######### ", authCookieValue) w.Header()["Location"] = []string{"/"} w.WriteHeader(http.StatusTemporaryRedirect) }
func loginHandler(providerName string, auth bool) http.HandlerFunc { if auth != true { return func(w http.ResponseWriter, r *http.Request) {} } return func(w http.ResponseWriter, r *http.Request) { provider, err := gomniauth.Provider(providerName) if err != nil { log.Printf("error getting gomniauth provider") http.Error(w, err.Error(), http.StatusInternalServerError) return } state := gomniauth.NewState("after", "success") authURL, err := provider.GetBeginAuthURL(state, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, authURL, http.StatusFound) } }
func loginHandler(providerName string) http.HandlerFunc { provider, err := gomniauth.Provider(providerName) if err != nil { panic(err) } return func(w http.ResponseWriter, r *http.Request) { state := gomniauth.NewState("after", "success") // This code borrowed from goweb example and not fixed. // if you want to request additional scopes from the provider, // pass them as login?scope=scope1,scope2 //options := objx.MSI("scope", ctx.QueryValue("scope")) authUrl, err := provider.GetBeginAuthURL(state, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // redirect http.Redirect(w, r, authUrl, http.StatusFound) } }
func loginHandler(w http.ReponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("fail to get provider", provider, "-", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("error GetBeginAuthURL", provider, "-", err) } w.Header().Set("Location", loginUrl) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("fail to get provider", provider, "-", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("error CompleteAuth", provider, "-", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("error GetUser", provider, "-", err) } authCookieValue := objx.New(map[string]interface{}{ "name": user.Name(), }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) w.Header()["Location"] = []string("/2/1") w.WriteHeader(http.StatusTemporaryRedirect) default: w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "not accept %s", action) } }
func callbackHandler(providerName string, auth bool) http.HandlerFunc { if auth != true { return func(w http.ResponseWriter, r *http.Request) {} } return func(w http.ResponseWriter, r *http.Request) { provider, err := gomniauth.Provider(providerName) if err != nil { log.Printf("error getting gomniauth provider") http.Error(w, err.Error(), http.StatusInternalServerError) return } omap, err := objx.FromURLQuery(r.URL.RawQuery) if err != nil { log.Printf("error getting resp from callback") http.Error(w, err.Error(), http.StatusInternalServerError) return } creds, err := provider.CompleteAuth(omap) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } user, userErr := provider.GetUser(creds) if userErr != nil { log.Printf("Failed to get user from Github %s", user) http.Error(w, err.Error(), http.StatusInternalServerError) return } session, err := store.Get(r, sessionName) if err != nil { log.Printf("Failed to get Session %s", user) http.Error(w, err.Error(), http.StatusInternalServerError) return } session.Options = &sessions.Options{ Path: "/", MaxAge: 86400 * 7, HttpOnly: true, } session.Values["userName"] = user.Nickname() session.Values["avatarURL"] = user.AvatarURL() session.Save(r, w) http.Redirect(w, r, os.Getenv("GITHUB_CALLBACK_URL"), http.StatusFound) } }
// CallbackHandler receives callback from github OAuth provider func CallbackHandler(w http.ResponseWriter, r *http.Request) { if !enabled { http.Error(w, "authenticatin disabled", http.StatusBadRequest) return } provider, err := gomniauth.Provider(providerName) if err != nil { glog.Errorf("failed to get authentication provider %s: %v", providerName, err) http.Error(w, err.Error(), http.StatusInternalServerError) return } omap, err := objx.FromURLQuery(r.URL.RawQuery) if err != nil { glog.Errorf("Failed to parse querystring: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } creds, err := provider.CompleteAuth(omap) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } user, userErr := provider.GetUser(creds) if userErr != nil { glog.Errorf("Failed to get user from Github %s", user) http.Error(w, err.Error(), http.StatusInternalServerError) return } session, err := store.Get(r, sessionName) if err != nil { glog.Errorf("Failed to fetch current session: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } session.Options = &sessions.Options{ Path: "/", MaxAge: 86400 * 7, HttpOnly: true, } session.Values["userName"] = user.Nickname() session.Values["avatarURL"] = user.AvatarURL() session.Save(r, w) http.Redirect(w, r, os.Getenv("GITHUB_CALLBACK_URL"), http.StatusFound) }
func (a *defaultAuthenticator) getAuthProvider(r *http.Request, providerName string) (common.Provider, error) { gomniauth.WithProviders( google.New(a.cfg.GoogleClientID, a.cfg.GoogleSecret, getBaseURL(r)+"/api/auth/oauth2/google/callback/", ), ) provider, err := gomniauth.Provider(providerName) if err != nil { return provider, errgo.Mask(err) } return provider, nil }
func callbackHandler(providerName string) http.HandlerFunc { provider, err := gomniauth.Provider(providerName) if err != nil { panic(err) } return func(w http.ResponseWriter, r *http.Request) { omap, err := objx.FromURLQuery(r.URL.RawQuery) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } creds, err := provider.CompleteAuth(omap) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } /* // This code borrowed from goweb example and not fixed. // get the state state, err := gomniauth.StateFromParam(ctx.QueryValue("state")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // redirect to the 'after' URL afterUrl := state.GetStringOrDefault("after", "error?e=No after parameter was set in the state") */ // load the user user, userErr := provider.GetUser(creds) if userErr != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } data := fmt.Sprintf("%#v", user) io.WriteString(w, data) // redirect //return goweb.Respond.WithRedirect(ctx, afterUrl) } }
func loginHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { providerName := kami.Param(ctx, "provider") provider, err := gomniauth.Provider(providerName) if err != nil { log.Fatalln("認証プロバイダー の取得に失敗しました:", provider, "-", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("GetBeginAuthURLの呼び出し中にエラーが発生しました:", provider, "-", err) } w.Header().Set("Location", loginUrl) w.WriteHeader(http.StatusTemporaryRedirect) }
func login(w http.ResponseWriter, r *http.Request, redirect string) { provider, err := gomniauth.Provider("google") if err != nil { log.Fatal(err) } state := gomniauth.NewState("redirect", redirect) authUrl, err := provider.GetBeginAuthURL(state, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } loginPage.Execute(w, []Provider{{URL: template.URL(authUrl), Name: "Google"}}) }
func oauth2callback(params martini.Params, s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) { providerName := params["provider"] if providerName == "" { http.Error(w, "Unknown provider", http.StatusBadRequest) return } provider, err := gomniauth.Provider(providerName) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("ERROR: %s", err) return } omap, err := objx.FromURLQuery(r.URL.RawQuery) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } creds, err := provider.CompleteAuth(omap) if err != nil { s.Delete("username") http.Redirect(w, r, "/signin?error=Access+Denied", http.StatusFound) log.Printf("ERROR: %s", err) return } user, err := provider.GetUser(creds) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("ERROR: %s", err) return } if strings.HasSuffix(user.Email(), authDomain) { log.Printf("%s authenticated via %s", user.Email(), providerName) s.Set("username", user.Email()) } else { http.Redirect(w, r, "/signin", http.StatusFound) return } http.Redirect(w, r, "/", http.StatusFound) }
func loginHandler(providerName string) http.HandlerFunc { provider, err := gomniauth.Provider(providerName) if err != nil { panic(err) } return func(w http.ResponseWriter, r *http.Request) { state := gomniauth.NewState("after", "success") authURL, err := provider.GetBeginAuthURL(state, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // redirect http.Redirect(w, r, authURL, http.StatusFound) } }
func callbackHandler(providerName string) http.HandlerFunc { provider, err := gomniauth.Provider(providerName) if err != nil { panic(err) } return func(w http.ResponseWriter, r *http.Request) { omap, err := objx.FromURLQuery(r.URL.RawQuery) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } creds, err := provider.CompleteAuth(omap) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // load the user user, userErr := provider.GetUser(creds) if userErr != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Printf("Authenticated as %s", user.Email()) sig := aDB.Register(user.Email(), user.Email(), time.Now().AddDate(0, 0, 1)) cookie := http.Cookie{Name: "auth", Value: string(sig.Sig), Expires: sig.Expiration, Path: "/"} http.SetCookie(w, &cookie) // data := fmt.Sprintf("%#v", user) // io.WriteString(w, data) // redirect http.Redirect(w, r, "/", http.StatusFound) } }
// LoginHandler begins github OAuth2 authentication func LoginHandler(w http.ResponseWriter, r *http.Request) { if !enabled { return } provider, err := gomniauth.Provider(providerName) if err != nil { glog.Errorf("failed to get authentication provider %s: %v", providerName, err) http.Error(w, err.Error(), http.StatusInternalServerError) return } state := gomniauth.NewState("after", "success") authURL, err := provider.GetBeginAuthURL(state, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, authURL, http.StatusFound) }
func authRedirect(params martini.Params, s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) { providerName := params["provider"] if providerName == "" { http.Error(w, "Unknown provider", http.StatusBadRequest) return } provider, err := gomniauth.Provider(providerName) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("ERROR: %s", err) return } authUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { w.WriteHeader(http.StatusInternalServerError) log.Printf("ERROR: %s", err) return } http.Redirect(w, r, authUrl, http.StatusFound) }
func Connect(ctx context.Context) error { provider_type := ctx.PathValue("provider") action := ctx.PathValue("action") if provider_type == "facebook" { provider, err := gomniauth.Provider(provider_type) if err != nil { log.Error("Error on getting provider: " + err.Error()) return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."}) } state := gomniauth.NewState("after", "success") // if you want to request additional scopes from the provider, // pass them as login?scope=scope1,scope2 //options := objx.MSI("scope", ctx.QueryValue("scope")) authUrl, err := provider.GetBeginAuthURL(state, nil) if err != nil { log.Error("Error on getting url: " + err.Error()) return goweb.API.Respond(ctx, 200, nil, []string{"An error has occured."}) } // redirect return goweb.Respond.WithRedirect(ctx, authUrl) } else if provider_type == "local" && ctx.MethodString() == "POST" { // This is taken care of in separate functions. // Local login only with POST if action == "login" { return nil } else if action == "register" { return nil } else if action == "connect" { return nil } else { return goweb.API.Respond(ctx, 200, nil, []string{"Invalid action."}) } } else { return goweb.API.Respond(ctx, 200, nil, []string{"Invalid provider type."}) } }
// loginHander handles the third-party login process. // format: /auth/{action}/{provider} func loginHander(w http.ResponseWriter, r *http.Request) { segs := strings.Split(r.URL.Path, "/") if len(segs) < 4 { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "format: /auth/{action}/{provider}") return } action := segs[2] provider := segs[3] switch action { case "login": // redirect users to the provider's authentication page // when they land on our /auth/login/{provider} path. provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } loginURL, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("Error when trying to GetBeginAuthURL for", provider, "-", err) } w.Header().Set("Location", loginURL) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": // the provider rediect back to our callback endpoint, the // Gomniauth will exchange the grant code for an access token. provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("Error when trying to get provider", provider, "-", err) } // parse the RawQuery from the http.Request into objx.Map and the // CompleteAuth method uses the URL query parameter values to // complete the authentication handshake with the provider. creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("Error when trying to complete auth for", provider, "-", err) } // use the specified credential to access the basic user info. user, err := provider.GetUser(creds) if err != nil { log.Fatalln("Error when trying to get user from", provider, "-", err) } chatUser := &chatUser{User: user} // create a new md5 hasher, because the hasher implements // the io.Writer interface, we can use io.WriteString to // write a string of bytes to it. Calling Sum returns the // current hash for the bytes written. m := md5.New() io.WriteString(m, strings.ToLower(user.Email())) chatUser.uniqueID = fmt.Sprintf("%x", m.Sum(nil)) avatarURL, err := avatars.GetAvatarURL(chatUser) if err != nil { log.Fatalln("Error when trying to GetAvatarURL", "-", err) } // save the auth info into cookie authCookieValue := objx.New(map[string]interface{}{ "userid": chatUser.uniqueID, "name": user.Name(), "avatar_url": avatarURL, }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) default: // write out an error message and return an // http.StatusNotFound status code (404) w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Auth action %s not supported", action) } }
// loginHandler handles the third-party login process // format: /auth/{action}/{provider} // callback: /auth/callback/{provider} func loginHandler(w http.ResponseWriter, r *http.Request) { log.Println("req url path:", r.URL.Path) segs := strings.Split(r.URL.Path, "/") action := segs[2] provider := segs[3] switch action { case "login": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("error when trying to get provider", provider, "-", err) } loginUrl, err := provider.GetBeginAuthURL(nil, nil) if err != nil { log.Fatalln("error when trying to get GetBeginAuthURL for", provider, "-", err) } w.Header().Set("Location", loginUrl) w.WriteHeader(http.StatusTemporaryRedirect) case "callback": provider, err := gomniauth.Provider(provider) if err != nil { log.Fatalln("error when trying to get provider", provider, "-", err) } creds, err := provider.CompleteAuth(objx.MustFromURLQuery(r.URL.RawQuery)) if err != nil { log.Fatalln("error when trying to complete auth for", provider, "-", err) } user, err := provider.GetUser(creds) if err != nil { log.Fatalln("error when trying to get user from", provider, "-", err) } // log.Println("user name:", user.Name()) // log.Println("user avatar url:", user.AvatarURL()) m := md5.New() io.WriteString(m, strings.ToLower(user.Name())) chatUser := &chatUser{User: user} chatUser.uniqueId = fmt.Sprintf("%x", m.Sum(nil)) avatarUrl, err := avatars.GetAvatarURL(chatUser) if err != nil { log.Fatalln("error when trying to GetAvatarURL", "-", err) } // save some data authCookieValue := objx.New(map[string]interface{}{ "userid": chatUser.UniqueId(), "name": user.Name(), "avatar_url": avatarUrl, }).MustBase64() http.SetCookie(w, &http.Cookie{ Name: "auth", Value: authCookieValue, Path: "/", }) w.Header()["Location"] = []string{"/chat"} w.WriteHeader(http.StatusTemporaryRedirect) default: // todo: use /auth/nonsense ? w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "Auth action %s not supported", action) } }
func main() { usr := hero.User{ UserName: "******", Password: "******", Email: "*****@*****.**", } genericClient := hero.Client{ Name: "simple", UUID: "sampleUUID", Secret: "mysecret", } heroCfg := hero.DefaultConfig() heroURL := "http://localhost:8000" demoserver := "http://localhost:8001" s := hero.NewServer(heroCfg, &hero.SimpleTokenGen{}, nil) s.DropAllTables() s.Migrate() cCliet := genericClient cCliet.RedirectURL = demoserver + "/callback" cUsr := usr s.TestClient(&cUsr, &cCliet) clientCfg := &client.Config{ ProviderName: "hero", ProviderDisplayName: "Hero", AuthURL: fmt.Sprintf("%s%s", heroURL, heroCfg.AuthEndpoint), TokenURL: fmt.Sprintf("%s%s", heroURL, heroCfg.TokenEndpoint), ProfileURL: heroURL + heroCfg.InfoEndpoint, CLientID: genericClient.UUID, CLientSecret: genericClient.Secret, DefaultScope: "user", RedirectURL: fmt.Sprintf("%s/callback", demoserver), } gomniauth.SetSecurityKey("ylqRcG4sLnhgOUIt3hbPKiHULHgrutOkpBNwibeJjL4eZ08zzR6YQ0WPl476Cubo") gomniauth.WithProviders( client.New(clientCfg), ) demo := http.NewServeMux() demo.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) { provider, err := gomniauth.Provider(clientCfg.ProviderName) if err != nil { // w.Write([]byte(err.Error())) // return panic(err) } state := gomniauth.NewState("after", "success") // This code borrowed from goweb example and not fixed. // if you want to request additional scopes from the provider, // pass them as login?scope=scope1,scope2 //options := objx.MSI("scope", ctx.QueryValue("scope")) authUrl, err := provider.GetBeginAuthURL(state, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // redirect http.Redirect(w, r, authUrl, http.StatusFound) }) demo.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { provider, err := gomniauth.Provider(clientCfg.ProviderName) if err != nil { panic(err) } omap, err := objx.FromURLQuery(r.URL.RawQuery) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } creds, err := provider.CompleteAuth(omap) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } /* // This code borrowed from goweb example and not fixed. // get the state state, err := gomniauth.StateFromParam(ctx.QueryValue("state")) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // redirect to the 'after' URL afterUrl := state.GetStringOrDefault("after", "error?e=No after parameter was set in the state") */ // load the user user, userErr := provider.GetUser(creds) if userErr != nil { http.Error(w, userErr.Error(), http.StatusInternalServerError) return } rst := make(map[string]interface{}) rst["name"] = user.Name() rst["email"] = user.Email() json.NewEncoder(w).Encode(rst) // redirect //return goweb.Respond.WithRedirect(ctx, afterUrl) }) go http.ListenAndServe(":8000", s) log.Println(" visit server at " + demoserver + "/login") log.Fatal(http.ListenAndServe(":8001", demo)) }