urbac/urbac.go

68 lines
1.4 KiB
Go

package urbac
import (
"fmt"
"strings"
"github.com/loveuer/urbac/cache"
"github.com/loveuer/urbac/internal/tool"
"github.com/loveuer/urbac/store"
)
type Urbac struct {
cache cache.Cache
store store.Store
}
type Option func(u *Urbac)
func New(opts ...Option) (*Urbac, error) {
var (
err error
u = &Urbac{}
rootPrivilege *Privilege
rootRole *Role
rootScope *Scope
)
for _, opt := range opts {
opt(u)
}
if u.store == nil {
if u.store, err = store.NewSqliteStore("sqlite.db"); err != nil {
return nil, err
}
}
if u.cache == nil {
if u.cache, err = cache.NewRedisCache("redis://10.220.10.15:6379"); err != nil {
return nil, err
}
}
if err = u.store.Session(tool.Timeout()).AutoMigrate(&Scope{}, &Privilege{}, &Role{}); err != nil {
return nil, fmt.Errorf("urbac migrate err: %w", err)
}
if rootPrivilege, err = u.newPrivilege(tool.Timeout(), "*:*:*:*", "admin", 0, "*"); 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
}
}
return u, nil
}