54 lines
1.4 KiB
Go
54 lines
1.4 KiB
Go
package urbac
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/loveuer/urbac/internal/sqlType"
|
|
"github.com/samber/lo"
|
|
)
|
|
|
|
type Role struct {
|
|
CreatedAt int64 `json:"created_at" gorm:"column:created_at;autoCreateTime:milli"`
|
|
UpdatedAt int64 `json:"updated_at" gorm:"column:updated_at;autoUpdateTime:milli"`
|
|
DeletedAt int64 `json:"deleted_at" gorm:"index;column:deleted_at;default:0"`
|
|
Name string `json:"name" gorm:"primaryKey;column:name"`
|
|
Label string `json:"label" gorm:"column:label"`
|
|
Parent string `json:"parent" gorm:"column:parent"`
|
|
PrivilegeCodes sqlType.StrSlice `json:"privilege_codes" gorm:"column:privilege_codes"`
|
|
}
|
|
|
|
func (u *Urbac) newRole(ctx context.Context, name, label, parent string, privileges ...*Privilege) (*Role, error) {
|
|
ps := lo.FilterMap(
|
|
privileges,
|
|
func(p *Privilege, _ int) (string, bool) {
|
|
if p == nil {
|
|
return "", false
|
|
}
|
|
|
|
return p.Code, p.Code != ""
|
|
},
|
|
)
|
|
|
|
r := &Role{
|
|
Name: name,
|
|
Label: label,
|
|
Parent: parent,
|
|
PrivilegeCodes: ps,
|
|
}
|
|
|
|
if err := u.store.Session(ctx).Create(r).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return r, nil
|
|
}
|
|
|
|
func (u *Urbac) GetRole(ctx context.Context, name string) (*Role, error) {
|
|
var r Role
|
|
if err := u.store.Session(ctx).Take(&r, "name = ?", name).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &r, nil
|
|
}
|