287 lines
9.0 KiB
Go
287 lines
9.0 KiB
Go
package logic
|
||
|
||
import (
|
||
"context"
|
||
"sort"
|
||
|
||
"github.com/gogf/gf/v2/errors/gerror"
|
||
|
||
"easygoadmin/api/v1"
|
||
"easygoadmin/internal/consts"
|
||
"easygoadmin/internal/dao"
|
||
"easygoadmin/internal/service"
|
||
"easygoadmin/utility/crypto"
|
||
"easygoadmin/utility/upload"
|
||
)
|
||
|
||
// ============================== 个人中心与菜单聚合业务实现 ==============================
|
||
|
||
// sIndex 个人中心与菜单聚合业务实现
|
||
// 实现 service.IIndex 接口,承载当前用户信息、菜单树与个人资料相关业务
|
||
type sIndex struct{}
|
||
|
||
func init() {
|
||
service.RegisterIndex(&sIndex{})
|
||
}
|
||
|
||
// GetUser 获取当前登录用户信息
|
||
//
|
||
// 敏感字段永不返回;角色与权限来自身份加载器,
|
||
// 超管返回通配权限码,供前端放开全部按钮权限
|
||
func (s *sIndex) GetUser(ctx context.Context, req *v1.GetUserReq) (res *v1.GetUserRes, err error) {
|
||
uid := consts.GetUserID(ctx)
|
||
if uid <= 0 {
|
||
return nil, gerror.NewCode(consts.CodeUnauthorized)
|
||
}
|
||
one, err := dao.User.Ctx(ctx).Where("id", uid).One()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(one) == 0 {
|
||
return nil, gerror.NewCode(consts.CodeUserNotFound)
|
||
}
|
||
|
||
// 角色编码与权限节点(与 JWT 中间件同源:user_role → role / role_menu → menu.permission)
|
||
roles := consts.GetRoles(ctx)
|
||
perms := consts.GetPerms(ctx)
|
||
if len(roles) == 0 {
|
||
if idn, lerr := LoadIdentity(ctx, uid); lerr == nil && idn != nil {
|
||
roles, perms = idn.Roles, idn.Perms
|
||
}
|
||
}
|
||
if roles == nil {
|
||
roles = []string{}
|
||
}
|
||
// 超管返回通配权限码 *:*:*(前端据此放开全部按钮权限)
|
||
if s.isSuperAdmin(ctx, uid) {
|
||
perms = []string{consts.PermWildcard}
|
||
} else if perms == nil {
|
||
perms = []string{}
|
||
}
|
||
|
||
// 城市编码数组(省市区街道,空编码跳过);city_info 为空时按编码回填名称
|
||
city := make([]string, 0, 4)
|
||
for _, col := range []string{"province_code", "city_code", "district_code", "street_code"} {
|
||
if v := one[col].String(); v != "" {
|
||
city = append(city, v)
|
||
}
|
||
}
|
||
cityInfo := one["city_info"].String()
|
||
if cityInfo == "" && len(city) > 0 {
|
||
cityInfo = ResolveCityNames(ctx, city, ",")
|
||
}
|
||
return &v1.GetUserRes{
|
||
Id: one["id"].Int64(),
|
||
Username: one["username"].String(),
|
||
Realname: one["realname"].String(),
|
||
Gender: one["gender"].Int(),
|
||
Avatar: upload.GetFileUrl(ctx, one["avatar"].String()),
|
||
Mobile: one["mobile"].String(),
|
||
Email: one["email"].String(),
|
||
DeptId: one["dept_id"].Int(),
|
||
LevelId: one["level_id"].Int(),
|
||
PositionId: one["position_id"].Int(),
|
||
City: city,
|
||
CityInfo: cityInfo,
|
||
Address: one["address"].String(),
|
||
Intro: one["intro"].String(),
|
||
Status: one["status"].Int(),
|
||
Note: one["note"].String(),
|
||
TenantId: one["tenant_id"].Int(),
|
||
Roles: roles,
|
||
Permissions: perms,
|
||
}, nil
|
||
}
|
||
|
||
// GetMenus 获取当前用户菜单树
|
||
//
|
||
// 关联路径:user → user_role → role → role_menu → menu,超管返回全量
|
||
func (s *sIndex) GetMenus(ctx context.Context, req *v1.GetMenusReq) (res *v1.GetMenusRes, err error) {
|
||
return s.getMenuTree(ctx)
|
||
}
|
||
|
||
// GetMenusById 获取当前用户菜单树(带路径参数)
|
||
//
|
||
// 与无路径参数的菜单路由共用同一处理逻辑
|
||
func (s *sIndex) GetMenusById(ctx context.Context, req *v1.GetMenusByIdReq) (res *v1.GetMenusRes, err error) {
|
||
return s.getMenuTree(ctx)
|
||
}
|
||
|
||
// getMenuTree 组装菜单树
|
||
//
|
||
// 仅取目录与菜单节点,按钮权限节点不进菜单树
|
||
func (s *sIndex) getMenuTree(ctx context.Context) (*v1.GetMenusRes, error) {
|
||
uid := consts.GetUserID(ctx)
|
||
if uid <= 0 {
|
||
return nil, gerror.NewCode(consts.CodeUnauthorized)
|
||
}
|
||
|
||
// 1. 可见菜单集合:超管全量,其余按角色关联
|
||
// 仅取目录/菜单(type=0)、启用(status=0)、非隐藏(hide=0);按钮权限节点不进菜单树(由 GetUser.permissions 下发)
|
||
query := dao.Menu.Ctx(ctx).Where("type", 0).Where("status", 0).Where("hide", 0)
|
||
if !s.isSuperAdmin(ctx, uid) {
|
||
roleRows, err := dao.UserRole.Ctx(ctx).Where("user_id", uid).All()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(roleRows) == 0 {
|
||
empty := []*v1.MenuTreeItem{}
|
||
return &empty, nil
|
||
}
|
||
roleIds := make([]int64, 0, len(roleRows))
|
||
for _, r := range roleRows {
|
||
roleIds = append(roleIds, r["role_id"].Int64())
|
||
}
|
||
menuRows, err := dao.RoleMenu.Ctx(ctx).WhereIn("role_id", roleIds).All()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(menuRows) == 0 {
|
||
empty := []*v1.MenuTreeItem{}
|
||
return &empty, nil
|
||
}
|
||
menuIds := make([]int64, 0, len(menuRows))
|
||
for _, r := range menuRows {
|
||
menuIds = append(menuIds, r["menu_id"].Int64())
|
||
}
|
||
query = query.WhereIn("id", menuIds)
|
||
}
|
||
rows, err := query.Order("sort, id").All()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
// 2. 平铺节点
|
||
nodes := make(map[int64]*v1.MenuTreeItem, len(rows))
|
||
ids := make([]int64, 0, len(rows))
|
||
for _, row := range rows {
|
||
item := &v1.MenuTreeItem{
|
||
Id: row["id"].Int64(),
|
||
ParentId: row["parent_id"].Int(),
|
||
Name: row["name"].String(),
|
||
Icon: row["icon"].String(),
|
||
Icon2: row["icon2"].String(),
|
||
Path: row["path"].String(),
|
||
Component: row["component"].String(),
|
||
Permission: row["permission"].String(),
|
||
Target: row["target"].Int(),
|
||
Type: row["type"].Int(),
|
||
Status: row["status"].Int(),
|
||
Hide: row["hide"].Int(),
|
||
Sort: row["sort"].Int(),
|
||
Children: []*v1.MenuTreeItem{},
|
||
}
|
||
nodes[item.Id] = item
|
||
ids = append(ids, item.Id)
|
||
}
|
||
|
||
// 3. 挂树:父节点不在集合内(未授权/顶级)一律挂根,避免菜单丢失
|
||
roots := make([]*v1.MenuTreeItem, 0, len(ids))
|
||
for _, id := range ids {
|
||
node := nodes[id]
|
||
if node.ParentId != 0 {
|
||
if parent, ok := nodes[int64(node.ParentId)]; ok {
|
||
parent.Children = append(parent.Children, node)
|
||
continue
|
||
}
|
||
}
|
||
roots = append(roots, node)
|
||
}
|
||
// 父子均已按 sort,id 查询,子级顺序天然有序;根级再兜底一次
|
||
sort.SliceStable(roots, func(i, j int) bool {
|
||
if roots[i].Sort == roots[j].Sort {
|
||
return roots[i].Id < roots[j].Id
|
||
}
|
||
return roots[i].Sort < roots[j].Sort
|
||
})
|
||
return &roots, nil
|
||
}
|
||
|
||
// isSuperAdmin 判断是否超级管理员
|
||
// 优先读取上下文角色,未命中时回源用户角色表
|
||
func (s *sIndex) isSuperAdmin(ctx context.Context, uid int) bool {
|
||
for _, r := range consts.GetRoles(ctx) {
|
||
if r == consts.RoleCodeSuperAdmin {
|
||
return true
|
||
}
|
||
}
|
||
// 角色缓存未命中时回源
|
||
roleRows, err := dao.UserRole.Ctx(ctx).Where("user_id", uid).All()
|
||
if err != nil || len(roleRows) == 0 {
|
||
return false
|
||
}
|
||
roleIds := make([]int64, 0, len(roleRows))
|
||
for _, r := range roleRows {
|
||
roleIds = append(roleIds, r["role_id"].Int64())
|
||
}
|
||
count, err := dao.Role.Ctx(ctx).WhereIn("id", roleIds).Where("code", consts.RoleCodeSuperAdmin).Count()
|
||
return err == nil && count > 0
|
||
}
|
||
|
||
// UpdatePassword 修改个人密码
|
||
//
|
||
// 校验旧密码后使用 bcrypt 重写密码与盐
|
||
func (s *sIndex) UpdatePassword(ctx context.Context, req *v1.UpdatePasswordReq) (res *v1.UpdatePasswordRes, err error) {
|
||
uid := consts.GetUserID(ctx)
|
||
if uid <= 0 {
|
||
return nil, gerror.NewCode(consts.CodeUnauthorized)
|
||
}
|
||
one, err := dao.User.Ctx(ctx).Where("id", uid).Fields("id, password, salt").One()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if len(one) == 0 {
|
||
return nil, gerror.NewCode(consts.CodeUserNotFound)
|
||
}
|
||
// 旧密码校验(外部 salt + bcrypt(password+salt);salt 为空兼容旧数据)
|
||
if !crypto.IsBcrypt(one["password"].String()) || !crypto.VerifyPassword(one["password"].String(), req.Password, one["salt"].String()) {
|
||
return nil, gerror.NewCode(consts.CodeOldPwdWrong)
|
||
}
|
||
salt := crypto.GenerateSalt()
|
||
hashed, err := crypto.HashPassword(req.NewPassword, salt)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if _, err = dao.User.Ctx(ctx).Where("id", uid).Data(map[string]any{
|
||
"password": hashed,
|
||
"salt": salt,
|
||
}).Update(); err != nil {
|
||
return nil, err
|
||
}
|
||
return &v1.UpdatePasswordRes{}, nil
|
||
}
|
||
|
||
// UpdateProfile 更新个人信息
|
||
//
|
||
// 头像执行临时转正,城市信息优先由编码数组解析名称,审计字段由全局钩子盖章
|
||
func (s *sIndex) UpdateProfile(ctx context.Context, req *v1.UpdateProfileReq) (res *v1.UpdateProfileRes, err error) {
|
||
uid := consts.GetUserID(ctx)
|
||
if uid <= 0 {
|
||
return nil, gerror.NewCode(consts.CodeUnauthorized)
|
||
}
|
||
data := map[string]any{
|
||
"realname": req.Realname,
|
||
"gender": req.Gender,
|
||
"avatar": SaveFileField(ctx, req.Avatar, "user"), // 头像 temp 转正 + 剥离域名
|
||
"mobile": req.Mobile,
|
||
"email": req.Email,
|
||
"city_info": req.CityInfo,
|
||
"province_code": cityCodeAt(req.City, 0),
|
||
"city_code": cityCodeAt(req.City, 1),
|
||
"district_code": cityCodeAt(req.City, 2),
|
||
"street_code": cityCodeAt(req.City, 3),
|
||
"address": req.Address,
|
||
"intro": req.Intro,
|
||
}
|
||
// 城市信息:优先由编码数组解析名称
|
||
if len(req.City) > 0 {
|
||
if info := ResolveCityNames(ctx, req.City, ","); info != "" {
|
||
data["city_info"] = info
|
||
}
|
||
}
|
||
if _, err = dao.User.Ctx(ctx).Where("id", uid).Data(data).Update(); err != nil {
|
||
return nil, err
|
||
}
|
||
return &v1.UpdateProfileRes{}, nil
|
||
}
|