Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
alist-org
GitHub Repository: alist-org/alist
Path: blob/main/internal/model/role.go
1560 views
1
package model
2
3
import (
4
"encoding/json"
5
6
"gorm.io/gorm"
7
)
8
9
// PermissionEntry defines permission bitmask for a specific path.
10
type PermissionEntry struct {
11
Path string `json:"path"` // path prefix, e.g. "/admin"
12
Permission int32 `json:"permission"` // bitmask permissions
13
}
14
15
// Role represents a permission template which can be bound to users.
16
type Role struct {
17
ID uint `json:"id" gorm:"primaryKey"`
18
Name string `json:"name" gorm:"unique" binding:"required"`
19
Description string `json:"description"`
20
Default bool `json:"default" gorm:"default:false"`
21
// PermissionScopes stores structured permission list and is ignored by gorm.
22
PermissionScopes []PermissionEntry `json:"permission_scopes" gorm:"-"`
23
// RawPermission is the JSON representation of PermissionScopes stored in DB.
24
RawPermission string `json:"-" gorm:"type:text"`
25
}
26
27
// BeforeSave GORM hook serializes PermissionScopes into RawPermission.
28
func (r *Role) BeforeSave(tx *gorm.DB) error {
29
if len(r.PermissionScopes) == 0 {
30
r.RawPermission = ""
31
return nil
32
}
33
bs, err := json.Marshal(r.PermissionScopes)
34
if err != nil {
35
return err
36
}
37
r.RawPermission = string(bs)
38
return nil
39
}
40
41
// AfterFind GORM hook deserializes RawPermission into PermissionScopes.
42
func (r *Role) AfterFind(tx *gorm.DB) error {
43
if r.RawPermission == "" {
44
r.PermissionScopes = nil
45
return nil
46
}
47
var scopes []PermissionEntry
48
if err := json.Unmarshal([]byte(r.RawPermission), &scopes); err != nil {
49
return err
50
}
51
r.PermissionScopes = scopes
52
return nil
53
}
54
55