uauth/pkg/rbac/rbac.go

84 lines
1.7 KiB
Go

package rbac
import (
"fmt"
"strings"
"uauth/model"
"uauth/pkg/cache"
"uauth/pkg/store"
"uauth/tool"
)
type RBAC struct {
cache cache.Cache
store store.Store
}
var (
Default *RBAC
)
func New(store store.Store, cache cache.Cache) (*RBAC, error) {
var (
err error
u = &RBAC{
store: store,
cache: cache,
}
rootPrivilege *model.Privilege
rootRole *model.Role
rootScope *model.Scope
rootUser *model.User
)
if err = u.store.Session(tool.Timeout()).AutoMigrate(
&model.Scope{},
&model.Privilege{},
&model.Role{},
&model.User{},
); err != nil {
return nil, fmt.Errorf("urbac migrate err: %w", err)
}
if rootPrivilege, err = u.newPrivilege(tool.Timeout(), "*:*:*:*", "admin", "", "*"); err != nil {
if !strings.Contains(strings.ToLower(err.Error()), "unique") {
return nil, err
}
}
if rootRole, err = u.newRole(tool.Timeout(), "admin", "管理员", "", rootPrivilege); err != nil {
if !strings.Contains(strings.ToLower(err.Error()), "unique") {
return nil, err
}
}
if rootScope, err = u.newScope(tool.Timeout(), "*", "全部", ""); err != nil {
if !strings.Contains(strings.ToLower(err.Error()), "unique") {
return nil, err
}
}
rootUser = &model.User{
Username: "admin",
Password: tool.NewPassword("123456"),
Status: model.StatusActive,
Nickname: "管理员",
RoleNames: []string{rootRole.Code},
}
if _, err = u.newUser(tool.Timeout(3), rootUser); err != nil {
if !strings.Contains(strings.ToLower(err.Error()), "unique") {
return nil, err
}
}
_ = rootScope
return u, nil
}
func Init(store store.Store, cache cache.Cache) (err error) {
Default, err = New(store, cache)
return err
}