-
Notifications
You must be signed in to change notification settings - Fork 8
/
userstore.go
427 lines (365 loc) · 9.3 KB
/
userstore.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package auth
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"text/template"
"time"
dgo "github.com/dgraph-io/dgo/v2"
"github.com/gocontrib/auth"
"github.com/sergeyt/pandora/modules/dgraph"
"github.com/sergeyt/pandora/modules/orderedjson"
log "github.com/sirupsen/logrus"
)
var templateCache = make(map[string]*template.Template)
func execTemplate(name, source string, data interface{}) string {
t, ok := templateCache[name]
if !ok {
t = template.Must(template.New(name).Parse(source))
templateCache[name] = t
}
var out bytes.Buffer
err := t.Execute(&out, data)
if err != nil {
panic(err)
}
return out.String()
}
func makeUserStore() *userStore {
return &userStore{}
}
type userStore struct {
}
type templateParams struct {
Label string
}
var baseParams = &templateParams{Label: userLabel()}
func (s *userStore) ValidateCredentials(ctx context.Context, username, password string) (auth.User, error) {
// TODO detect phone and normalize it
const src = `query users($username: string, $password: string) {
users(func: has(User)) @filter(eq(email, $username) OR eq(login, $username) OR eq(phone, $username)) {
uid
name
email
role
checkpwd(password, $password)
}
}`
query := execTemplate("ValidateCredentials", src, baseParams)
vars := map[string]string{
"$username": username,
"$password": password,
}
return s.FindUser(ctx, query, vars, username, true)
}
func (s *userStore) findUserByName(ctx context.Context, txn *dgo.Txn, username string) (auth.User, error) {
const src = `query users($username: string) {
users(func: has(User)) @filter(eq(email, $username) OR eq(login, $username) OR eq(phone, $username)) {
uid
name
email
role
}
}`
query := execTemplate("FindUserByName", src, baseParams)
vars := map[string]string{
"$username": username,
}
return s.findUserImpl(ctx, txn, query, vars, username, true)
}
func (s *userStore) FindUserByEmail(ctx context.Context, email string) (auth.User, error) {
src := `query users($id: string) {
users(func: has(User)) @filter(eq(email, $id)) {
uid
name
email
role
}
}`
query := execTemplate("FindUserByEmail", src, baseParams)
vars := map[string]string{
"$id": email,
}
return s.FindUser(ctx, query, vars, email, false)
}
func (s *userStore) FindUserByID(ctx context.Context, userID string) (auth.User, error) {
src := `query users($id: string) {
users(func: uid($id)) @filter(has(User)) {
uid
name
email
role
}
}`
query := execTemplate("FindUserByID", src, baseParams)
vars := map[string]string{
"$id": userID,
}
return s.FindUser(ctx, query, vars, userID, false)
}
func userLabel() string {
return dgraph.NodeLabel("user")
}
func (s *userStore) Close() {
}
func (s *userStore) FindUser(ctx context.Context, query string, vars map[string]string, userID string, checkPwd bool) (auth.User, error) {
dg, close, err := dgraph.NewClient(ctx)
if err != nil {
return nil, err
}
defer close()
txn := dg.NewTxn()
defer dgraph.Discard(ctx, txn)
return s.findUserImpl(ctx, txn, query, vars, userID, checkPwd)
}
func (s *userStore) findUserImpl(ctx context.Context, txn *dgo.Txn, query string, vars map[string]string, userID string, checkPwd bool) (auth.User, error) {
resp, err := txn.QueryWithVars(ctx, query, vars)
if err != nil {
log.Errorf("dgraph.Txn.QueryWithVars fail: %v", err)
return nil, err
}
var result struct {
Users []struct {
ID string `json:"uid"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
CheckPwd *bool `json:"checkpwd(password)"`
} `json:"users"`
}
err = json.Unmarshal(resp.GetJson(), &result)
if err != nil {
log.Errorf("json.Unmarshal fail: %v", err)
return nil, err
}
if len(result.Users) == 0 {
return nil, fmt.Errorf("user not found by %s", userID)
}
user := result.Users[0]
if checkPwd && user.CheckPwd != nil && !*user.CheckPwd {
return nil, fmt.Errorf("wrong password: %s", userID)
}
return &auth.UserInfo{
ID: user.ID,
Name: user.Name,
Email: user.Email,
Admin: isAdmin(user.Role),
Claims: map[string]interface{}{
"email": user.Email,
"role": user.Role,
},
}, nil
}
func isAdmin(role string) bool {
roles := splitRoles(role)
isAdmin := false
for _, r := range roles {
if r == "admin" {
isAdmin = true
break
}
}
return isAdmin
}
func splitRoles(s string) []string {
s = strings.TrimSpace(s)
if len(s) == 0 {
return []string{}
}
parts := strings.Split(s, ",")
result := make([]string, 0)
for _, p := range parts {
t := strings.TrimSpace(p)
if len(t) > 0 {
result = append(result, strings.ToLower(t))
}
}
return result
}
func (s *userStore) CreateUser(ctx context.Context, account auth.UserData) (auth.User, error) {
if account.Email == "" {
return nil, fmt.Errorf("user.email is not defined")
}
if account.Name == "" {
account.Name = account.FirstName
if account.LastName != "" {
account.Name += " " + account.LastName
}
}
if account.NickName == "" {
account.NickName = account.Name
}
if account.Name == "" {
return nil, fmt.Errorf("user.name is not defined")
}
dg, close, err := dgraph.NewClient(ctx)
if err != nil {
return nil, err
}
defer close()
tx := dg.NewTxn()
defer dgraph.Discard(ctx, tx)
u, err := s.findUserByName(ctx, tx, account.Email)
if u != nil {
return nil, fmt.Errorf("user with email %s already registered", account.Email)
}
// TODO generate unique login
in := make(orderedjson.Map)
in["name"] = account.Name
in["login"] = account.NickName
in["first_name"] = account.FirstName
in["last_name"] = account.LastName
in["email"] = account.Email
in["avatar"] = account.AvatarURL
in["location"] = account.Location
in["registered_at"] = time.Now()
in["password"] = account.Password
results, err := dgraph.Mutate(ctx, tx, dgraph.Mutation{
Input: in,
NodeLabel: userLabel(),
By: "system",
NoCommit: true,
})
if err != nil {
return nil, err
}
user := mapUser(results[0])
// create account for given oauth provider
if account.Provider != "" {
in = makeAccount(account)
in["registered_at"] = time.Now()
results, err = dgraph.Mutate(ctx, tx, dgraph.Mutation{
Input: in,
NodeLabel: dgraph.NodeLabel("account"),
By: "system",
NoCommit: true,
})
if err != nil {
return nil, err
}
// link account with user record
acc := results[0]
accountID := getString(acc, "uid")
err = linkAccount(ctx, tx, user.ID, accountID)
if err != nil {
return nil, err
}
}
err = tx.Commit(ctx)
if err != nil {
log.Errorf("dgraph.Txn.Commit fail: %v", err)
return nil, err
}
return user, nil
}
func linkAccount(ctx context.Context, tx *dgo.Txn, userID, accountID string) error {
in := make(orderedjson.Map)
in["account"] = map[string]interface{}{
"uid": accountID,
}
_, err := dgraph.Mutate(ctx, tx, dgraph.Mutation{
Input: in,
NodeLabel: userLabel(),
ID: userID,
By: "system",
NoCommit: true,
})
return err
}
func (s *userStore) UpdateAccount(ctx context.Context, user auth.User, data auth.UserData) error {
dg, close, err := dgraph.NewClient(ctx)
if err != nil {
return err
}
defer close()
tx := dg.NewTxn()
defer dgraph.Discard(ctx, tx)
query := `query accounts($provider: string, $email: string) {
accounts(func: has(Account)) @filter(eq(provider, $provider) AND eq(email, $email)) {
uid
}
}`
vars := map[string]string{
"$provider": data.Provider,
"$email": data.Email,
}
resp, err := tx.QueryWithVars(ctx, query, vars)
if err != nil {
log.Errorf("dgraph.Txn.QueryWithVars fail: %v", err)
return err
}
var result struct {
Accounts []struct {
ID string `json:"uid"`
} `json:"accounts"`
}
err = json.Unmarshal(resp.GetJson(), &result)
if err != nil {
log.Errorf("json.Unmarshal fail: %v", err)
return err
}
accountID := ""
if len(result.Accounts) > 0 {
accountID = result.Accounts[0].ID
}
in := makeAccount(data)
if len(accountID) == 0 {
in["registered_at"] = time.Now()
}
results, err := dgraph.Mutate(ctx, tx, dgraph.Mutation{
Input: in,
NodeLabel: dgraph.NodeLabel("account"),
ID: accountID,
By: "system",
NoCommit: true,
})
if err != nil {
return err
}
// link account with user record
acc := results[0]
accountID = getString(acc, "uid")
return linkAccount(ctx, tx, user.GetID(), accountID)
}
func makeAccount(account auth.UserData) orderedjson.Map {
in := make(orderedjson.Map)
in["provider"] = account.Provider
in["email"] = account.Email
in["name"] = account.Name
in["login"] = account.NickName
in["first_name"] = account.FirstName
in["last_name"] = account.LastName
in["nick_name"] = account.NickName
in["user_id"] = account.UserID
in["description"] = account.Description
in["avatar"] = account.AvatarURL
in["location"] = account.Location
in["role"] = account.Role
return in
}
func mapUser(raw map[string]interface{}) *auth.UserInfo {
email := getString(raw, "email")
role := getString(raw, "role")
return &auth.UserInfo{
ID: getString(raw, "uid"),
Name: getString(raw, "name"),
Email: email,
Admin: isAdmin(role),
Claims: map[string]interface{}{
"email": email,
"role": role,
},
}
}
func getString(m map[string]interface{}, key string) string {
v, ok := m[key]
if ok {
s, ok := v.(string)
if ok {
return s
}
}
return ""
}