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

489 lines
12 KiB
Go

package controllers
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand"
"strconv"
"strings"
"time"
"server/models"
"server/pkg/identity"
"server/pkg/passwordutil"
"server/services"
authsvc "server/services/auth"
"github.com/beego/beego/v2/client/orm"
beego "github.com/beego/beego/v2/server/web"
)
func syncTenantUserToAuth(row *models.SystemTenantUser, updatePassword bool) {
if row == nil {
return
}
in := authsvc.SyncTenantUserInput{
Tid: row.Tid,
GroupID: row.GroupID,
OrgID: row.OrgID,
Status: row.Status,
IsDefault: row.IsDefault,
UpdatePassword: updatePassword,
}
if row.Account != nil {
in.Account = strings.TrimSpace(*row.Account)
}
if row.Name != nil {
in.Name = strings.TrimSpace(*row.Name)
}
if row.Phone != nil {
in.Phone = strings.TrimSpace(*row.Phone)
}
if row.Email != nil {
in.Email = strings.TrimSpace(*row.Email)
}
if row.Password != nil {
in.PasswordHash = *row.Password
}
if err := authsvc.SyncTenantUser(in); err != nil {
log.Printf("[auth] 同步租户用户到认证中心失败 tid=%d account=%s: %v", row.Tid, in.Account, err)
}
}
func removeTenantUserFromAuth(row *models.SystemTenantUser) {
if row == nil {
return
}
account, phone, email := "", "", ""
if row.Account != nil {
account = strings.TrimSpace(*row.Account)
}
if row.Phone != nil {
phone = strings.TrimSpace(*row.Phone)
}
if row.Email != nil {
email = strings.TrimSpace(*row.Email)
}
if err := authsvc.RemoveTenantUser(row.Tid, account, phone, email); err != nil {
log.Printf("[auth] 删除认证中心企业绑定失败 tid=%d account=%s: %v", row.Tid, account, err)
}
}
type PlatformTenantUserController struct {
beego.Controller
}
type tenantUserPayload struct {
Tid uint64 `json:"tid"`
Uid uint64 `json:"uid"`
Account *string `json:"account"`
Name *string `json:"name"`
Phone *string `json:"phone"`
Email *string `json:"email"`
Password *string `json:"password"`
IsDefault *int8 `json:"is_default"`
Status *int8 `json:"status"`
OrgID *uint64 `json:"org_id"`
Remark *string `json:"remark"`
}
func (c *PlatformTenantUserController) GetTenantOrganizations() {
if _, err := requirePlatform(&c.Controller); err != nil {
code := identity.Status(err)
c.Data["json"] = map[string]interface{}{"code": code, "msg": err.Error()}
_ = c.ServeJSON()
return
}
tid, _ := c.GetUint64("tid")
list := make([]map[string]interface{}, 0)
if tid > 0 {
var rows []models.BackendOrganization
_, _ = models.Orm.QueryTable(new(models.BackendOrganization)).
Filter("tid", tid).
Filter("delete_time__isnull", true).
OrderBy("sort", "id").
All(&rows)
for i := range rows {
list = append(list, map[string]interface{}{
"id": rows[i].ID,
"org_name": rows[i].OrgName,
"parent_id": rows[i].ParentID,
"sort": rows[i].Sort,
"status": rows[i].Status,
})
}
}
c.Data["json"] = map[string]interface{}{
"code": 200,
"msg": "success",
"data": map[string]interface{}{"list": list},
}
_ = c.ServeJSON()
}
func (c *PlatformTenantUserController) GetTenantUserList() {
tid, _ := c.GetUint64("tid")
uid, _ := c.GetUint64("uid")
keyword := strings.TrimSpace(c.GetString("keyword"))
qs := models.Orm.QueryTable(new(models.SystemTenantUser))
var cond *orm.Condition
needCond := false
if tid > 0 {
if cond == nil {
cond = orm.NewCondition()
}
cond = cond.And("tid", tid)
needCond = true
}
if uid > 0 {
if cond == nil {
cond = orm.NewCondition()
}
cond = cond.And("uid", uid)
needCond = true
}
if keyword != "" {
kwCond := orm.NewCondition()
kwCond = kwCond.Or("name__icontains", keyword).
Or("phone__icontains", keyword).
Or("email__icontains", keyword).
Or("account__icontains", keyword)
if cond == nil {
cond = kwCond
} else {
cond = cond.AndCond(kwCond)
}
needCond = true
}
if needCond {
qs = qs.SetCond(cond)
}
var rows []models.SystemTenantUser
_, err := qs.OrderBy("-is_default", "-id").All(&rows)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "查询失败: " + err.Error()}
_ = c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{
"code": 200,
"msg": "success",
"data": map[string]interface{}{
"list": rows,
"total": len(rows),
},
}
_ = c.ServeJSON()
}
func (c *PlatformTenantUserController) GetTenantUsersByTid() {
tidStr := c.Ctx.Input.Param(":tid")
tid, _ := strconv.ParseUint(tidStr, 10, 64)
if tid == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "tid 不能为空"}
_ = c.ServeJSON()
return
}
var rows []models.SystemTenantUser
_, err := models.Orm.QueryTable(new(models.SystemTenantUser)).
Filter("tid", tid).
OrderBy("-is_default", "-id").
All(&rows)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "查询失败: " + err.Error()}
_ = c.ServeJSON()
return
}
c.Data["json"] = map[string]interface{}{
"code": 200,
"msg": "success",
"data": map[string]interface{}{"list": rows, "total": len(rows)},
}
_ = c.ServeJSON()
}
func (c *PlatformTenantUserController) GetTenantUserDetail() {
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if err != nil || id == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "无效ID"}
_ = c.ServeJSON()
return
}
var row models.SystemTenantUser
err = models.Orm.QueryTable(new(models.SystemTenantUser)).Filter("id", id).One(&row)
if 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": row}
_ = c.ServeJSON()
}
func (c *PlatformTenantUserController) CreateTenantUser() {
p, ok := c.parsePayload()
if !ok {
return
}
if p.Tid == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "tid 不能为空"}
_ = c.ServeJSON()
return
}
if p.Account == nil || strings.TrimSpace(*p.Account) == "" {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "account 不能为空"}
_ = c.ServeJSON()
return
}
if p.Password == nil || strings.TrimSpace(*p.Password) == "" {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "password 不能为空"}
_ = c.ServeJSON()
return
}
hashed, err := passwordutil.Hash(*p.Password)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": err.Error()}
_ = c.ServeJSON()
return
}
p.Password = &hashed
if p.Uid == 0 {
uid, err := ensureTenantUIDForNewUser(
p.Tid,
strOrEmpty(p.Account),
strOrEmpty(p.Name),
strOrEmpty(p.Phone),
strOrEmpty(p.Email),
strOrEmpty(p.Password),
)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "生成租户用户ID失败"}
_ = c.ServeJSON()
return
}
p.Uid = uid
}
if check, err := services.CheckTenantUserQuota(p.Tid, p.Uid); err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "用户数校验失败: " + err.Error()}
_ = c.ServeJSON()
return
} else if !check.Allowed {
c.Data["json"] = map[string]interface{}{
"code": 400,
"msg": fmt.Sprintf("该租户用户数已达上限(%d/%d),请先为租户增购用户数", check.Used, check.Quota),
}
_ = c.ServeJSON()
return
}
isDefault := int8(0)
status := int8(1)
if p.IsDefault != nil {
isDefault = *p.IsDefault
}
if p.Status != nil {
status = *p.Status
}
id, err := services.BindTenantUser(p.Tid, p.Uid, p.Account, p.Name, p.Phone, p.Email, nil, nil, p.Password, isDefault, status, p.Remark)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "创建失败: " + err.Error()}
_ = c.ServeJSON()
return
}
if p.OrgID != nil && *p.OrgID > 0 {
_, _ = models.Orm.QueryTable(new(models.SystemTenantUser)).
Filter("id", id).
Update(map[string]interface{}{"org_id": *p.OrgID})
}
if isDefault == 1 {
_ = services.SetDefaultTenant(p.Uid, p.Tid)
if adminRoleID, err := models.GetTenantAdminRole(); err == nil && adminRoleID > 0 {
_, _ = models.Orm.QueryTable(new(models.SystemTenantUser)).
Filter("id", id).
Update(map[string]interface{}{"group_id": adminRoleID})
}
}
var created models.SystemTenantUser
if e := models.Orm.QueryTable(new(models.SystemTenantUser)).Filter("id", id).One(&created); e == nil {
syncTenantUserToAuth(&created, false)
}
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success", "data": map[string]interface{}{"id": id}}
_ = c.ServeJSON()
}
func (c *PlatformTenantUserController) EditTenantUser() {
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if err != nil || id == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "无效ID"}
_ = c.ServeJSON()
return
}
p, ok := c.parsePayload()
if !ok {
return
}
update := map[string]interface{}{}
if p.Tid > 0 {
update["tid"] = p.Tid
}
if p.Uid > 0 {
update["uid"] = p.Uid
}
if p.Account != nil {
update["account"] = p.Account
}
if p.Name != nil {
update["name"] = p.Name
}
if p.Phone != nil {
update["phone"] = p.Phone
}
if p.Email != nil {
update["email"] = p.Email
}
if p.Password != nil {
hashed, err := passwordutil.Hash(*p.Password)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": err.Error()}
_ = c.ServeJSON()
return
}
update["password"] = hashed
}
if p.IsDefault != nil {
update["is_default"] = *p.IsDefault
}
if p.Status != nil {
update["status"] = *p.Status
}
if p.OrgID != nil {
update["org_id"] = *p.OrgID
}
if p.Remark != nil {
update["remark"] = p.Remark
}
if len(update) == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "无更新字段"}
_ = c.ServeJSON()
return
}
_, err = models.Orm.QueryTable(new(models.SystemTenantUser)).Filter("id", id).Update(update)
if err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "更新失败: " + err.Error()}
_ = c.ServeJSON()
return
}
if p.IsDefault != nil && *p.IsDefault == 1 && p.Uid > 0 && p.Tid > 0 {
_ = services.SetDefaultTenant(p.Uid, p.Tid)
}
var updated models.SystemTenantUser
if err := models.Orm.QueryTable(new(models.SystemTenantUser)).Filter("id", id).One(&updated); err == nil {
syncTenantUserToAuth(&updated, p.Password != nil)
}
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success"}
_ = c.ServeJSON()
}
func (c *PlatformTenantUserController) DeleteTenantUser() {
id, err := strconv.ParseUint(c.Ctx.Input.Param(":id"), 10, 64)
if err != nil || id == 0 {
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "无效ID"}
_ = c.ServeJSON()
return
}
var row models.SystemTenantUser
_ = models.Orm.QueryTable(new(models.SystemTenantUser)).Filter("id", id).One(&row)
if err := services.UnbindTenantUser(id); err != nil {
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "删除失败: " + err.Error()}
_ = c.ServeJSON()
return
}
removeTenantUserFromAuth(&row)
c.Data["json"] = map[string]interface{}{"code": 200, "msg": "success"}
_ = c.ServeJSON()
}
func (c *PlatformTenantUserController) parsePayload() (tenantUserPayload, bool) {
var p tenantUserPayload
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 tenantUserPayload{}, false
}
return p, true
}
func ensureTenantUIDForNewUser(tid uint64, account, name, phone, email, passwordHash string) (uint64, error) {
if tid == 0 {
return 0, errors.New("tid 不能为空")
}
id, err := authsvc.SyncTenantUserAndGetIdentity(authsvc.SyncTenantUserInput{
Tid: tid,
Account: strings.TrimSpace(account),
Name: strings.TrimSpace(name),
Phone: strings.TrimSpace(phone),
Email: strings.TrimSpace(email),
PasswordHash: strings.TrimSpace(passwordHash),
Status: 1,
})
if err == nil && id > 0 {
return id, nil
}
if err != nil {
log.Printf("[auth] 预建身份失败,退回随机 uid: %v", err)
}
return generateTenantUID(tid)
}
func strOrEmpty(p *string) string {
if p == nil {
return ""
}
return *p
}
func generateTenantUID(tid uint64) (uint64, error) {
rand.Seed(time.Now().UnixNano())
for i := 0; i < 8; i++ {
uid := uint64(10000000 + rand.Intn(90000000))
cnt, err := models.Orm.QueryTable(new(models.SystemTenantUser)).
Filter("tid", tid).
Filter("uid", uid).
Count()
if err != nil {
return 0, err
}
if cnt == 0 {
return uid, nil
}
}
return 0, errors.New("uid collision")
}