forked from RichardKnop/go-oauth2-server
/
login.go
99 lines (87 loc) · 2.52 KB
/
login.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package web
import (
"net/http"
"github.com/RichardKnop/go-oauth2-server/session"
)
func loginForm(w http.ResponseWriter, r *http.Request) {
// Get the session service from the request context
sessionService, err := getSessionService(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Render the template
renderTemplate(w, "login.html", map[string]interface{}{
"error": sessionService.GetFlashMessage(),
"queryString": getQueryString(r.URL.Query()),
})
}
func login(w http.ResponseWriter, r *http.Request) {
// Get the session service from the request context
sessionService, err := getSessionService(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Authenticate the user
user, err := theService.oauthService.AuthUser(
r.Form.Get("email"), // username
r.Form.Get("password"), // password
)
if err != nil {
sessionService.SetFlashMessage(err.Error())
http.Redirect(w, r, r.RequestURI, http.StatusFound)
return
}
// Get the scope string
scope, err := theService.oauthService.GetScope(r.Form.Get("scope"))
if err != nil {
sessionService.SetFlashMessage(err.Error())
http.Redirect(w, r, r.RequestURI, http.StatusFound)
return
}
// Fetch the trusted client
client, err := theService.oauthService.FindClientByClientID(
theService.cnf.TrustedClient.ClientID,
)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Grant an access token
accessToken, err := theService.oauthService.GrantAccessToken(
client, // client
user, // user
scope, // scope
)
if err != nil {
sessionService.SetFlashMessage(err.Error())
http.Redirect(w, r, r.RequestURI, http.StatusFound)
return
}
// Get a refresh token
refreshToken, err := theService.oauthService.GetOrCreateRefreshToken(
client, // client
user, // user
scope, // scope
)
if err != nil {
sessionService.SetFlashMessage(err.Error())
http.Redirect(w, r, r.RequestURI, http.StatusFound)
return
}
// Log in the user and store the user session in a cookie
userSession := &session.UserSession{
ClientID: client.ClientID,
Username: user.Username,
AccessToken: accessToken.Token,
RefreshToken: refreshToken.Token,
}
if err := sessionService.SetUserSession(userSession); err != nil {
sessionService.SetFlashMessage(err.Error())
http.Redirect(w, r, r.RequestURI, http.StatusFound)
return
}
// Redirect to the authorize page
redirectWithQueryString("/web/authorize", r.URL.Query(), w, r)
}