-
Notifications
You must be signed in to change notification settings - Fork 2
/
auth.go
188 lines (158 loc) · 5.12 KB
/
auth.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"context"
"encoding/gob"
"errors"
"net/http"
"net/url"
uuid "github.com/gofrs/uuid"
"github.com/goh-chunlin/GoLab/util"
"golang.org/x/oauth2"
plus "google.golang.org/api/plus/v1"
)
const (
defaultSessionID = "default"
// The following keys are used for the default session. For example:
googleProfileSessionKey = "google_profile"
oauthTokenSessionKey = "oauth_token"
// This key is used in the OAuth flow session to store the URL to redirect the
// user to after the OAuth flow is complete.
oauthFlowRedirectKey = "redirect"
)
// This flag is for the use of unit testing to do fake login
var isTesting bool
func init() {
// Gob encoding for gorilla/sessions
gob.Register(&oauth2.Token{})
gob.Register(&Profile{})
}
func handleLoginRequest(writer http.ResponseWriter, request *http.Request) {
sessionID := uuid.Must(uuid.NewV4()).String()
oauthFlowSession, err := SessionStore.New(request, sessionID)
util.CheckError(err)
oauthFlowSession.Options.MaxAge = 3600 // 1 hour, i.e. 3,600 seconds
oauthFlowSession.Values[oauthFlowRedirectKey] = "/player"
if err := oauthFlowSession.Save(request, writer); err != nil {
util.CheckError(err)
}
// Use the session ID for the "state" parameter.
// This protects against CSRF (cross-site request forgery).
// See https://godoc.org/golang.org/x/oauth2#Config.AuthCodeURL for more detail.
authCodeURL := OAuthConfig.AuthCodeURL(sessionID, oauth2.ApprovalForce,
oauth2.AccessTypeOnline)
http.Redirect(writer, request, authCodeURL, http.StatusFound)
}
// handleLogoutRequest clears the default session.
func handleLogoutRequest(writer http.ResponseWriter, request *http.Request) {
session, err := SessionStore.New(request, defaultSessionID)
if err != nil {
util.CheckError(err)
}
session.Options.MaxAge = -1 // Clear session.
if err := session.Save(request, writer); err != nil {
util.CheckError(err)
}
redirectURL := request.FormValue("redirect")
if redirectURL == "" {
redirectURL = "/"
}
http.Redirect(writer, request, redirectURL, http.StatusFound)
}
// validateRedirectURL checks that the URL provided is valid.
// If the URL is missing, redirect the user to the application's root.
// The URL must not be absolute (i.e., the URL must refer to a path within this
// application).
func validateRedirectURL(path string) (string, error) {
if path == "" {
return "/", nil
}
// Ensure redirect URL is valid and not pointing to a different server.
parsedURL, err := url.Parse(path)
if err != nil {
return "/", err
}
if parsedURL.IsAbs() {
return "/", errors.New("URL must not be absolute")
}
return path, nil
}
// oauthCallbackHandler completes the OAuth flow, retreives the user's profile
// information and stores it in a session.
func oauthCallbackHandler(writer http.ResponseWriter, request *http.Request) {
oauthFlowSession, err := SessionStore.Get(request, request.FormValue("state"))
if err != nil {
util.CheckError(err)
}
redirectURL, ok := oauthFlowSession.Values[oauthFlowRedirectKey].(string)
// Validate this callback request came from the app.
if !ok {
util.CheckError(err)
}
code := request.FormValue("code")
tok, err := OAuthConfig.Exchange(context.Background(), code)
if err != nil {
util.CheckError(err)
}
session, err := SessionStore.New(request, defaultSessionID)
if err != nil {
util.CheckError(err)
}
ctx := context.Background()
profile, err := fetchProfile(ctx, tok)
if err != nil {
util.CheckError(err)
}
session.Values[oauthTokenSessionKey] = tok
// Strip the profile to only the fields we need. Otherwise the struct is too big.
session.Values[googleProfileSessionKey] = stripProfile(profile)
if err := session.Save(request, writer); err != nil {
util.CheckError(err)
}
http.Redirect(writer, request, redirectURL, http.StatusFound)
}
// fetchProfile retrieves the Google+ profile of the user associated with the
// provided OAuth token.
func fetchProfile(ctx context.Context, tok *oauth2.Token) (*plus.Person, error) {
client := oauth2.NewClient(ctx, OAuthConfig.TokenSource(ctx, tok))
plusService, err := plus.New(client)
if err != nil {
return nil, err
}
return plusService.People.Get("me").Do()
}
// profileFromSession retreives the Google+ profile from the default session.
// Returns nil if the profile cannot be retreived (e.g. user is logged out).
func profileFromSession(request *http.Request) *Profile {
if isTesting {
return &Profile{
ID: "154226945598527500122",
DisplayName: "Chun Lin",
ImageURL: "https://avatars1.githubusercontent.com/u/8535306?s=460&v=4",
}
}
session, err := SessionStore.Get(request, defaultSessionID)
if err != nil {
return nil
}
tok, ok := session.Values[oauthTokenSessionKey].(*oauth2.Token)
if !ok || !tok.Valid() {
return nil
}
profile, ok := session.Values[googleProfileSessionKey].(*Profile)
if !ok {
return nil
}
return profile
}
// Profile is the user profile of logged in user
type Profile struct {
ID, DisplayName, ImageURL string
}
// stripProfile returns a subset of a plus.Person.
func stripProfile(p *plus.Person) *Profile {
return &Profile{
ID: p.Id,
DisplayName: p.DisplayName,
ImageURL: p.Image.Url,
}
}