forked from harranali/authority
-
Notifications
You must be signed in to change notification settings - Fork 0
/
authority.go
545 lines (480 loc) · 14.5 KB
/
authority.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
package authority
import (
"errors"
"fmt"
"gorm.io/gorm"
)
// Authority helps deal with permissions
type Authority struct {
TablesPrefix string
DB *gorm.DB
}
// Options has the options for initiating the package
type Options struct {
TablesPrefix string
DB *gorm.DB
}
var (
ErrPermissionInUse = errors.New("cannot delete assigned permission")
ErrPermissionNotFound = errors.New("permission not found")
ErrRoleInUse = errors.New("cannot delete assigned role")
ErrRoleNotFound = errors.New("role not found")
)
var tablePrefix string
var auth *Authority
var options Options
var tx *gorm.DB
// New initiates authority
func New(opts Options) *Authority {
options = opts
auth = &Authority{
TablesPrefix: options.TablesPrefix,
DB: opts.DB,
}
migrateTables(opts.DB)
return auth
}
// New initiates new instance of authority
func newInstance(opts Options) *Authority {
newAuth := &Authority{
DB: opts.DB,
}
migrateTables(opts.DB)
return newAuth
}
// Resolve returns the initiated instance
func Resolve() *Authority {
return auth
}
// Add a new role to the database
// it accepts the Role struct as a parameter
// it returns an error in case of any
// it returns an error if the role is already exists
func (a *Authority) CreateRole(r Role) error {
roleSlug := r.Slug
var dbRole Role
res := a.DB.Where("slug = ?", roleSlug).First(&dbRole)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
// create
createRes := a.DB.Create(&r)
if createRes.Error != nil {
return createRes.Error
}
return nil
}
return res.Error
}
return errors.New(fmt.Sprintf("role '%v' already exists", roleSlug))
}
// Add a new permission to the database
// it accepts the Permission struct as a parameter
// it returns an error in case of any
// it returns an error if the permission is already exists
func (a *Authority) CreatePermission(p Permission) error {
permSlug := p.Slug
var dbPerm Permission
res := a.DB.Where("slug = ?", permSlug).First(&dbPerm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
// create
createRes := a.DB.Create(&p)
if createRes.Error != nil {
return createRes.Error
}
return nil
}
return res.Error
}
return errors.New(fmt.Sprintf("permission '%v' already exists", permSlug))
}
// Assigns a group of permissions to a given role
// it accepts the the role slug as the first parameter
// the second parameter is a slice of permission slugs (strings) to be assigned to the role
// it returns an error in case of any
// it returns an error in case the role does not exists
// it returns an error in case any of the permissions does not exists
// it returns an error in case any of the permissions is already assigned
func (a *Authority) AssignPermissionsToRole(roleSlug string, permSlugs []string) error {
var role Role
rRes := a.DB.Where("slug = ?", roleSlug).First(&role)
if rRes.Error != nil {
if errors.Is(rRes.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return rRes.Error
}
var perms []Permission
for _, permSlug := range permSlugs {
var perm Permission
pRes := a.DB.Where("slug = ?", permSlug).First(&perm)
if pRes.Error != nil {
if errors.Is(pRes.Error, gorm.ErrRecordNotFound) {
return ErrPermissionNotFound
}
return pRes.Error
}
perms = append(perms, perm)
}
tx := a.DB.Begin()
for _, perm := range perms {
var rolePerm RolePermission
res := a.DB.Where("role_id = ?", role.ID).Where("permission_id =?", perm.ID).First(&rolePerm)
if res.Error != nil && errors.Is(res.Error, gorm.ErrRecordNotFound) {
cRes := tx.Create(&RolePermission{RoleID: role.ID, PermissionID: perm.ID})
if cRes.Error != nil {
tx.Rollback()
return cRes.Error
}
}
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
tx.Rollback()
return res.Error
}
if rolePerm != (RolePermission{}) {
tx.Rollback()
return errors.New(fmt.Sprintf("permission '%v' is aleady assigned to the role '%v'", perm.Name, role.Name))
}
rolePerm = RolePermission{}
}
return tx.Commit().Error
}
// Assigns a role to a given user
// it accepts the user id as the first parameter
// the second parameter the role slug
// it returns an error in case of any
// it returns an error in case the role does not exists
// it returns an error in case the role is already assigned
func (a *Authority) AssignRoleToUser(userID interface{}, roleSlug string) error {
userIDStr := fmt.Sprintf("%v", userID)
var role Role
res := a.DB.Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return res.Error
}
var userRole UserRole
res = a.DB.Where("user_id = ?", userIDStr).Where("role_id = ?", role.ID).First(&userRole)
if res.Error != nil && errors.Is(res.Error, gorm.ErrRecordNotFound) {
a.DB.Create(&UserRole{UserID: userIDStr, RoleID: role.ID})
return nil
}
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
return res.Error
}
return errors.New(fmt.Sprintf("this role '%v' is aleady assigned to the user", roleSlug))
}
// Checks if a role is assigned to a user
// it accepts the user id as the first parameter
// the second parameter the role slug
// it returns two parameters
// the first parameter of the return is a boolean represents whether the role is assigned or not
// the second is an error in case of any
// in case the role does not exists, an error is returned
func (a *Authority) CheckUserRole(userID interface{}, roleSlug string) (bool, error) {
userIDStr := fmt.Sprintf("%v", userID)
// find the role
var role Role
res := a.DB.Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrRoleNotFound
}
return false, res.Error
}
// check if the role is a assigned
var userRole UserRole
res = a.DB.Where("user_id = ?", userIDStr).Where("role_id = ?", role.ID).First(&userRole)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
return false, res.Error
}
return true, nil
}
// Checks if a permission is assigned to a user
// it accepts in the user id as the first parameter
// the second parameter the role slug
// it returns two parameters
// the first parameter of the return is a boolean represents whether the role is assigned or not
// the second is an error in case of any
// in case the role does not exists, an error is returned
func (a *Authority) CheckUserPermission(userID interface{}, permSlug string) (bool, error) {
userIDStr := fmt.Sprintf("%v", userID)
// the user role
var userRoles []UserRole
res := a.DB.Where("user_id = ?", userIDStr).Find(&userRoles)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
return false, res.Error
}
//prepare an array of role ids
var roleIDs []interface{}
for _, r := range userRoles {
roleIDs = append(roleIDs, r.RoleID)
}
// find the permission
var perm Permission
res = a.DB.Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrPermissionNotFound
}
return false, res.Error
}
// find the role permission
var rolePermission RolePermission
res = a.DB.Where("role_id IN (?)", roleIDs).Where("permission_id = ?", perm.ID).First(&rolePermission)
if res.Error != nil && errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, res.Error
}
return true, nil
}
// Checks if a permission is assigned to a role
// it accepts in the role slug as the first parameter
// the second parameter the permission slug
// it returns two parameters
// the first parameter of the return is a boolean represents whether the permission is assigned or not
// the second is an error in case of any
// in case the role does not exists, an error is returned
// in case the permission does not exists, an error is returned
func (a *Authority) CheckRolePermission(roleSlug string, permSlug string) (bool, error) {
// find the role
var role Role
res := a.DB.Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrRoleNotFound
}
return false, res.Error
}
// find the permission
var perm Permission
res = a.DB.Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, ErrPermissionNotFound
}
return false, res.Error
}
// find the rolePermission
var rolePermission RolePermission
res = a.DB.Where("role_id = ?", role.ID).Where("permission_id = ?", perm.ID).First(&rolePermission)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return false, nil
}
return false, res.Error
}
return true, nil
}
// Revokes a user's role
// it returns a error in case of any
// in case the role does not exists, an error is returned
func (a *Authority) RevokeUserRole(userID interface{}, roleSlug string) error {
userIDStr := fmt.Sprintf("%v", userID)
// find the role
var role Role
res := a.DB.Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return res.Error
}
// revoke the role
rRes := a.DB.Where("user_id = ?", userIDStr).Where("role_id = ?", role.ID).Delete(UserRole{})
if rRes.Error != nil {
return rRes.Error
}
return nil
}
// Revokes a roles's permission
// it returns a error in case of any
// in case the role does not exists, an error is returned
// in case the permission does not exists, an error is returned
func (a *Authority) RevokeRolePermission(roleSlug string, permSlug string) error {
// find the role
var role Role
res := a.DB.Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrRoleNotFound
}
return res.Error
}
// find the permission
var perm Permission
res = a.DB.Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
return ErrPermissionNotFound
}
return res.Error
}
// revoke the permission
rRes := a.DB.Where("role_id = ?", role.ID).Where("permission_id = ?", perm.ID).Delete(RolePermission{})
if rRes.Error != nil {
return rRes.Error
}
return nil
}
// Returns all stored roles
// it returns an error in case of any
func (a *Authority) GetAllRoles() ([]Role, error) {
var roles []Role
res := a.DB.Find(&roles)
if res.Error != nil {
return nil, res.Error
}
return roles, nil
}
// Returns all user assigned roles
// it returns an error in case of any
func (a *Authority) GetUserRoles(userID interface{}) ([]Role, error) {
userIDStr := fmt.Sprintf("%v", userID)
var userRoles []UserRole
res := a.DB.Where("user_id = ?", userIDStr).Find(&userRoles)
if res.Error != nil {
return nil, res.Error
}
var roleIDs []interface{}
for _, r := range userRoles {
roleIDs = append(roleIDs, r.RoleID)
}
var roles []Role
res = a.DB.Where("id IN (?)", roleIDs).Find(&roles)
if res.Error != nil {
return nil, res.Error
}
return roles, nil
}
// Returns all role assigned permissions
// it returns an error in case of any
func (a *Authority) GetRolePermissions(roleSlug string) ([]Permission, error) {
var role Role
res := a.DB.Where("slug = ?", roleSlug).Find(&role)
if res.Error != nil {
return nil, res.Error
}
var rolePerms []RolePermission
res = a.DB.Where("role_id = ?", role.ID).Find(&rolePerms)
if res.Error != nil {
return nil, res.Error
}
var permIDs []interface{}
for _, rolePerm := range rolePerms {
permIDs = append(permIDs, rolePerm.PermissionID)
}
var perms []Permission
res = a.DB.Where("id IN (?)", permIDs).Find(&perms)
if res.Error != nil {
return nil, res.Error
}
return perms, nil
}
// Returns all stored permissions
// it returns an error in case of any
func (a *Authority) GetAllPermissions() ([]Permission, error) {
var perms []Permission
res := a.DB.Find(&perms)
if res.Error != nil {
return nil, res.Error
}
return perms, nil
}
// Deletes a given role even if it's has assigned permissions
// it first deassign the permissions and then proceed with deleting the role
// it accepts the role slug as a parameter
// it returns an error in case of any
// if the role is assigned to a user it returns an error
func (a *Authority) DeleteRole(roleSlug string) error {
// find the role
var role Role
res := a.DB.Where("slug = ?", roleSlug).First(&role)
if res.Error != nil {
return res.Error
}
// check if the role is assigned to a user
var c int64
res = a.DB.Model(UserRole{}).Where("role_id = ?", role.ID).Count(&c)
if res.Error != nil {
return res.Error
}
if c != 0 {
// role is assigned
return ErrRoleInUse
}
tx := a.DB.Begin()
// revoke the assignment of permissions before deleting the role
dRes := tx.Where("role_id = ?", role.ID).Delete(RolePermission{})
if dRes.Error != nil {
tx.Rollback()
return dRes.Error
}
// delete the role
dRes = a.DB.Where("slug = ?", roleSlug).Delete(Role{})
if dRes.Error != nil {
tx.Rollback()
return dRes.Error
}
return tx.Commit().Error
}
// Deletes a given permission
// it accepts the permission slug as a parameter
// it returns an error in case of any
// if the permission is assigned to a role it returns an error
func (a *Authority) DeletePermission(permSlug string) error {
// find the permission
var perm Permission
res := a.DB.Where("slug = ?", permSlug).First(&perm)
if res.Error != nil {
return res.Error
}
// check if the permission is assigned to a role
var rolePermission RolePermission
res = a.DB.Where("permission_id = ?", perm.ID).First(&rolePermission)
if res.Error != nil && !errors.Is(res.Error, gorm.ErrRecordNotFound) {
return res.Error
}
if res.Error == nil {
return ErrPermissionInUse
}
// delete the permission
dRes := a.DB.Where("slug = ?", permSlug).Delete(Permission{})
if dRes.Error != nil {
return dRes.Error
}
return nil
}
// Begin a transaction session
func (a *Authority) BeginTX() *Authority {
tx = options.DB.Begin()
newAuth := newInstance(Options{
TablesPrefix: options.TablesPrefix,
DB: tx,
})
return newAuth
}
// Rolback previous queries
func (a *Authority) Rollback() error {
return tx.Rollback().Error
}
// Commit queries to the database
func (a *Authority) Commit() error {
return tx.Commit().Error
}
func migrateTables(db *gorm.DB) {
db.AutoMigrate(&Role{})
db.AutoMigrate(&Permission{})
db.AutoMigrate(&RolePermission{})
db.AutoMigrate(&UserRole{})
}