github.com/Richardknop/go-oauth2-server@v1.0.1/web/login.go (about) 1 package web 2 3 import ( 4 "net/http" 5 6 "github.com/RichardKnop/go-oauth2-server/session" 7 ) 8 9 func (s *Service) loginForm(w http.ResponseWriter, r *http.Request) { 10 // Get the session service from the request context 11 sessionService, err := getSessionService(r) 12 if err != nil { 13 http.Error(w, err.Error(), http.StatusInternalServerError) 14 return 15 } 16 17 // Render the template 18 errMsg, _ := sessionService.GetFlashMessage() 19 renderTemplate(w, "login.html", map[string]interface{}{ 20 "error": errMsg, 21 "queryString": getQueryString(r.URL.Query()), 22 }) 23 } 24 25 func (s *Service) login(w http.ResponseWriter, r *http.Request) { 26 // Get the session service from the request context 27 sessionService, err := getSessionService(r) 28 if err != nil { 29 http.Error(w, err.Error(), http.StatusInternalServerError) 30 return 31 } 32 33 // Get the client from the request context 34 client, err := getClient(r) 35 if err != nil { 36 http.Error(w, err.Error(), http.StatusBadRequest) 37 return 38 } 39 40 // Authenticate the user 41 user, err := s.oauthService.AuthUser( 42 r.Form.Get("email"), // username 43 r.Form.Get("password"), // password 44 ) 45 if err != nil { 46 sessionService.SetFlashMessage(err.Error()) 47 http.Redirect(w, r, r.RequestURI, http.StatusFound) 48 return 49 } 50 51 // Get the scope string 52 scope, err := s.oauthService.GetScope(r.Form.Get("scope")) 53 if err != nil { 54 sessionService.SetFlashMessage(err.Error()) 55 http.Redirect(w, r, r.RequestURI, http.StatusFound) 56 return 57 } 58 59 // Log in the user 60 accessToken, refreshToken, err := s.oauthService.Login( 61 client, 62 user, 63 scope, 64 ) 65 if err != nil { 66 sessionService.SetFlashMessage(err.Error()) 67 http.Redirect(w, r, r.RequestURI, http.StatusFound) 68 return 69 } 70 71 // Log in the user and store the user session in a cookie 72 userSession := &session.UserSession{ 73 ClientID: client.Key, 74 Username: user.Username, 75 AccessToken: accessToken.Token, 76 RefreshToken: refreshToken.Token, 77 } 78 if err := sessionService.SetUserSession(userSession); err != nil { 79 sessionService.SetFlashMessage(err.Error()) 80 http.Redirect(w, r, r.RequestURI, http.StatusFound) 81 return 82 } 83 84 // Redirect to the authorize page by default but allow redirection to other 85 // pages by specifying a path with login_redirect_uri query string param 86 loginRedirectURI := r.URL.Query().Get("login_redirect_uri") 87 if loginRedirectURI == "" { 88 loginRedirectURI = "/web/admin" 89 } 90 redirectWithQueryString(loginRedirectURI, r.URL.Query(), w, r) 91 }