70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package useCases
|
|
|
|
import (
|
|
"RenewCMS/internal/domain/role"
|
|
"RenewCMS/internal/domain/user"
|
|
)
|
|
|
|
type Access struct {
|
|
Role role.Role
|
|
Permissions []role.Grant
|
|
}
|
|
|
|
type GetMyAccessUseCase struct {
|
|
roles role.Repository
|
|
}
|
|
|
|
func NewGetMyAccessUseCase(roles role.Repository) *GetMyAccessUseCase {
|
|
return &GetMyAccessUseCase{roles: roles}
|
|
}
|
|
|
|
var legacyBuiltInNames = map[user.Role]string{
|
|
user.RoleOwner: role.OwnerName,
|
|
user.RoleAdmin: role.AdminName,
|
|
}
|
|
|
|
func (u *GetMyAccessUseCase) resolveRole(account user.User) (role.Role, error) {
|
|
if account.RoleID != 0 {
|
|
return u.roles.Get(account.RoleID)
|
|
}
|
|
name, known := legacyBuiltInNames[account.Role]
|
|
if !known {
|
|
return role.Role{}, role.ErrRoleNotFound
|
|
}
|
|
found, err := u.roles.GetByName(name)
|
|
if err != nil {
|
|
return role.Role{}, err
|
|
}
|
|
if !found.BuiltIn {
|
|
return role.Role{}, role.ErrRoleNotFound
|
|
}
|
|
return found, nil
|
|
}
|
|
|
|
func (u *GetMyAccessUseCase) Get(account user.User) (Access, error) {
|
|
resolved, err := u.resolveRole(account)
|
|
if err != nil {
|
|
return Access{}, err
|
|
}
|
|
granted, err := u.roles.ListGrants(resolved.ID)
|
|
if err != nil {
|
|
return Access{}, err
|
|
}
|
|
return Access{Role: resolved, Permissions: orderedGrants(granted)}, nil
|
|
}
|
|
|
|
func orderedGrants(granted []role.Grant) []role.Grant {
|
|
scopes := make(map[string]role.Scope, len(granted))
|
|
for _, grant := range granted {
|
|
scopes[grant.Key] = grant.Scope
|
|
}
|
|
ordered := []role.Grant{}
|
|
for _, permission := range role.Catalogue() {
|
|
scope, present := scopes[permission.Key]
|
|
if present && scope != role.ScopeNone {
|
|
ordered = append(ordered, role.Grant{Key: permission.Key, Scope: scope})
|
|
}
|
|
}
|
|
return ordered
|
|
}
|