You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.8 KiB
75 lines
1.8 KiB
// Code scaffolded by goctl. Safe to edit.
|
|
// goctl 1.9.2
|
|
|
|
package profile
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/youruser/base/internal/svc"
|
|
"github.com/youruser/base/internal/types"
|
|
jwtutil "github.com/youruser/base/internal/util/jwt"
|
|
"github.com/youruser/base/model"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type SwitchOrgLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
// 切换当前机构
|
|
func NewSwitchOrgLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SwitchOrgLogic {
|
|
return &SwitchOrgLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *SwitchOrgLogic) SwitchOrg(req *types.SwitchOrgRequest) (resp *types.SwitchOrgResponse, err error) {
|
|
userId, _ := l.ctx.Value("userId").(int64)
|
|
username, _ := l.ctx.Value("username").(string)
|
|
if userId == 0 {
|
|
return nil, fmt.Errorf("未获取到用户信息")
|
|
}
|
|
|
|
// 验证用户属于该机构
|
|
userOrg, err := model.UserOrgFindOne(l.ctx, l.svcCtx.DB, userId, req.OrgId)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("您不属于该机构")
|
|
}
|
|
|
|
// 获取角色编码
|
|
roleCode := model.RoleUser // 默认角色
|
|
if userOrg.RoleId > 0 {
|
|
role, err := model.RoleFindOne(l.ctx, l.svcCtx.DB, userOrg.RoleId)
|
|
if err == nil {
|
|
roleCode = role.Code
|
|
}
|
|
}
|
|
|
|
// 更新用户的 CurrentOrgId
|
|
user, err := model.FindOne(l.ctx, l.svcCtx.DB, userId)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("获取用户信息失败: %v", err)
|
|
}
|
|
user.CurrentOrgId = req.OrgId
|
|
err = model.Update(l.ctx, l.svcCtx.DB, user)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("更新用户机构失败: %v", err)
|
|
}
|
|
|
|
// 生成新的 JWT Token
|
|
token, err := jwtutil.GenerateToken(userId, username, roleCode, req.OrgId)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("生成Token失败: %v", err)
|
|
}
|
|
|
|
return &types.SwitchOrgResponse{
|
|
Token: token,
|
|
}, nil
|
|
}
|
|
|