-
Notifications
You must be signed in to change notification settings - Fork 302
/
user_store.go
241 lines (226 loc) · 8.04 KB
/
user_store.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
// Copyright © 2020 The Things Network Foundation, The Things Industries B.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package store
import (
"context"
"fmt"
"reflect"
"runtime/trace"
"strings"
"github.com/gogo/protobuf/types"
"github.com/jinzhu/gorm"
"go.thethings.network/lorawan-stack/v3/pkg/rpcmiddleware/warning"
"go.thethings.network/lorawan-stack/v3/pkg/ttnpb"
)
// GetUserStore returns an UserStore on the given db (or transaction).
func GetUserStore(db *gorm.DB) UserStore {
return &userStore{store: newStore(db)}
}
type userStore struct {
*store
}
// selectUserFields selects relevant fields (based on fieldMask) and preloads details if needed.
func selectUserFields(ctx context.Context, query *gorm.DB, fieldMask *types.FieldMask) *gorm.DB {
if fieldMask == nil || len(fieldMask.Paths) == 0 {
return query.Preload("Attributes").Preload("ProfilePicture").Select([]string{"accounts.uid", "users.*"})
}
var userColumns []string
var notFoundPaths []string
userColumns = append(userColumns, "accounts.uid")
for _, column := range modelColumns {
userColumns = append(userColumns, "users."+column)
}
for _, path := range ttnpb.TopLevelFields(fieldMask.Paths) {
switch path {
case "ids", "created_at", "updated_at":
// always selected
case attributesField:
query = query.Preload("Attributes")
case profilePictureField:
userColumns = append(userColumns, "profile_picture_id")
query = query.Preload("ProfilePicture")
default:
if columns, ok := userColumnNames[path]; ok {
userColumns = append(userColumns, columns...)
} else {
notFoundPaths = append(notFoundPaths, path)
}
}
}
if len(notFoundPaths) > 0 {
warning.Add(ctx, fmt.Sprintf("unsupported field mask paths: %s", strings.Join(notFoundPaths, ", ")))
}
return query.Select(userColumns)
}
func (s *userStore) CreateUser(ctx context.Context, usr *ttnpb.User) (*ttnpb.User, error) {
defer trace.StartRegion(ctx, "create user").End()
userModel := User{
Account: Account{UID: usr.UserID}, // The ID is not mutated by fromPB.
}
fieldMask := &types.FieldMask{Paths: append(defaultUserFieldMask.Paths, passwordField)}
userModel.fromPB(usr, fieldMask)
if err := s.createEntity(ctx, &userModel); err != nil {
return nil, err
}
var userProto ttnpb.User
userModel.toPB(&userProto, nil)
return &userProto, nil
}
func (s *userStore) FindUsers(ctx context.Context, ids []*ttnpb.UserIdentifiers, fieldMask *types.FieldMask) ([]*ttnpb.User, error) {
defer trace.StartRegion(ctx, "find users").End()
idStrings := make([]string, len(ids))
for i, id := range ids {
idStrings[i] = id.GetUserID()
}
query := s.query(ctx, User{}, withUserID(idStrings...))
query = selectUserFields(ctx, query, fieldMask)
query = query.Order(orderFromContext(ctx, "users", `"accounts"."uid"`, "ASC"))
if limit, offset := limitAndOffsetFromContext(ctx); limit != 0 {
countTotal(ctx, query.Model(User{}))
query = query.Limit(limit).Offset(offset)
}
var userModels []userWithUID
query = query.Find(&userModels)
setTotal(ctx, uint64(len(userModels)))
if query.Error != nil {
return nil, query.Error
}
userProtos := make([]*ttnpb.User, len(userModels))
for i, userModel := range userModels {
userProto := &ttnpb.User{}
userModel.toPB(userProto, fieldMask)
userProtos[i] = userProto
}
return userProtos, nil
}
func (s *userStore) ListAdmins(ctx context.Context, fieldMask *types.FieldMask) ([]*ttnpb.User, error) {
defer trace.StartRegion(ctx, "list admins").End()
query := s.query(ctx, User{}, withUserID()).Where(&User{Admin: true})
query = selectUserFields(ctx, query, fieldMask)
query = query.Order(orderFromContext(ctx, "users", `"accounts"."uid"`, "ASC"))
if limit, offset := limitAndOffsetFromContext(ctx); limit != 0 {
countTotal(ctx, query.Model(User{}))
query = query.Limit(limit).Offset(offset)
}
var userModels []userWithUID
query = query.Find(&userModels)
setTotal(ctx, uint64(len(userModels)))
if query.Error != nil {
return nil, query.Error
}
userProtos := make([]*ttnpb.User, len(userModels))
for i, userModel := range userModels {
userProto := &ttnpb.User{}
userModel.toPB(userProto, fieldMask)
userProtos[i] = userProto
}
return userProtos, nil
}
func (s *userStore) GetUser(ctx context.Context, id *ttnpb.UserIdentifiers, fieldMask *types.FieldMask) (*ttnpb.User, error) {
defer trace.StartRegion(ctx, "get user").End()
query := s.query(ctx, User{}, withUserID(id.GetUserID()))
query = selectUserFields(ctx, query, fieldMask)
var userModel userWithUID
if err := query.First(&userModel).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
return nil, errNotFoundForID(id)
}
return nil, err
}
userProto := &ttnpb.User{}
userModel.toPB(userProto, fieldMask)
return userProto, nil
}
func (s *userStore) UpdateUser(ctx context.Context, usr *ttnpb.User, fieldMask *types.FieldMask) (updated *ttnpb.User, err error) {
defer trace.StartRegion(ctx, "update user").End()
query := s.query(ctx, User{}, withUserID(usr.GetUserID()))
query = selectUserFields(ctx, query, fieldMask)
var userModel userWithUID
if err = query.First(&userModel).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
return nil, errNotFoundForID(usr.UserIdentifiers)
}
return nil, err
}
if err := ctx.Err(); err != nil { // Early exit if context canceled
return nil, err
}
oldAttributes, oldProfilePicture := userModel.Attributes, userModel.ProfilePicture
columns := userModel.fromPB(usr, fieldMask)
newProfilePicture := userModel.ProfilePicture
if newProfilePicture != oldProfilePicture {
if oldProfilePicture != nil {
if err = s.query(ctx, Picture{}).Delete(oldProfilePicture).Error; err != nil {
return nil, err
}
}
if newProfilePicture != nil {
if err = s.createEntity(ctx, &newProfilePicture); err != nil {
return nil, err
}
userModel.ProfilePictureID, userModel.ProfilePicture = &newProfilePicture.ID, nil
columns = append(columns, "profile_picture_id")
}
}
if err = s.updateEntity(ctx, &userModel.User, columns...); err != nil {
return nil, err
}
if !reflect.DeepEqual(oldAttributes, userModel.Attributes) {
if err = s.replaceAttributes(ctx, "user", userModel.ID, oldAttributes, userModel.Attributes); err != nil {
return nil, err
}
}
userModel.ProfilePicture = newProfilePicture
updated = &ttnpb.User{}
userModel.toPB(updated, fieldMask)
return updated, nil
}
func (s *userStore) DeleteUser(ctx context.Context, id *ttnpb.UserIdentifiers) (err error) {
defer trace.StartRegion(ctx, "delete user").End()
return s.deleteEntity(ctx, id)
}
func (s *userStore) PurgeUser(ctx context.Context, id *ttnpb.UserIdentifiers) (err error) {
defer trace.StartRegion(ctx, "purge user").End()
query := s.query(ctx, User{}, withUnscoped(), withUserID(id.GetUserID()))
query = selectUserFields(ctx, query, nil)
var userModel userWithUID
if err = query.First(&userModel).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
return errNotFoundForID(id)
}
return err
}
if err := ctx.Err(); err != nil { // Early exit if context canceled
return err
}
if len(userModel.Attributes) > 0 {
if err := s.replaceAttributes(ctx, "user", userModel.ID, userModel.Attributes, nil); err != nil {
return err
}
}
if userModel.ProfilePicture != nil {
if err = s.query(ctx, Picture{}).Delete(userModel.ProfilePicture).Error; err != nil {
return err
}
}
err = s.purgeEntity(ctx, id)
if err != nil {
return err
}
// Purge account after purging user because it is necessary for user query
return s.query(ctx, Account{}, withUnscoped()).Where(Account{
UID: id.IDString(),
AccountType: id.EntityType(),
}).Delete(Account{}).Error
}