/
auth_firestore.go
297 lines (281 loc) · 8.76 KB
/
auth_firestore.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
package identity
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"log"
"cloud.google.com/go/firestore"
"google.golang.org/api/iterator"
)
// fsClient defines Firestore interfaces needed
type fsClient interface {
Collection(path string) *firestore.CollectionRef
}
// Implements the Authenticator interface with a Firestore client
type authenticatorFS struct {
client fsClient
corpus string
}
// Create a new Authenticator with a Firestore client
func NewAuthenticator(client fsClient, corpus string) Authenticator {
return authenticatorFS{
client: client,
corpus: corpus,
}
}
func (a authenticatorFS) ChangePassword(ctx context.Context, userInfo UserInfo, oldPassword, password string) ChangePasswordResult {
log.Printf("ChangePassword for user, %s", userInfo.UserName)
uPath := a.corpus + "_users"
colRef := a.client.Collection(uPath)
user := colRef.Doc(userInfo.UserName)
users, err := a.CheckLogin(ctx, userInfo.UserName, oldPassword)
if err != nil {
log.Printf("ChangePassword error checking login for %s: %v", userInfo.UserName, err)
return ChangePasswordResult{
OldPasswordValid: true,
ChangeSuccessful: false,
ShowNewForm: false,
}
}
if len(users) != 1 {
log.Printf("ChangePassword, user or password wrong for %s", userInfo.UserName)
return ChangePasswordResult{
OldPasswordValid: false,
ChangeSuccessful: false,
ShowNewForm: false,
}
}
h := sha256.New()
h.Write([]byte(password))
hstr := fmt.Sprintf("%x", h.Sum(nil))
_, err = user.Update(ctx, []firestore.Update{{Path: "password", Value: hstr}})
if err != nil {
log.Printf("ChangePassword, Error setting password for %s: %v", userInfo.UserName, err)
return ChangePasswordResult{
OldPasswordValid: true,
ChangeSuccessful: false,
ShowNewForm: false,
}
}
log.Printf("ChangePassword, successful for %s", userInfo.UserName)
return ChangePasswordResult{
OldPasswordValid: true,
ChangeSuccessful: true,
ShowNewForm: false,
}
}
func (a authenticatorFS) CheckLogin(ctx context.Context, username, password string) ([]UserInfo, error) {
log.Printf("CheckLogin for username %s in corpus %s", username, a.corpus)
uPath := a.corpus + "_users"
if a.client == nil {
log.Println("CheckLogin, Firestore client is nil")
return nil, fmt.Errorf("server not configured")
}
colRef := a.client.Collection(uPath)
if colRef == nil {
log.Println("CheckLogin, colRef is nil")
return nil, fmt.Errorf("server not configured")
}
docRef := colRef.Doc(username)
var user UserInfo
doc, err := docRef.Get(ctx)
if err != nil {
return nil, err
}
if err := doc.DataTo(&user); err != nil {
return nil, err
}
h := sha256.New()
h.Write([]byte(password))
hstr := fmt.Sprintf("%x", h.Sum(nil))
if user.Password != hstr {
log.Printf("CheckLogin, username %s, password %s does not match", username, hstr)
return []UserInfo{}, nil
}
return []UserInfo{user}, nil
}
func (a authenticatorFS) CheckSession(ctx context.Context, sessionid string) SessionInfo {
log.Printf("CheckSession, sessionid: %s\n", sessionid)
uPath := a.corpus + "_sessions"
colRef := a.client.Collection(uPath)
docRef := colRef.Doc(sessionid)
doc, err := docRef.Get(ctx)
if err != nil {
return SessionInfo{}
}
var sessionRecord SessionRecord
if err := doc.DataTo(&sessionRecord); err != nil {
return SessionInfo{}
}
return SessionInfo{
Authenticated: sessionRecord.Authenticated,
Valid: sessionRecord.Valid,
User: UserInfo{
UserName: sessionRecord.UserName,
},
}
}
func (a authenticatorFS) GetUser(ctx context.Context, username string) ([]UserInfo, error) {
log.Println("GetUser, username:", username)
uPath := a.corpus + "_users"
colRef := a.client.Collection(uPath)
docRef := colRef.Doc(username)
var user UserInfo
doc, err := docRef.Get(ctx)
if err != nil {
return nil, err
}
if err := doc.DataTo(&user); err != nil {
return nil, err
}
return []UserInfo{user}, nil
}
func (a authenticatorFS) Logout(ctx context.Context, sessionid string) {
log.Printf("Logout, sessionid: %s\n", sessionid)
uPath := a.corpus + "_sessions"
colRef := a.client.Collection(uPath)
docRef := colRef.Doc(sessionid)
_, err := docRef.Delete(ctx)
if err != nil {
log.Printf("CheckSession, error logging out for sessionid: %s\n", sessionid)
}
}
func (a authenticatorFS) RequestPasswordReset(ctx context.Context, email string) RequestResetResult {
log.Printf("RequestPasswordReset, email: %s\n", email)
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
log.Printf("RequestPasswordReset, Error: %v", err)
return RequestResetResult{true, false, true, InvalidUser(), ""}
}
token, err := base64.URLEncoding.EncodeToString(b), err
if err != nil {
log.Println("RequestPasswordReset, Error: ", err)
return RequestResetResult{true, false, true, InvalidUser(), ""}
}
user, err := a.getUserByEmail(ctx, email)
if err != nil {
log.Println("RequestPasswordReset, Error: ", err)
return RequestResetResult{true, false, true, InvalidUser(), ""}
}
rPath := a.corpus + "_resets"
colRef := a.client.Collection(rPath)
docRef := colRef.Doc(token)
_, err = docRef.Set(ctx, RequestResetRecord{
EmailValid: true,
RequestResetSuccess: true,
Email: email,
UserName: user.UserName,
Token: token,
})
if err != nil {
log.Printf("RequestPasswordReset, error setting record for email %s\n", email)
return RequestResetResult{true, false, true, InvalidUser(), ""}
}
return RequestResetResult{
EmailValid: true,
RequestResetSuccess: true,
ShowNewForm: false,
User: user,
Token: token,
}
}
func (a authenticatorFS) ResetPassword(ctx context.Context, token, password string) bool {
log.Println("ResetPassword, token:", token)
rPath := a.corpus + "_resets"
colRef := a.client.Collection(rPath)
docRef := colRef.Doc(token)
doc, err := docRef.Get(ctx)
if err != nil {
log.Printf("ResetPassword, error looking up token %s\n", token)
return false
}
var rRecord RequestResetRecord
if err := doc.DataTo(&rRecord); err != nil {
log.Printf("ResetPassword, error reading request record for %s\n", token)
return false
}
if !rRecord.EmailValid {
log.Printf("ResetPassword, Request record is not valid for %s\n", token)
return false
}
uPath := a.corpus + "_users"
uColRef := a.client.Collection(uPath)
uDocRef := uColRef.Doc(rRecord.UserName)
uDoc, err := uDocRef.Get(ctx)
if err != nil {
log.Printf("ResetPassword error getting user record for %s:, %v", rRecord.UserName, err)
return false
}
var user UserInfo
if err := uDoc.DataTo(&user); err != nil {
log.Printf("ResetPassword, error reading user record for %s: %v\n", rRecord.UserName, err)
return false
}
h := sha256.New()
h.Write([]byte(password))
hstr := fmt.Sprintf("%x", h.Sum(nil))
_, err = uDocRef.Update(ctx, []firestore.Update{{Path: "password", Value: hstr}})
if err != nil {
log.Printf("ResetPassword, error setting password for %s: %v\n", rRecord.UserName, err)
return false
}
_, err = docRef.Update(ctx, []firestore.Update{{Path: "EmailValid", Value: false}})
if err != nil {
log.Printf("ResetPassword, error updating EmailValid for %s: %v\n", rRecord.UserName, err)
return false
}
log.Println("ResetPassword, successful")
return true
}
func (a authenticatorFS) SaveSession(ctx context.Context, sessionid string, userInfo UserInfo, authenticated int) SessionInfo {
log.Printf("SaveSession, sessionid: %s\n", sessionid)
uPath := a.corpus + "_sessions"
colRef := a.client.Collection(uPath)
docRef := colRef.Doc(sessionid)
_, err := docRef.Set(ctx, SessionRecord{
Authenticated: 1,
Valid: true,
UserName: userInfo.UserName,
})
if err != nil {
log.Printf("SaveSession, error saving session for sessionid: %s, user: %s\n", sessionid, userInfo.UserName)
return SessionInfo{}
}
return SessionInfo{
Authenticated: 1,
Valid: true,
User: userInfo,
}
}
func (a authenticatorFS) UpdateSession(ctx context.Context, sessionid string, userInfo UserInfo, authenticated int) SessionInfo {
return a.SaveSession(ctx, sessionid, userInfo, authenticated)
}
func (a authenticatorFS) getUserByEmail(ctx context.Context, email string) (UserInfo, error) {
log.Printf("getUserByEmail, email: %s", email)
uPath := a.corpus + "_users"
colRef := a.client.Collection(uPath)
q := colRef.Where("email", "==", email).Limit(100)
iter := q.Documents(ctx)
defer iter.Stop()
for {
ds, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
return UserInfo{}, fmt.Errorf("getUserByEmail iteration error: %v", err)
}
var d UserInfo
err = ds.DataTo(&d)
if err != nil {
return UserInfo{}, fmt.Errorf("getUserByEmail type conversion error: %v", err)
}
if len(d.UserName) > 0 {
return d, nil
}
}
return UserInfo{}, fmt.Errorf("user not found for email: %s", email)
}