79 lines
2.4 KiB
Go
79 lines
2.4 KiB
Go
package version_local
|
|
|
|
import (
|
|
"runtime"
|
|
|
|
"go-admin/app/goauto/access"
|
|
"go-admin/cmd/migrate/migration"
|
|
migrationmodels "go-admin/cmd/migrate/migration/models"
|
|
common "go-admin/common/models"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
func init() {
|
|
_, fileName, _, _ := runtime.Caller(0)
|
|
migration.Migrate.SetVersion(migration.GetFilename(fileName), migratePurchaserRole)
|
|
}
|
|
|
|
func migratePurchaserRole(db *gorm.DB, version string) error {
|
|
return db.Transaction(func(tx *gorm.DB) error {
|
|
if err := ensurePurchaserRoleAndPolicies(tx); err != nil {
|
|
return err
|
|
}
|
|
return tx.Create(&common.Migration{Version: version}).Error
|
|
})
|
|
}
|
|
|
|
// purchaserCasbinRule deliberately targets the table used by gorm-adapter.
|
|
// The inherited go-admin migration model points at an unused
|
|
// `sys_casbin_rule` table and must not be used for runtime authorization.
|
|
type purchaserCasbinRule struct {
|
|
ID uint `gorm:"primaryKey;autoIncrement"`
|
|
Ptype string `gorm:"size:100"`
|
|
V0 string `gorm:"size:100"`
|
|
V1 string `gorm:"size:100"`
|
|
V2 string `gorm:"size:100"`
|
|
V3 string `gorm:"size:100"`
|
|
V4 string `gorm:"size:100"`
|
|
V5 string `gorm:"size:100"`
|
|
}
|
|
|
|
func (purchaserCasbinRule) TableName() string { return "casbin_rule" }
|
|
|
|
func ensurePurchaserRoleAndPolicies(db *gorm.DB) error {
|
|
role := migrationmodels.SysRole{}
|
|
if err := db.Where("role_key = ?", access.RolePurchaser).
|
|
Assign(migrationmodels.SysRole{
|
|
RoleName: "采购员", Status: "2", RoleSort: 20, Admin: false,
|
|
DataScope: "1", Remark: "GoAuto 采购业务角色(系统维护)",
|
|
}).FirstOrCreate(&role, migrationmodels.SysRole{RoleKey: access.RolePurchaser}).Error; err != nil {
|
|
return err
|
|
}
|
|
|
|
for _, permission := range access.AdminAPIs {
|
|
api := migrationmodels.SysApi{}
|
|
if err := db.Where("path = ? AND action = ?", permission.Path, permission.Method).
|
|
Attrs(migrationmodels.SysApi{Title: permission.Title, Type: "BUS"}).
|
|
FirstOrCreate(&api).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
|
|
// The role is system-maintained: reconcile its policies to the reviewed
|
|
// matrix so stale grants cannot survive a permission reduction.
|
|
if err := db.Where("ptype = ? AND v0 = ?", "p", access.RolePurchaser).
|
|
Delete(&purchaserCasbinRule{}).Error; err != nil {
|
|
return err
|
|
}
|
|
for _, permission := range access.PurchaserAPIs() {
|
|
rule := purchaserCasbinRule{
|
|
Ptype: "p", V0: access.RolePurchaser, V1: permission.Path, V2: permission.Method,
|
|
}
|
|
if err := db.Create(&rule).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|