Files
yunzerwebsiteallinone/go/controllers/backend_role.go
T
2026-11-16 17:22:50 +08:00

364 lines
9.1 KiB
Go

package controllers
import (
"encoding/json"
"io"
"strconv"
"strings"
"server/models"
"server/pkg/identity"
beego "github.com/beego/beego/v2/server/web"
)
type BackendRoleController struct {
beego.Controller
}
type backendRolePayload struct {
Name string `json:"name"`
Status *uint8 `json:"status"`
Rights interface{} `json:"rights"`
}
func parseSubmittedIDs(v interface{}) []uint64 {
ids := make([]uint64, 0)
switch t := v.(type) {
case []interface{}:
for _, item := range t {
switch n := item.(type) {
case float64:
ids = append(ids, uint64(n))
case json.Number:
if i, err := n.Int64(); err == nil {
ids = append(ids, uint64(i))
}
case string:
if i, err := strconv.ParseUint(strings.TrimSpace(n), 10, 64); err == nil {
ids = append(ids, i)
}
}
}
case []uint64:
ids = append(ids, t...)
case string:
var arr []uint64
if err := json.Unmarshal([]byte(t), &arr); err == nil {
ids = append(ids, arr...)
} else {
for _, part := range strings.Split(t, ",") {
if i, err := strconv.ParseUint(strings.TrimSpace(part), 10, 64); err == nil {
ids = append(ids, i)
}
}
}
}
return ids
}
func loadAssignableTenantMenuIDs() map[uint64]bool {
ids := make(map[uint64]bool)
var menus []models.SystemMenu
if _, err := models.Orm.QueryTable(new(models.SystemMenu)).All(&menus); err != nil {
return ids
}
menus = filterMenusByView(menus, 2)
menus = filterAssignableMenus(menus)
for _, m := range menus {
ids[m.ID] = true
}
return ids
}
func sanitizeTenantRights(v interface{}) *string {
if v == nil {
return nil
}
if s, ok := v.(string); ok && strings.TrimSpace(s) == "" {
return nil
}
submitted := parseSubmittedIDs(v)
empty := "[]"
if len(submitted) == 0 {
return &empty
}
allowed := loadAssignableTenantMenuIDs()
kept := make([]uint64, 0, len(submitted))
seen := make(map[uint64]bool, len(submitted))
for _, id := range submitted {
if id == 0 || seen[id] || !allowed[id] {
continue
}
seen[id] = true
kept = append(kept, id)
}
if len(kept) == 0 {
return &empty
}
b, _ := json.Marshal(kept)
s := string(b)
return &s
}
func tenantRoleReadOnly(role models.AdminRole) bool {
return role.IsLocked == 1 || role.TenantID == 0
}
func (c *BackendRoleController) currentTenantID() (uint64, bool) {
claims, err := identity.Claims(c.Ctx.Request.Header.Get("Authorization"), identity.EndBackend, identity.EndApp)
if err != nil {
code := identity.Status(err)
c.Data["json"] = map[string]interface{}{"code": code, "msg": err.Error()}
_ = c.ServeJSON()
return 0, false
}
if claims.TenantId <= 0 {
c.Data["json"] = map[string]interface{}{"code": 401, "msg": "租户信息缺失"}
_ = c.ServeJSON()
return 0, false
}
return uint64(claims.TenantId), true
}
func (c *BackendRoleController) GetAllRoles() {
tid, ok := c.currentTenantID()
if !ok {
return
}
var rows []models.AdminRole
_, err := models.Orm.QueryTable(new(models.AdminRole)).
Filter("cid", 2).
Filter("tenant_id__in", []uint64{0, tid}).
OrderBy("tenant_id", "is_custom", "id").
All(&rows)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "查询失败"}
_ = c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success", "data": rows}
_ = c.ServeJSON()
}
func (c *BackendRoleController) GetRoleByID() {
tid, ok := c.currentTenantID()
if !ok {
return
}
idStr := c.Ctx.Input.Param(":id")
id, _ := strconv.ParseUint(idStr, 10, 64)
if id == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "id 不能为空"}
_ = c.ServeJSON()
return
}
var role models.AdminRole
if err := models.Orm.QueryTable(new(models.AdminRole)).
Filter("id", id).
Filter("cid", 2).
Filter("tenant_id__in", []uint64{0, tid}).
One(&role); err != nil {
c.Data["json"] = map[string]interface{}{"code": 404, "msg": "角色不存在"}
_ = c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success", "data": role}
_ = c.ServeJSON()
}
func (c *BackendRoleController) CreateRole() {
tid, ok := c.currentTenantID()
if !ok {
return
}
var p backendRolePayload
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "参数错误"}
_ = c.ServeJSON()
return
}
p.Name = strings.TrimSpace(p.Name)
if p.Name == "" {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "name 不能为空"}
_ = c.ServeJSON()
return
}
dup, derr := models.Orm.QueryTable(new(models.AdminRole)).
Filter("cid", 2).
Filter("tenant_id__in", []uint64{0, tid}).
Filter("name", p.Name).
Count()
if derr != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "创建失败"}
_ = c.ServeJSON()
return
}
if dup > 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "已存在同名角色(含平台默认角色),请更换名称"}
_ = c.ServeJSON()
return
}
status := uint8(1)
if p.Status != nil {
status = *p.Status
}
rights := sanitizeTenantRights(p.Rights)
role := &models.AdminRole{
TenantID: tid,
Cid: 2,
IsCustom: 1,
Name: p.Name,
Status: status,
Rights: rights,
}
id, err := models.Orm.Insert(role)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "创建失败"}
_ = c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success", "data": map[string]interface{}{"id": id}}
_ = c.ServeJSON()
}
func (c *BackendRoleController) UpdateRole() {
tid, ok := c.currentTenantID()
if !ok {
return
}
idStr := c.Ctx.Input.Param(":id")
id, _ := strconv.ParseUint(idStr, 10, 64)
if id == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "id 不能为空"}
_ = c.ServeJSON()
return
}
var p backendRolePayload
raw, _ := io.ReadAll(c.Ctx.Request.Body)
if err := json.Unmarshal(raw, &p); err != nil {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "参数错误"}
_ = c.ServeJSON()
return
}
update := map[string]interface{}{}
if strings.TrimSpace(p.Name) != "" {
update["name"] = strings.TrimSpace(p.Name)
}
if p.Status != nil {
update["status"] = *p.Status
}
if p.Rights != nil {
update["rights"] = sanitizeTenantRights(p.Rights)
}
if len(update) == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "无更新字段"}
_ = c.ServeJSON()
return
}
var target models.AdminRole
if e := models.Orm.QueryTable(new(models.AdminRole)).
Filter("id", id).
Filter("cid", 2).
One(&target); e == nil && tenantRoleReadOnly(target) {
c.Data["json"] = map[string]interface{}{"code": 403, "msg": "该角色由平台端统一下发,租户端不能修改"}
_ = c.ServeJSON()
return
}
if newName, ok := update["name"]; ok {
dup, derr := models.Orm.QueryTable(new(models.AdminRole)).
Filter("cid", 2).
Filter("tenant_id__in", []uint64{0, tid}).
Filter("name", newName).
Exclude("id", id).
Count()
if derr != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "更新失败"}
_ = c.ServeJSON()
return
}
if dup > 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "已存在同名角色(含平台默认角色),请更换名称"}
_ = c.ServeJSON()
return
}
}
exist, err := models.Orm.QueryTable(new(models.AdminRole)).
Filter("id", id).
Filter("cid", 2).
Filter("tenant_id", tid).
Count()
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "更新失败"}
_ = c.ServeJSON()
return
}
if exist == 0 {
c.Data["json"] = map[string]interface{}{"code": 404, "msg": "角色不存在"}
_ = c.ServeJSON()
return
}
if _, err := models.Orm.QueryTable(new(models.AdminRole)).
Filter("id", id).
Filter("cid", 2).
Filter("tenant_id", tid).
Update(update); err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "更新失败"}
_ = c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success"}
_ = c.ServeJSON()
}
func (c *BackendRoleController) DeleteRole() {
tid, ok := c.currentTenantID()
if !ok {
return
}
idStr := c.Ctx.Input.Param(":id")
id, _ := strconv.ParseUint(idStr, 10, 64)
if id == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "id 不能为空"}
_ = c.ServeJSON()
return
}
var target models.AdminRole
if e := models.Orm.QueryTable(new(models.AdminRole)).
Filter("id", id).
Filter("cid", 2).
One(&target); e == nil && tenantRoleReadOnly(target) {
c.Data["json"] = map[string]interface{}{"code": 403, "msg": "该角色由平台端统一下发,租户端不能删除"}
_ = c.ServeJSON()
return
}
cnt, err := models.Orm.QueryTable(new(models.AdminRole)).
Filter("id", id).
Filter("cid", 2).
Filter("tenant_id", tid).
Delete()
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "删除失败"}
_ = c.ServeJSON()
return
}
if cnt == 0 {
c.Data["json"] = map[string]interface{}{"code": 404, "msg": "角色不存在"}
_ = c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success"}
_ = c.ServeJSON()
}