forked from brocaar/chirpstack-application-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
390 lines (323 loc) · 10.2 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
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
package api
import (
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/empty"
"github.com/jmoiron/sqlx"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
pb "github.com/brocaar/lora-app-server/api"
"github.com/brocaar/lora-app-server/internal/api/auth"
"github.com/brocaar/lora-app-server/internal/config"
"github.com/brocaar/lora-app-server/internal/storage"
)
// UserAPI exports the User related functions.
type UserAPI struct {
validator auth.Validator
}
// InternalUserAPI exports the internal User related functions.
type InternalUserAPI struct {
validator auth.Validator
}
// NewUserAPI creates a new UserAPI.
func NewUserAPI(validator auth.Validator) *UserAPI {
return &UserAPI{
validator: validator,
}
}
// Create creates the given user.
func (a *UserAPI) Create(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {
if req.User == nil {
return nil, grpc.Errorf(codes.InvalidArgument, "user must not be nil")
}
if err := a.validator.Validate(ctx,
auth.ValidateUsersAccess(auth.Create)); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
// validate if the client has admin rights for the given organizations
// to which the user must be linked
for _, org := range req.Organizations {
if err := a.validator.Validate(ctx,
auth.ValidateIsOrganizationAdmin(org.OrganizationId)); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
}
user := storage.User{
Username: req.User.Username,
SessionTTL: req.User.SessionTtl,
IsAdmin: req.User.IsAdmin,
IsActive: req.User.IsActive,
Email: req.User.Email,
Note: req.User.Note,
}
isAdmin, err := a.validator.GetIsAdmin(ctx)
if err != nil {
return nil, errToRPCError(err)
}
if !isAdmin {
// non-admin users are not able to modify the fields below
user.IsAdmin = false
user.IsActive = true
user.SessionTTL = 0
}
var userID int64
err = storage.Transaction(config.C.PostgreSQL.DB, func(tx sqlx.Ext) error {
userID, err = storage.CreateUser(tx, &user, req.Password)
if err != nil {
return err
}
for _, org := range req.Organizations {
if err := storage.CreateOrganizationUser(tx, org.OrganizationId, userID, org.IsAdmin); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, errToRPCError(err)
}
return &pb.CreateUserResponse{Id: userID}, nil
}
// Get returns the user matching the given ID.
func (a *UserAPI) Get(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) {
if err := a.validator.Validate(ctx,
auth.ValidateUserAccess(req.Id, auth.Read)); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
user, err := storage.GetUser(config.C.PostgreSQL.DB, req.Id)
if err != nil {
return nil, errToRPCError(err)
}
resp := pb.GetUserResponse{
User: &pb.User{
Id: user.ID,
Username: user.Username,
SessionTtl: user.SessionTTL,
IsAdmin: user.IsAdmin,
IsActive: user.IsActive,
Email: user.Email,
Note: user.Note,
},
}
resp.CreatedAt, err = ptypes.TimestampProto(user.CreatedAt)
if err != nil {
return nil, errToRPCError(err)
}
resp.UpdatedAt, err = ptypes.TimestampProto(user.UpdatedAt)
if err != nil {
return nil, errToRPCError(err)
}
return &resp, nil
}
// List lists the users.
func (a *UserAPI) List(ctx context.Context, req *pb.ListUserRequest) (*pb.ListUserResponse, error) {
if err := a.validator.Validate(ctx,
auth.ValidateUsersAccess(auth.List)); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
users, err := storage.GetUsers(config.C.PostgreSQL.DB, int(req.Limit), int(req.Offset), req.Search)
if err != nil {
return nil, errToRPCError(err)
}
totalUserCount, err := storage.GetUserCount(config.C.PostgreSQL.DB, req.Search)
if err != nil {
return nil, errToRPCError(err)
}
resp := pb.ListUserResponse{
TotalCount: int64(totalUserCount),
}
for _, u := range users {
row := pb.UserListItem{
Id: u.ID,
Username: u.Username,
SessionTtl: u.SessionTTL,
IsAdmin: u.IsAdmin,
IsActive: u.IsActive,
}
row.CreatedAt, err = ptypes.TimestampProto(u.CreatedAt)
if err != nil {
return nil, errToRPCError(err)
}
row.UpdatedAt, err = ptypes.TimestampProto(u.UpdatedAt)
if err != nil {
return nil, errToRPCError(err)
}
resp.Result = append(resp.Result, &row)
}
return &resp, nil
}
// Update updates the given user.
func (a *UserAPI) Update(ctx context.Context, req *pb.UpdateUserRequest) (*empty.Empty, error) {
if req.User == nil {
return nil, grpc.Errorf(codes.InvalidArgument, "user must not be nil")
}
if err := a.validator.Validate(ctx,
auth.ValidateUserAccess(req.User.Id, auth.Update)); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
userUpdate := storage.UserUpdate{
ID: req.User.Id,
Username: req.User.Username,
IsAdmin: req.User.IsAdmin,
IsActive: req.User.IsActive,
SessionTTL: req.User.SessionTtl,
Email: req.User.Email,
Note: req.User.Note,
}
err := storage.UpdateUser(config.C.PostgreSQL.DB, userUpdate)
if err != nil {
return nil, errToRPCError(err)
}
return &empty.Empty{}, nil
}
// Delete deletes the user matching the given ID.
func (a *UserAPI) Delete(ctx context.Context, req *pb.DeleteUserRequest) (*empty.Empty, error) {
if err := a.validator.Validate(ctx,
auth.ValidateUserAccess(req.Id, auth.Delete)); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
err := storage.DeleteUser(config.C.PostgreSQL.DB, req.Id)
if err != nil {
return nil, errToRPCError(err)
}
return &empty.Empty{}, nil
}
// UpdatePassword updates the password for the user matching the given ID.
func (a *UserAPI) UpdatePassword(ctx context.Context, req *pb.UpdateUserPasswordRequest) (*empty.Empty, error) {
if err := a.validator.Validate(ctx,
auth.ValidateUserAccess(req.UserId, auth.UpdateProfile)); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
err := storage.UpdatePassword(config.C.PostgreSQL.DB, req.UserId, req.Password)
if err != nil {
return nil, errToRPCError(err)
}
return &empty.Empty{}, nil
}
// NewInternalUserAPI creates a new InternalUserAPI.
func NewInternalUserAPI(validator auth.Validator) *InternalUserAPI {
return &InternalUserAPI{
validator: validator,
}
}
// Login validates the login request and returns a JWT token.
func (a *InternalUserAPI) Login(ctx context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) {
jwt, err := storage.LoginUser(config.C.PostgreSQL.DB, req.Username, req.Password)
if nil != err {
return nil, errToRPCError(err)
}
return &pb.LoginResponse{Jwt: jwt}, nil
}
type claims struct {
Username string `json:"username"`
}
// Profile returns the user profile.
func (a *InternalUserAPI) Profile(ctx context.Context, req *empty.Empty) (*pb.ProfileResponse, error) {
if err := a.validator.Validate(ctx,
auth.ValidateActiveUser()); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
username, err := a.validator.GetUsername(ctx)
if nil != err {
return nil, errToRPCError(err)
}
// Get the user id based on the username.
user, err := storage.GetUserByUsername(config.C.PostgreSQL.DB, username)
if nil != err {
return nil, errToRPCError(err)
}
prof, err := storage.GetProfile(config.C.PostgreSQL.DB, user.ID)
if err != nil {
return nil, errToRPCError(err)
}
resp := pb.ProfileResponse{
User: &pb.User{
Id: prof.User.ID,
Username: prof.User.Username,
SessionTtl: prof.User.SessionTTL,
IsAdmin: prof.User.IsAdmin,
IsActive: prof.User.IsActive,
},
Settings: &pb.ProfileSettings{
DisableAssignExistingUsers: auth.DisableAssignExistingUsers,
},
}
for _, org := range prof.Organizations {
row := pb.OrganizationLink{
OrganizationId: org.ID,
OrganizationName: org.Name,
IsAdmin: org.IsAdmin,
}
row.CreatedAt, err = ptypes.TimestampProto(org.CreatedAt)
if err != nil {
return nil, errToRPCError(err)
}
row.UpdatedAt, err = ptypes.TimestampProto(org.UpdatedAt)
if err != nil {
return nil, errToRPCError(err)
}
resp.Organizations = append(resp.Organizations, &row)
}
return &resp, nil
}
// Branding returns UI branding.
func (a *InternalUserAPI) Branding(ctx context.Context, req *empty.Empty) (*pb.BrandingResponse, error) {
resp := pb.BrandingResponse{
Logo: config.C.ApplicationServer.Branding.Header,
Registration: config.C.ApplicationServer.Branding.Registration,
Footer: config.C.ApplicationServer.Branding.Footer,
}
return &resp, nil
}
// GlobalSearch performs a global search.
func (a *InternalUserAPI) GlobalSearch(ctx context.Context, req *pb.GlobalSearchRequest) (*pb.GlobalSearchResponse, error) {
if err := a.validator.Validate(ctx,
auth.ValidateActiveUser()); err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "authentication failed: %s", err)
}
isAdmin, err := a.validator.GetIsAdmin(ctx)
if err != nil {
return nil, errToRPCError(err)
}
username, err := a.validator.GetUsername(ctx)
if err != nil {
return nil, errToRPCError(err)
}
results, err := storage.GlobalSearch(config.C.PostgreSQL.DB, username, isAdmin, req.Search, int(req.Limit), int(req.Offset))
if err != nil {
return nil, errToRPCError(err)
}
var out pb.GlobalSearchResponse
for _, r := range results {
res := pb.GlobalSearchResult{
Kind: r.Kind,
Score: float32(r.Score),
}
if r.OrganizationID != nil {
res.OrganizationId = *r.OrganizationID
}
if r.OrganizationName != nil {
res.OrganizationName = *r.OrganizationName
}
if r.ApplicationID != nil {
res.ApplicationId = *r.ApplicationID
}
if r.ApplicationName != nil {
res.ApplicationName = *r.ApplicationName
}
if r.DeviceDevEUI != nil {
res.DeviceDevEui = r.DeviceDevEUI.String()
}
if r.DeviceName != nil {
res.DeviceName = *r.DeviceName
}
if r.GatewayMAC != nil {
res.GatewayMac = r.GatewayMAC.String()
}
if r.GatewayName != nil {
res.GatewayName = *r.GatewayName
}
out.Result = append(out.Result, &res)
}
return &out, nil
}