111 lines
2.6 KiB
Go
111 lines
2.6 KiB
Go
package role
|
|
|
|
import (
|
|
"SciencesServer/app/api/admin/controller/auth"
|
|
"SciencesServer/app/api/admin/model"
|
|
model2 "SciencesServer/app/common/model"
|
|
"SciencesServer/app/service"
|
|
"SciencesServer/app/session"
|
|
"SciencesServer/serve/orm"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Auth struct{ *session.Admin }
|
|
|
|
type AuthHandle func(session *session.Admin) *Auth
|
|
|
|
// Instance 角色权限列表
|
|
func (c *Auth) Instance(roleID uint64) ([]*auth.TreeChecked, error) {
|
|
mSysAuth := model.NewSysAuth()
|
|
|
|
out, err := mSysAuth.RoleAuth(c.TenantID, roleID)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return auth.TreeCheckedFunc(out, 0), nil
|
|
}
|
|
|
|
// Bind 角色权限绑定
|
|
func (c *Auth) Bind(roleID uint64, authIDs []uint64) error {
|
|
if c.TenantID > 0 {
|
|
// 查询该租户下绑定的菜单信息
|
|
mSysTenantAuth := model.NewSysTenantAuth()
|
|
|
|
var count int64
|
|
|
|
if err := model2.Count(mSysTenantAuth.SysTenantAuth, &count, model2.NewWhere("tenant_id", c.TenantID),
|
|
model2.NewWhereNotIn("auth_id", authIDs)); err != nil {
|
|
return err
|
|
} else if count > 0 {
|
|
return errors.New("操作异常,菜单权限异常")
|
|
}
|
|
}
|
|
mSysRoleAuth := model.NewSysRoleAuth()
|
|
|
|
return orm.GetDB().Transaction(func(tx *gorm.DB) error {
|
|
err := model2.DeleteWhere(mSysRoleAuth.SysRoleAuth, []*model2.ModelWhere{model2.NewWhere("role_id", roleID)}, tx)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
permission := service.NewPermission(
|
|
service.WithAuthTenant(fmt.Sprintf("%d", c.TenantID)),
|
|
service.WithAuthRoles([]string{fmt.Sprintf("%d", roleID)}),
|
|
)
|
|
if len(authIDs) <= 0 {
|
|
_, err = permission.RemoveSingleRolePolicy()
|
|
return err
|
|
}
|
|
// 查询权限信息
|
|
mSysAuth := model.NewSysAuth()
|
|
|
|
auths := make([]*model2.SysAuth, 0)
|
|
|
|
if err = model2.ScanFields(mSysAuth.SysAuth, &auths, []string{"id", "kind", "auth"}, &model2.ModelWhereOrder{
|
|
Where: model2.NewWhereIn("id", authIDs),
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
data := make([]*model2.SysRoleAuth, 0)
|
|
|
|
request := make([]*service.AuthRequest, 0)
|
|
|
|
for _, v := range auths {
|
|
data = append(data, &model2.SysRoleAuth{
|
|
RoleID: roleID,
|
|
AuthID: v.ID,
|
|
})
|
|
if v.Kind == model2.SysAuthKindForModule || v.Auth == "" {
|
|
continue
|
|
}
|
|
mSysAuth.Auth = v.Auth
|
|
|
|
request = append(request, &service.AuthRequest{
|
|
Url: mSysAuth.FilterAuth(),
|
|
Method: "*",
|
|
})
|
|
}
|
|
if err = model2.Creates(mSysRoleAuth.SysRoleAuth, data); err != nil {
|
|
return err
|
|
}
|
|
if len(request) > 0 {
|
|
permission.AddRequest(request)
|
|
|
|
if _, err = permission.AddPolicies(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func NewAuth() AuthHandle {
|
|
return func(session *session.Admin) *Auth {
|
|
return &Auth{Admin: session}
|
|
}
|
|
}
|