313 lines
10 KiB
Go
313 lines
10 KiB
Go
package data
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"kra/internal/biz"
|
|
|
|
"github.com/casbin/casbin/v3"
|
|
casbinmodel "github.com/casbin/casbin/v3/model"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type apiPO struct {
|
|
ID uint `gorm:"primaryKey"`
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
DeletedAt gorm.DeletedAt `gorm:"index"`
|
|
Path string
|
|
Description string
|
|
APIGroup string `gorm:"column:api_group"`
|
|
Method string
|
|
}
|
|
|
|
func (apiPO) TableName() string { return "sys_apis" }
|
|
|
|
type ignoredAPIPO struct {
|
|
Path string `gorm:"primaryKey"`
|
|
Method string `gorm:"primaryKey"`
|
|
}
|
|
|
|
func (ignoredAPIPO) TableName() string { return "sys_ignore_apis" }
|
|
|
|
type authorityAPIPO struct {
|
|
AuthorityID uint `gorm:"primaryKey;column:authority_id"`
|
|
APIID uint `gorm:"primaryKey;column:api_id"`
|
|
}
|
|
|
|
func (authorityAPIPO) TableName() string { return "sys_authority_apis" }
|
|
|
|
func apiFromPO(po apiPO) *biz.API {
|
|
return &biz.API{ID: po.ID, CreatedAt: po.CreatedAt, UpdatedAt: po.UpdatedAt, Path: po.Path, Description: po.Description, APIGroup: po.APIGroup, Method: po.Method}
|
|
}
|
|
func (r *accessRepo) CreateAPI(ctx context.Context, v *biz.API) error {
|
|
po := apiPO{Path: v.Path, Description: v.Description, APIGroup: v.APIGroup, Method: strings.ToUpper(v.Method)}
|
|
var count int64
|
|
if err := r.data.gormDB.WithContext(ctx).Model(&apiPO{}).Where("path = ? AND method = ?", po.Path, po.Method).Count(&count).Error; err != nil {
|
|
return err
|
|
}
|
|
if count > 0 {
|
|
return errors.New("存在相同api")
|
|
}
|
|
if err := r.data.gormDB.WithContext(ctx).Create(&po).Error; err != nil {
|
|
return err
|
|
}
|
|
v.ID, v.CreatedAt, v.UpdatedAt, v.Method = po.ID, po.CreatedAt, po.UpdatedAt, po.Method
|
|
return nil
|
|
}
|
|
func (r *accessRepo) UpdateAPI(ctx context.Context, v *biz.API) error {
|
|
db := r.data.gormDB.WithContext(ctx)
|
|
var old apiPO
|
|
if err := db.First(&old, v.ID).Error; err != nil {
|
|
return err
|
|
}
|
|
method := strings.ToUpper(v.Method)
|
|
if old.Path != v.Path || old.Method != method {
|
|
var count int64
|
|
if err := db.Model(&apiPO{}).Where("id <> ? AND path = ? AND method = ?", v.ID, v.Path, method).Count(&count).Error; err != nil {
|
|
return err
|
|
}
|
|
if count > 0 {
|
|
return errors.New("存在相同api路径")
|
|
}
|
|
}
|
|
return db.Model(&old).Updates(map[string]any{"path": v.Path, "description": v.Description, "api_group": v.APIGroup, "method": method}).Error
|
|
}
|
|
func (r *accessRepo) DeleteAPIs(ctx context.Context, ids []uint) error {
|
|
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
|
|
return err
|
|
}
|
|
return tx.Delete(&apiPO{}, ids).Error
|
|
})
|
|
}
|
|
func (r *accessRepo) FindAPI(ctx context.Context, id uint) (*biz.API, error) {
|
|
var po apiPO
|
|
if err := r.data.gormDB.WithContext(ctx).First(&po, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return apiFromPO(po), nil
|
|
}
|
|
func (r *accessRepo) ListAPIs(ctx context.Context, page, size int, q *biz.API) ([]*biz.API, int64, error) {
|
|
db := r.data.gormDB.WithContext(ctx).Model(&apiPO{})
|
|
if q != nil && q.StrictAll {
|
|
config := r.data.runtime.Admin()
|
|
if actor, ok := biz.ActorFromContext(ctx); ok && config != nil && config.System != nil && config.System.UseStrictAuth {
|
|
var authority authorityPO
|
|
if err := r.data.gormDB.WithContext(ctx).Where("authority_id = ?", actor.AuthorityID).First(&authority).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
if authority.ParentID != nil && *authority.ParentID != 0 {
|
|
db = db.Where("id IN (?)", r.data.gormDB.WithContext(ctx).Model(&authorityAPIPO{}).Select("api_id").Where("authority_id = ?", actor.AuthorityID))
|
|
}
|
|
}
|
|
}
|
|
if q != nil {
|
|
if q.Path != "" {
|
|
db = db.Where("path LIKE ?", "%"+q.Path+"%")
|
|
}
|
|
if q.Description != "" {
|
|
db = db.Where("description LIKE ?", "%"+q.Description+"%")
|
|
}
|
|
if q.APIGroup != "" {
|
|
db = db.Where("api_group = ?", q.APIGroup)
|
|
}
|
|
if q.Method != "" {
|
|
db = db.Where("method = ?", strings.ToUpper(q.Method))
|
|
}
|
|
}
|
|
var total int64
|
|
if err := db.Count(&total).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
order := "id desc"
|
|
if q != nil && q.OrderKey != "" {
|
|
allowed := map[string]bool{"id": true, "path": true, "api_group": true, "description": true, "method": true}
|
|
if !allowed[q.OrderKey] {
|
|
return nil, 0, errors.New("非法的排序字段: " + q.OrderKey)
|
|
}
|
|
order = q.OrderKey
|
|
if q.Desc {
|
|
order += " desc"
|
|
}
|
|
}
|
|
var pos []apiPO
|
|
maxSize := 100
|
|
if q != nil && q.StrictAll {
|
|
maxSize = 0
|
|
}
|
|
if err := applyPagination(db.Order(order), page, size, maxSize).Find(&pos).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
out := make([]*biz.API, 0, len(pos))
|
|
for _, po := range pos {
|
|
out = append(out, apiFromPO(po))
|
|
}
|
|
return out, total, nil
|
|
}
|
|
func (r *accessRepo) APIRoleIDs(ctx context.Context, path, method string) ([]uint, error) {
|
|
var ids []uint
|
|
err := r.data.gormDB.WithContext(ctx).Table("sys_authority_apis").
|
|
Joins("JOIN sys_apis ON sys_apis.id = sys_authority_apis.api_id").
|
|
Where("sys_apis.path = ? AND sys_apis.method = ? AND sys_apis.deleted_at IS NULL", path, strings.ToUpper(method)).
|
|
Pluck("sys_authority_apis.authority_id", &ids).Error
|
|
return ids, err
|
|
}
|
|
func (r *accessRepo) SetAPIRoles(ctx context.Context, path, method string, ids []uint) error {
|
|
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
var api apiPO
|
|
if err := tx.Where("path = ? AND method = ?", path, strings.ToUpper(method)).First(&api).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Where("api_id = ?", api.ID).Delete(&authorityAPIPO{}).Error; err != nil {
|
|
return err
|
|
}
|
|
links := make([]authorityAPIPO, 0, len(ids))
|
|
for _, aid := range ids {
|
|
links = append(links, authorityAPIPO{AuthorityID: aid, APIID: api.ID})
|
|
}
|
|
if len(links) > 0 {
|
|
return tx.Create(&links).Error
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
func (r *accessRepo) Authorize(ctx context.Context, aid uint, path, method string) (bool, error) {
|
|
policies, err := r.PolicyPaths(ctx, aid)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
model, err := casbinmodel.NewModelFromString(`[request_definition]
|
|
r = sub, obj, act
|
|
[policy_definition]
|
|
p = sub, obj, act
|
|
[policy_effect]
|
|
e = some(where (p.eft == allow))
|
|
[matchers]
|
|
m = r.sub == p.sub && keyMatch2(r.obj, p.obj) && regexMatch(r.act, p.act)`)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
enforcer, err := casbin.NewEnforcer(model)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
subject := strconv.FormatUint(uint64(aid), 10)
|
|
for _, policy := range policies {
|
|
if _, err := enforcer.AddPolicy(subject, policy.Path, strings.ToUpper(policy.Method)); err != nil {
|
|
return false, err
|
|
}
|
|
}
|
|
return enforcer.Enforce(subject, path, strings.ToUpper(method))
|
|
}
|
|
func (r *accessRepo) PolicyPaths(ctx context.Context, aid uint) ([]*biz.API, error) {
|
|
var pos []apiPO
|
|
err := r.data.gormDB.WithContext(ctx).Table("sys_apis").Joins("JOIN sys_authority_apis ON sys_authority_apis.api_id = sys_apis.id").Where("sys_authority_apis.authority_id = ? AND sys_apis.deleted_at IS NULL", aid).Order("sys_apis.path,sys_apis.method").Find(&pos).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]*biz.API, 0, len(pos))
|
|
for _, po := range pos {
|
|
out = append(out, apiFromPO(po))
|
|
}
|
|
return out, nil
|
|
}
|
|
func (r *accessRepo) SetPolicyPaths(ctx context.Context, aid uint, paths []*biz.API) error {
|
|
if err := r.checkAuthorityIDAuth(ctx, aid); err != nil {
|
|
return err
|
|
}
|
|
config := r.data.runtime.Admin()
|
|
if actor, ok := biz.ActorFromContext(ctx); ok && config != nil && config.System != nil && config.System.UseStrictAuth {
|
|
var authority authorityPO
|
|
if err := r.data.gormDB.WithContext(ctx).Where("authority_id = ?", actor.AuthorityID).First(&authority).Error; err != nil {
|
|
return err
|
|
}
|
|
if authority.ParentID != nil && *authority.ParentID != 0 {
|
|
allowed, err := r.PolicyPaths(ctx, actor.AuthorityID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
allowedSet := make(map[string]bool, len(allowed))
|
|
for _, item := range allowed {
|
|
allowedSet[item.Path+"\x00"+strings.ToUpper(item.Method)] = true
|
|
}
|
|
for _, item := range paths {
|
|
if !allowedSet[item.Path+"\x00"+strings.ToUpper(item.Method)] {
|
|
return errors.New("存在api不在权限列表中")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Where("authority_id = ?", aid).Delete(&authorityAPIPO{}).Error; err != nil {
|
|
return err
|
|
}
|
|
links := make([]authorityAPIPO, 0, len(paths))
|
|
for _, path := range paths {
|
|
var po apiPO
|
|
err := tx.Where("path = ? AND method = ?", path.Path, strings.ToUpper(path.Method)).First(&po).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
po = apiPO{Path: path.Path, Method: strings.ToUpper(path.Method), Description: path.Description, APIGroup: path.APIGroup}
|
|
if err = tx.Create(&po).Error; err != nil {
|
|
return err
|
|
}
|
|
} else if err != nil {
|
|
return err
|
|
}
|
|
links = append(links, authorityAPIPO{AuthorityID: aid, APIID: po.ID})
|
|
}
|
|
if len(links) > 0 {
|
|
return tx.Create(&links).Error
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func (r *accessRepo) IgnoredAPIs(ctx context.Context) ([]*biz.API, error) {
|
|
var pos []ignoredAPIPO
|
|
if err := r.data.gormDB.WithContext(ctx).Order("path,method").Find(&pos).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]*biz.API, 0, len(pos))
|
|
for _, po := range pos {
|
|
out = append(out, &biz.API{Path: po.Path, Method: po.Method})
|
|
}
|
|
return out, nil
|
|
}
|
|
func (r *accessRepo) SetAPIIgnored(ctx context.Context, path, method string, ignored bool) error {
|
|
po := ignoredAPIPO{Path: path, Method: strings.ToUpper(method)}
|
|
if ignored {
|
|
return r.data.gormDB.WithContext(ctx).FirstOrCreate(&po, po).Error
|
|
}
|
|
return r.data.gormDB.WithContext(ctx).Where("path = ? AND method = ?", po.Path, po.Method).Delete(&ignoredAPIPO{}).Error
|
|
}
|
|
func (r *accessRepo) ApplyAPISync(ctx context.Context, added, deleted []*biz.API) error {
|
|
return r.data.gormDB.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
for _, item := range added {
|
|
po := apiPO{Path: item.Path, Method: strings.ToUpper(item.Method), Description: item.Description, APIGroup: item.APIGroup}
|
|
if err := tx.Where("path = ? AND method = ?", po.Path, po.Method).FirstOrCreate(&po).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
for _, item := range deleted {
|
|
var ids []uint
|
|
if err := tx.Model(&apiPO{}).Where("path = ? AND method = ?", item.Path, strings.ToUpper(item.Method)).Pluck("id", &ids).Error; err != nil {
|
|
return err
|
|
}
|
|
if len(ids) > 0 {
|
|
if err := tx.Where("api_id IN ?", ids).Delete(&authorityAPIPO{}).Error; err != nil {
|
|
return err
|
|
}
|
|
if err := tx.Where("id IN ?", ids).Delete(&apiPO{}).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|