-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathauth.go
298 lines (247 loc) · 7.19 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/gob"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"path/filepath"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var conf *oauth2.Config
var store *sessions.CookieStore
// User is a Google user
type User struct {
Name string `json:"name"`
GivenName string `json:"given_name"`
FamilyName string `json:"family_name"`
Email string `json:"email"`
Picture string `json:"picture"`
}
// GroupMember defines whether the user is a member of a group
// It is set by the groups `hasMember` API endpoint
type GroupMember struct {
IsMember bool `json:"isMember"`
}
func init() {
gob.Register(User{})
}
func oauthConfig() {
keyFile := filepath.Join(dataDir, ".cookie_key")
if key, err := ioutil.ReadFile(keyFile); err == nil {
store = sessions.NewCookieStore(key)
} else {
// TODO(jamesog): Add a second parameter for encryption
// This makes it more complicated to write to the cache file
// It should probably be saved in the database instead
key := securecookie.GenerateRandomKey(64)
err := ioutil.WriteFile(keyFile, key, 0600)
if err != nil {
log.Fatal(err)
}
store = sessions.NewCookieStore(key)
}
f, err := ioutil.ReadFile(credsFile)
if err != nil {
log.Fatalf("couldn't read credentials file: %s", err)
}
scopes := []string{
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/admin.directory.group.member.readonly",
}
conf, err = google.ConfigFromJSON(f, scopes...)
if err != nil {
log.Fatalf("couldn't parse OAuth2 config: %s", err)
}
}
func getLoginURL(state string) string {
return conf.AuthCodeURL(state)
}
func randToken() string {
b := make([]byte, 32)
rand.Read(b)
return base64.StdEncoding.EncodeToString(b)
}
// loginHandler is just a redirect to the Google login page
func (app *App) loginHandler(w http.ResponseWriter, r *http.Request) {
tok := randToken()
state, err := store.Get(r, "state")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// State only needs to be valid for 5 mins
state.Options.MaxAge = 300
state.Values["state"] = tok
// Store a redirect URL to send the user back to the page they were on
redir, _ := store.Get(r, "redir")
redir.Options.MaxAge = 300
redir.Values["redir"] = r.URL.Query().Get("redir")
// Save both sessions
sessions.Save(r, w)
http.Redirect(w, r, getLoginURL(tok), http.StatusFound)
}
func (app *App) logoutHandler(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "user")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
v := session.Values["user"]
if user, ok := v.(User); ok {
app.audit(user.Email, "logout", "")
}
session.Options.MaxAge = -1
session.Save(r, w)
// User is logged out. Redirect back to the index page
http.Redirect(w, r, "/", http.StatusFound)
}
// AuthSession stores the session and OAuth2 client
type AuthSession struct {
state *sessions.Session
user *sessions.Session
token *oauth2.Token
client *http.Client
}
type googleAPIError struct {
Error struct {
Message string `json:"message"`
Code int `json:"code"`
} `json:"error"`
}
// userInfo fetches the user profile info from the Google API
func (s AuthSession) userInfo() (*User, error) {
// Retrieve the logged in user's information
res, err := s.client.Get("https://www.googleapis.com/oauth2/v3/userinfo")
if err != nil {
return nil, err
}
defer res.Body.Close()
data, _ := ioutil.ReadAll(res.Body)
// Unmarshal the user data
var user User
err = json.Unmarshal(data, &user)
if err != nil {
return nil, err
}
return &user, nil
}
// validateUser looks up the user's email address in the database and returns
// true if they exist
func (app *App) validateUser(user *User) (bool, error) {
return app.db.UserExists(user.Email)
}
// validateGroupMember looks up all group names in the database and returns
// true if the user is a member of any of the groups
func (app *App) validateGroupMember(s AuthSession, email string) (bool, error) {
url := "https://www.googleapis.com/admin/directory/v1/groups/%s/hasMember/%s"
groups, err := app.db.LoadGroups()
if err != nil {
log.Printf("error retrieving groups from database: %v", err)
return false, err
}
for _, group := range groups {
res, err := s.client.Get(fmt.Sprintf(url, group, email))
if err != nil {
log.Printf("error retrieving user %s for group %s: %v", email, group, err)
continue
}
defer res.Body.Close()
data, _ := ioutil.ReadAll(res.Body)
if res.StatusCode != http.StatusOK {
var e googleAPIError
err := json.Unmarshal(data, &e)
if err != nil {
log.Printf("[group %s] error unmarshaling Google API error: %v", group, err)
continue
}
log.Printf("[group %s] error code %d from groups API: %v", group, e.Error.Code, e.Error.Message)
continue
}
var gm GroupMember
err = json.Unmarshal(data, &gm)
if err != nil {
return false, err
}
if gm.IsMember {
return true, nil
}
}
return false, nil
}
// authHandler receives the login information from Google and checks if the
// email address is authorized
func (app *App) authHandler(w http.ResponseWriter, r *http.Request) {
var s AuthSession
var err error
s.state, err = store.Get(r, "state")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Check if the user has a valid session
q := r.URL.Query()
if s.state.Values["state"] != q.Get("state") {
http.Error(w, "Invalid session", http.StatusUnauthorized)
return
}
// Attempt to fetch the redirect URI from the store
uri := "/"
redir, _ := store.Get(r, "redir")
if u := redir.Values["redir"]; u != "" {
uri = u.(string)
}
// Destroy the redirect session, it isn't needed any more
redir.Options.MaxAge = -1
redir.Save(r, w)
s.user, err = store.Get(r, "user")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.token, err = conf.Exchange(context.Background(), q.Get("code"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.client = conf.Client(context.Background(), s.token)
var authorised bool
// Check if the user email is in the individual users list
// If the individual user is not authorised, check group membership
user, err := s.userInfo()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
authorised, err = app.validateUser(user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// The user doesn't have an individual entry, check group membership
if !authorised {
authorised, err = app.validateGroupMember(s, user.Email)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if authorised {
// Store the information in the session
s.user.Values["user"] = user
} else {
s.user.AddFlash(fmt.Sprintf("%s is not authorised", user.Email), "unauth_flash")
}
s.user.Save(r, w)
app.audit(user.Email, "login", "")
// User is logged in. Redirect back to the index page
http.Redirect(w, r, uri, http.StatusFound)
}