forked from pocketbase/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
282 lines (235 loc) · 7.24 KB
/
user.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
package daos
import (
"database/sql"
"errors"
"fmt"
"log"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/models"
"github.com/pocketbase/pocketbase/models/schema"
"github.com/pocketbase/pocketbase/tools/list"
"github.com/pocketbase/pocketbase/tools/security"
)
// UserQuery returns a new User model select query.
func (dao *Dao) UserQuery() *dbx.SelectQuery {
return dao.ModelQuery(&models.User{})
}
// LoadProfile loads the profile record associated to the provided user.
func (dao *Dao) LoadProfile(user *models.User) error {
collection, err := dao.FindCollectionByNameOrId(models.ProfileCollectionName)
if err != nil {
return err
}
profile, err := dao.FindFirstRecordByData(collection, models.ProfileCollectionUserFieldName, user.Id)
if err != nil && err != sql.ErrNoRows {
return err
}
user.Profile = profile
return nil
}
// LoadProfiles loads the profile records associated to the provided users list.
func (dao *Dao) LoadProfiles(users []*models.User) error {
collection, err := dao.FindCollectionByNameOrId(models.ProfileCollectionName)
if err != nil {
return err
}
// extract user ids
ids := make([]string, len(users))
usersMap := map[string]*models.User{}
for i, user := range users {
ids[i] = user.Id
usersMap[user.Id] = user
}
profiles, err := dao.FindRecordsByExpr(collection, dbx.HashExp{
models.ProfileCollectionUserFieldName: list.ToInterfaceSlice(ids),
})
if err != nil {
return err
}
// populate each user.Profile member
for _, profile := range profiles {
userId := profile.GetStringDataValue(models.ProfileCollectionUserFieldName)
user, ok := usersMap[userId]
if !ok {
continue
}
user.Profile = profile
}
return nil
}
// FindUserById finds a single User model by its id.
//
// This method also auto loads the related user profile record
// into the found model.
func (dao *Dao) FindUserById(id string) (*models.User, error) {
model := &models.User{}
err := dao.UserQuery().
AndWhere(dbx.HashExp{"id": id}).
Limit(1).
One(model)
if err != nil {
return nil, err
}
// try to load the user profile (if exist)
if err := dao.LoadProfile(model); err != nil {
log.Println(err)
}
return model, nil
}
// FindUserByEmail finds a single User model by its non-empty email address.
//
// This method also auto loads the related user profile record
// into the found model.
func (dao *Dao) FindUserByEmail(email string) (*models.User, error) {
model := &models.User{}
err := dao.UserQuery().
AndWhere(dbx.Not(dbx.HashExp{"email": ""})).
AndWhere(dbx.HashExp{"email": email}).
Limit(1).
One(model)
if err != nil {
return nil, err
}
// try to load the user profile (if exist)
if err := dao.LoadProfile(model); err != nil {
log.Println(err)
}
return model, nil
}
// FindUserByToken finds the user associated with the provided JWT token.
// Returns an error if the JWT token is invalid or expired.
//
// This method also auto loads the related user profile record
// into the found model.
func (dao *Dao) FindUserByToken(token string, baseTokenKey string) (*models.User, error) {
unverifiedClaims, err := security.ParseUnverifiedJWT(token)
if err != nil {
return nil, err
}
// check required claims
id, _ := unverifiedClaims["id"].(string)
if id == "" {
return nil, errors.New("Missing or invalid token claims.")
}
user, err := dao.FindUserById(id)
if err != nil || user == nil {
return nil, err
}
verificationKey := user.TokenKey + baseTokenKey
// verify token signature
if _, err := security.ParseJWT(token, verificationKey); err != nil {
return nil, err
}
return user, nil
}
// IsUserEmailUnique checks if the provided email address is not
// already in use by other users.
func (dao *Dao) IsUserEmailUnique(email string, excludeId string) bool {
if email == "" {
return false
}
var exists bool
err := dao.UserQuery().
Select("count(*)").
AndWhere(dbx.Not(dbx.HashExp{"id": excludeId})).
AndWhere(dbx.HashExp{"email": email}).
Limit(1).
Row(&exists)
return err == nil && !exists
}
// DeleteUser deletes the provided User model.
//
// This method will also cascade the delete operation to all
// Record models that references the provided User model
// (delete or set to NULL, depending on the related user shema field settings).
//
// The delete operation may fail if the user is part of a required
// reference in another Record model (aka. cannot be deleted or set to NULL).
func (dao *Dao) DeleteUser(user *models.User) error {
// fetch related records
// note: the select is outside of the transaction to prevent SQLITE_LOCKED error when mixing read&write in a single transaction
relatedRecords, err := dao.FindUserRelatedRecords(user)
if err != nil {
return err
}
return dao.RunInTransaction(func(txDao *Dao) error {
// check if related records has to be deleted (if `CascadeDelete` is set)
// OR
// just unset the user related fields (if they are not required)
// -----------------------------------------------------------
recordsLoop:
for _, record := range relatedRecords {
var needSave bool
for _, field := range record.Collection().Schema.Fields() {
if field.Type != schema.FieldTypeUser {
continue // not a user field
}
ids := record.GetStringSliceDataValue(field.Name)
// unset the user id
for i := len(ids) - 1; i >= 0; i-- {
if ids[i] == user.Id {
ids = append(ids[:i], ids[i+1:]...)
break
}
}
options, _ := field.Options.(*schema.UserOptions)
// cascade delete
// (only if there are no other user references in case of multiple select)
if options.CascadeDelete && len(ids) == 0 {
if err := txDao.DeleteRecord(record); err != nil {
return err
}
// no need to further iterate the user fields (the record is deleted)
continue recordsLoop
}
if field.Required && len(ids) == 0 {
return fmt.Errorf("Failed delete the user because a record exist with required user reference to the current model (%q, %q).", record.Id, record.Collection().Name)
}
// apply the reference changes
record.SetDataValue(field.Name, field.PrepareValue(ids))
needSave = true
}
if needSave {
if err := txDao.SaveRecord(record); err != nil {
return err
}
}
}
// -----------------------------------------------------------
return txDao.Delete(user)
})
}
// SaveUser upserts the provided User model.
//
// An empty profile record will be created if the user
// doesn't have a profile record set yet.
func (dao *Dao) SaveUser(user *models.User) error {
profileCollection, err := dao.FindCollectionByNameOrId(models.ProfileCollectionName)
if err != nil {
return err
}
// fetch the related user profile record (if exist)
var userProfile *models.Record
if user.HasId() {
userProfile, _ = dao.FindFirstRecordByData(
profileCollection,
models.ProfileCollectionUserFieldName,
user.Id,
)
}
return dao.RunInTransaction(func(txDao *Dao) error {
if err := txDao.Save(user); err != nil {
return err
}
// create default/empty profile record if doesn't exist
if userProfile == nil {
userProfile = models.NewRecord(profileCollection)
userProfile.SetDataValue(models.ProfileCollectionUserFieldName, user.Id)
if err := txDao.Save(userProfile); err != nil {
return err
}
user.Profile = userProfile
}
return nil
})
}