108 lines
2.7 KiB
Go
108 lines
2.7 KiB
Go
package controllers
|
||
|
||
import (
|
||
"encoding/json"
|
||
"io"
|
||
"math/rand"
|
||
"strings"
|
||
"time"
|
||
|
||
"server/pkg/passwordutil"
|
||
"server/services"
|
||
|
||
beego "github.com/beego/beego/v2/server/web"
|
||
)
|
||
|
||
// PlatformUserController 平台端用户相关(简化:当前用户信息落在 yz_system_tenant_user)
|
||
type PlatformUserController struct {
|
||
beego.Controller
|
||
}
|
||
|
||
type addUserPayload struct {
|
||
Tid uint64 `json:"tid"`
|
||
Account string `json:"account"`
|
||
Password string `json:"password"`
|
||
Name string `json:"name"`
|
||
Phone string `json:"phone"`
|
||
Email string `json:"email"`
|
||
Status *int8 `json:"status"`
|
||
Remark *string `json:"remark"`
|
||
}
|
||
|
||
// AddUser 添加用户(绑定到租户)
|
||
// POST /platform/addUser
|
||
func (c *PlatformUserController) AddUser() {
|
||
var p addUserPayload
|
||
|
||
// 兼容 JSON body
|
||
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.Account = strings.TrimSpace(p.Account)
|
||
p.Password = strings.TrimSpace(p.Password)
|
||
p.Name = strings.TrimSpace(p.Name)
|
||
p.Phone = strings.TrimSpace(p.Phone)
|
||
p.Email = strings.TrimSpace(p.Email)
|
||
|
||
if p.Tid == 0 {
|
||
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "tid 不能为空"}
|
||
_ = c.ServeJSON()
|
||
return
|
||
}
|
||
if p.Account == "" {
|
||
c.Data["json"] = map[string]interface{}{"code": 400, "msg": "account 不能为空"}
|
||
_ = c.ServeJSON()
|
||
return
|
||
}
|
||
if 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
|
||
}
|
||
|
||
status := int8(1)
|
||
if p.Status != nil {
|
||
status = *p.Status
|
||
}
|
||
|
||
// 生成 uid:8位数字即可(10000000~99999999)
|
||
rand.Seed(time.Now().UnixNano())
|
||
var uid uint64
|
||
for i := 0; i < 5; i++ {
|
||
uid = uint64(10000000 + rand.Intn(90000000))
|
||
// 尝试写入(若冲突由唯一索引兜底,外层再重试)
|
||
account := &p.Account
|
||
name := &p.Name
|
||
phone := &p.Phone
|
||
email := &p.Email
|
||
hashedPwd := hashed
|
||
password := &hashedPwd
|
||
|
||
_, err := services.BindTenantUser(p.Tid, uid, account, name, phone, email, password, 0, status, p.Remark)
|
||
if err == nil {
|
||
c.Data["json"] = map[string]interface{}{
|
||
"code": 200,
|
||
"msg": "success",
|
||
"data": map[string]interface{}{"tid": p.Tid, "uid": uid},
|
||
}
|
||
_ = c.ServeJSON()
|
||
return
|
||
}
|
||
// 轻量重试
|
||
time.Sleep(5 * time.Millisecond)
|
||
}
|
||
|
||
c.Data["json"] = map[string]interface{}{"code": 500, "msg": "添加失败,请重试"}
|
||
_ = c.ServeJSON()
|
||
}
|