forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.go
190 lines (163 loc) · 5.71 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
189
190
// Copyright 2015 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"encoding/gob"
"errors"
"net/http"
"net/url"
plus "google.golang.org/api/plus/v1"
"golang.org/x/net/context"
"golang.org/x/oauth2"
"github.com/GoogleCloudPlatform/golang-samples/getting-started/bookshelf"
uuid "github.com/satori/go.uuid"
)
const (
defaultSessionID = "default"
// The following keys are used for the default session. For example:
// session, _ := bookshelf.SessionStore.New(r, defaultSessionID)
// session.Values[oauthTokenSessionKey]
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"
)
func init() {
// Gob encoding for gorilla/sessions
gob.Register(&oauth2.Token{})
gob.Register(&Profile{})
}
// loginHandler initiates an OAuth flow to authenticate the user.
func loginHandler(w http.ResponseWriter, r *http.Request) *appError {
sessionID := uuid.Must(uuid.NewV4()).String()
oauthFlowSession, err := bookshelf.SessionStore.New(r, sessionID)
if err != nil {
return appErrorf(err, "could not create oauth session: %v", err)
}
oauthFlowSession.Options.MaxAge = 10 * 60 // 10 minutes
redirectURL, err := validateRedirectURL(r.FormValue("redirect"))
if err != nil {
return appErrorf(err, "invalid redirect URL: %v", err)
}
oauthFlowSession.Values[oauthFlowRedirectKey] = redirectURL
if err := oauthFlowSession.Save(r, w); err != nil {
return appErrorf(err, "could not save session: %v", 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.
url := bookshelf.OAuthConfig.AuthCodeURL(sessionID, oauth2.ApprovalForce,
oauth2.AccessTypeOnline)
http.Redirect(w, r, url, http.StatusFound)
return nil
}
// 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(w http.ResponseWriter, r *http.Request) *appError {
oauthFlowSession, err := bookshelf.SessionStore.Get(r, r.FormValue("state"))
if err != nil {
return appErrorf(err, "invalid state parameter. try logging in again.")
}
redirectURL, ok := oauthFlowSession.Values[oauthFlowRedirectKey].(string)
// Validate this callback request came from the app.
if !ok {
return appErrorf(err, "invalid state parameter. try logging in again.")
}
code := r.FormValue("code")
tok, err := bookshelf.OAuthConfig.Exchange(context.Background(), code)
if err != nil {
return appErrorf(err, "could not get auth token: %v", err)
}
session, err := bookshelf.SessionStore.New(r, defaultSessionID)
if err != nil {
return appErrorf(err, "could not get default session: %v", err)
}
ctx := context.Background()
profile, err := fetchProfile(ctx, tok)
if err != nil {
return appErrorf(err, "could not fetch Google profile: %v", 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(r, w); err != nil {
return appErrorf(err, "could not save session: %v", err)
}
http.Redirect(w, r, redirectURL, http.StatusFound)
return nil
}
// 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, bookshelf.OAuthConfig.TokenSource(ctx, tok))
plusService, err := plus.New(client)
if err != nil {
return nil, err
}
return plusService.People.Get("me").Do()
}
// logoutHandler clears the default session.
func logoutHandler(w http.ResponseWriter, r *http.Request) *appError {
session, err := bookshelf.SessionStore.New(r, defaultSessionID)
if err != nil {
return appErrorf(err, "could not get default session: %v", err)
}
session.Options.MaxAge = -1 // Clear session.
if err := session.Save(r, w); err != nil {
return appErrorf(err, "could not save session: %v", err)
}
redirectURL := r.FormValue("redirect")
if redirectURL == "" {
redirectURL = "/"
}
http.Redirect(w, r, redirectURL, http.StatusFound)
return nil
}
// 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(r *http.Request) *Profile {
session, err := bookshelf.SessionStore.Get(r, 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
}
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,
}
}