zhangqian
2023-10-13 4a23356a5840b624c81dda44b0028ed8fc3656cc
销售线索简单数据权限
11个文件已修改
1002 ■■■■ 已修改文件
api/v1/captcha.go 104 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
api/v1/salesLeads.go 9 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
api/v1/user.go 723 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
middleware/jwt.go 11 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
model/request/jwt.go 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
model/user.go 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/base.go 32 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/image.go 31 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/index.go 16 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
router/user.go 48 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
utils/clamis.go 24 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
api/v1/captcha.go
@@ -1,62 +1,50 @@
package v1
import (
    "aps_crm/conf"
    "aps_crm/constvar"
    "aps_crm/model/response"
    "aps_crm/pkg/contextx"
    "aps_crm/pkg/convertx"
    "aps_crm/pkg/ecode"
    "aps_crm/pkg/logx"
    "github.com/gin-gonic/gin"
    "github.com/mojocn/base64Captcha"
    "time"
)
type BaseApi struct{}
// Captcha
//    @Tags        Base
//    @Summary    获取验证码
//    @Produce    application/json
//    @Success    200    {object}    contextx.Response{data=response.LoginResponse}    "成功"
//    @Router        /api/base/captcha [post]
func (slf *BaseApi) Captcha(c *gin.Context) {
    ctx, ok := contextx.NewContext(c, nil)
    if !ok {
        return
    }
    // 判断验证码是否开启
    openCaptcha := conf.Conf.Captcha.OpenCaptcha               // 是否开启防爆次数
    openCaptchaTimeOut := conf.Conf.Captcha.OpenCaptchaTimeOut // 缓存超时时间
    key := c.ClientIP()
    v, ok := constvar.BlackCache.Get(key)
    if !ok {
        constvar.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
    }
    var oc bool
    if openCaptcha == 0 || convertx.InterfaceToInt(v) > openCaptcha { // 0 表示每次登录都需要验证码 或者当前次数已超过防爆次数
        oc = true
    }
    // 字符,公式,验证码配置
    // 生成默认数字的driver
    driver := base64Captcha.NewDriverDigit(conf.Conf.Captcha.ImgHeight, conf.Conf.Captcha.ImgWidth, conf.Conf.Captcha.KeyLong, 0.7, 80)
    cp := base64Captcha.NewCaptcha(driver, store)
    id, b64s, err := cp.Generate()
    captcha := store.Get(id, false)
    logx.Infof("Captcha Generate captchaId:%v captcha:%v", id, captcha)
    if err != nil {
        logx.Errorf("Captcha Generate err:%v", err)
        ctx.Fail(ecode.CaptchaGenerateFailed)
        return
    }
    ctx.OkWithDetailed(response.CaptchaResponse{
        CaptchaId:     id,
        PicPath:       b64s,
        CaptchaLength: conf.Conf.Captcha.KeyLong,
        OpenCaptcha:   oc,
    })
}
//
//// Captcha
////    @Tags        Base
////    @Summary    获取验证码
////    @Produce    application/json
////    @Success    200    {object}    contextx.Response{data=response.LoginResponse}    "成功"
////    @Router        /api/base/captcha [post]
//func (slf *BaseApi) Captcha(c *gin.Context) {
//    ctx, ok := contextx.NewContext(c, nil)
//    if !ok {
//        return
//    }
//
//    // 判断验证码是否开启
//    openCaptcha := conf.Conf.Captcha.OpenCaptcha               // 是否开启防爆次数
//    openCaptchaTimeOut := conf.Conf.Captcha.OpenCaptchaTimeOut // 缓存超时时间
//    key := c.ClientIP()
//    v, ok := constvar.BlackCache.Get(key)
//    if !ok {
//        constvar.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
//    }
//
//    var oc bool
//    if openCaptcha == 0 || convertx.InterfaceToInt(v) > openCaptcha { // 0 表示每次登录都需要验证码 或者当前次数已超过防爆次数
//        oc = true
//    }
//    // 字符,公式,验证码配置
//    // 生成默认数字的driver
//    driver := base64Captcha.NewDriverDigit(conf.Conf.Captcha.ImgHeight, conf.Conf.Captcha.ImgWidth, conf.Conf.Captcha.KeyLong, 0.7, 80)
//    cp := base64Captcha.NewCaptcha(driver, store)
//    id, b64s, err := cp.Generate()
//    captcha := store.Get(id, false)
//    logx.Infof("Captcha Generate captchaId:%v captcha:%v", id, captcha)
//    if err != nil {
//        logx.Errorf("Captcha Generate err:%v", err)
//        ctx.Fail(ecode.CaptchaGenerateFailed)
//        return
//    }
//
//    ctx.OkWithDetailed(response.CaptchaResponse{
//        CaptchaId:     id,
//        PicPath:       b64s,
//        CaptchaLength: conf.Conf.Captcha.KeyLong,
//        OpenCaptcha:   oc,
//    })
//}
api/v1/salesLeads.go
@@ -7,6 +7,7 @@
    "aps_crm/model/response"
    "aps_crm/pkg/contextx"
    "aps_crm/pkg/ecode"
    "aps_crm/utils"
    "github.com/gin-gonic/gin"
)
@@ -152,6 +153,14 @@
        return
    }
    userInfo := utils.GetUserInfo(c)
    if userInfo.UserType == constvar.UserTypeSub {
        if params.SearchMap == nil {
            params.SearchMap = make(map[string]interface{}, 0)
        }
        params.SearchMap["member_id"] = userInfo.CrmUserId
    }
    salesLeadss, total, errCode := salesLeadsService.GetSalesLeadsList(params.Page, params.PageSize, params.SearchMap)
    if errCode != ecode.OK {
        ctx.Fail(errCode)
api/v1/user.go
@@ -1,381 +1,364 @@
package v1
import (
    "aps_crm/conf"
    "aps_crm/constvar"
    "aps_crm/model"
    "aps_crm/model/request"
    "aps_crm/model/response"
    "aps_crm/pkg/contextx"
    "aps_crm/pkg/ecode"
    "aps_crm/pkg/encrypt"
    "aps_crm/pkg/logx"
    "aps_crm/pkg/snowflake"
    "aps_crm/utils"
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/go-redis/redis/v8"
    "github.com/mojocn/base64Captcha"
)
// 当开启多服务器部署时,替换下面的配置,使用redis共享存储验证码
// var store = captcha.NewDefaultRedisStore()
var store = base64Captcha.DefaultMemStore
// Login
//
//    @Tags        Base
//    @Summary    用户登录
//    @Produce    application/json
//    @Param        object    body        request.Login                                    true    "查询参数"
//    @Success    200        {object}    contextx.Response{data=response.LoginResponse}    "成功"
//    @Router        /api/base/login [post]
func (slf *BaseApi) Login(c *gin.Context) {
    var params request.Login
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    // 判断验证码是否开启
    key := c.ClientIP()
    //openCaptcha := conf.Conf.Captcha.OpenCaptcha               // 是否开启防暴次数
    //openCaptchaTimeOut := conf.Conf.Captcha.OpenCaptchaTimeOut // 缓存超时时间
    //v, ok := constvar.BlackCache.Get(key)
    //if !ok {
    //    constvar.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
    //}
    //var oc = openCaptcha == 0 || convertx.InterfaceToInt(v) > openCaptcha // 0 表示每次登录都需要验证码 或者当前次数已超过防暴次数
    //if !oc || store.Verify(params.CaptchaId, params.Captcha, true) {
    u := &model.User{Username: params.Username, Password: params.Password}
    user, errCode := userService.Login(u)
    if errCode != ecode.OK {
        logx.Errorf("登陆失败! 用户名不存在或者密码错误! errCode:%v", errCode)
        // 验证码次数+1
        _ = constvar.BlackCache.Increment(key, 1)
        ctx.Fail(errCode)
        return
    }
    // 赋值菜单ID列表
    //user.MenuIds, _ = menuService.GetUserMenuIds(user.UUID, user.UserType)
    slf.TokenNext(ctx, *user)
    return
    //}
    // 验证码次数+1
    //_ = constvar.BlackCache.Increment(key, 1)
    //ctx.Fail(ecode.CaptchaErr)
}
// TokenNext 登录以后签发jwt
func (slf *BaseApi) TokenNext(ctx *contextx.Context, user model.User) {
    logx.Infof("TokenNext user:%+v", user)
    j := &utils.JWT{SigningKey: []byte(conf.Conf.JWT.SigningKey)} // 唯一签名
    claims := j.CreateClaims(request.BaseClaims{
        UserId:      user.UUID,
        Username:    user.Username,
        UserType:    user.UserType,
        AuthorityId: user.AuthorityId,
    })
    token, err := j.CreateToken(claims)
    if err != nil {
        logx.Errorf("创建token失败! err:%v", err)
        ctx.Fail(ecode.CreateTokenErr)
        return
    }
    if !conf.Conf.System.UseMultipoint { // 不允许多点登录
        ctx.OkWithDetailed(response.LoginResponse{
            User:  user,
            Token: token,
            //ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
        })
        return
    }
    if jwtStr, err := jwtService.GetRedisJWT(user.Username); err == redis.Nil { // redis无JWT数据
        if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
            logx.Errorf("设置登录状态失败! err:%v", err)
            ctx.Fail(ecode.RedisErr)
            return
        }
        ctx.OkWithDetailed(response.LoginResponse{
            User:  user,
            Token: token,
            //ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
        })
    } else if err != nil { // redis获取JWT报错
        logx.Errorf("设置登录状态失败! err:%v", err)
        ctx.Fail(ecode.RedisErr)
    } else { // 成功获取redis的JWT,旧的作废
        var blackJWT model.JwtBlacklist
        blackJWT.Jwt = jwtStr
        if err := jwtService.JsonInBlacklist(blackJWT); err != nil {
            ctx.Fail(ecode.DBErr)
            return
        }
        if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
            ctx.Fail(ecode.RedisErr)
            return
        }
        ctx.OkWithDetailed(response.LoginResponse{
            User:  user,
            Token: token,
            //ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
        })
    }
}
// Register
//// 当开启多服务器部署时,替换下面的配置,使用redis共享存储验证码
//// var store = captcha.NewDefaultRedisStore()
//var store = base64Captcha.DefaultMemStore
//
//    @Tags        User
//    @Summary    注册账号
//    @Produce    application/json
//    @Param        object    body        request.Register                                true    "查询参数"
//    @Success    200        {object}    contextx.Response{data=response.UserResponse}    "成功"
//    @Router        /api/user/register [post]
func (slf *BaseApi) Register(c *gin.Context) {
    var params request.Register
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    userInfo := utils.GetUserInfo(c)
    if len(userInfo.UserId) <= 0 {
        ctx.Fail(ecode.UnknownErr)
        return
    }
    if len(params.Username) == 0 || len(params.Password) == 0 || len(params.NickName) == 0 || params.AuthorityId == 0 || len(params.RePassword) == 0 || params.DepartmentId == 0 {
        ctx.Fail(ecode.ParamsErr)
        return
    }
    var userId = fmt.Sprintf("u%v", snowflake.GenerateId())
    var passWord = encrypt.BcryptHash(params.Password)
    var userType constvar.UserType
    user := &model.User{UUID: userId, Username: params.Username, UserType: userType, NickName: params.NickName, Password: passWord, HeaderImg: params.HeaderImg, Phone: params.Phone, Email: params.Email, DepartmentId: params.DepartmentId, AuthorityId: params.AuthorityId}
    userReturn, errCode := userService.Register(user)
    if errCode != ecode.OK {
        ctx.Fail(errCode)
        return
    }
    //if user.UserType == constvar.UserTypePrimary { // 主账户创建对应的数据库用户和排程数据库
    //    err := model.NewMysql().CreateDatabase(user.Username)
    //    if err != nil {
    //        ctx.Fail(ecode.CreateDatabaseErr)
    //        return
    //    }
    //
    //    defaultPwd := fmt.Sprintf("%v@Basic2023", user.Username)
    //    err = model.NewMysql().CreateUser(user.Username, defaultPwd, user.Username)
    //    if err != nil {
    //        ctx.Fail(ecode.CreateDatabaseUserErr)
    //        return
    //    }
    //}
    ctx.OkWithDetailed(response.UserResponse{User: *userReturn})
}
// ChangePassword
//// Login
////
////    @Tags        Base
////    @Summary    用户登录
////    @Produce    application/json
////    @Param        object    body        request.Login                                    true    "查询参数"
////    @Success    200        {object}    contextx.Response{data=response.LoginResponse}    "成功"
////    @Router        /api/base/login [post]
//func (slf *BaseApi) Login(c *gin.Context) {
//    var params request.Login
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    @Tags        User
//    @Summary    用户修改密码
//    @Produce    application/json
//    @Param        object    body        request.ChangePasswordReq    true    "查询参数"
//    @Success    200        {object}    contextx.Response{}            "成功"
//    @Router        /api/user/changePassword [post]
func (slf *BaseApi) ChangePassword(c *gin.Context) {
    var params request.ChangePasswordReq
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    u := &model.User{UUID: utils.GetUserID(c), Password: params.Password}
    _, errCode := userService.ChangePassword(u, params.NewPassword)
    if errCode != ecode.OK {
        ctx.Fail(errCode)
        return
    }
    ctx.Ok()
}
// GetUserList
//    // 判断验证码是否开启
//    key := c.ClientIP()
//    //openCaptcha := conf.Conf.Captcha.OpenCaptcha               // 是否开启防暴次数
//    //openCaptchaTimeOut := conf.Conf.Captcha.OpenCaptchaTimeOut // 缓存超时时间
//    //v, ok := constvar.BlackCache.Get(key)
//    //if !ok {
//    //    constvar.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
//    //}
//
//    @Tags        User
//    @Summary    分页获取用户列表(不传分页参数,获取全部)
//    @Produce    application/json
//    @Param        object    body        request.GetUserList                            true    "查询参数"
//    @Success    200        {object}    contextx.Response{data=response.PageResult}    "成功"
//    @Router        /api/user/getUserList [post]
func (slf *BaseApi) GetUserList(c *gin.Context) {
    var params request.GetUserList
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    userInfo := utils.GetUserInfo(c)
    if len(userInfo.UserId) <= 0 || len(userInfo.ParentId) == 0 {
        ctx.Fail(ecode.UnknownErr)
        return
    }
    ctx.OkWithDetailed(response.PageResult{
        Page:     params.Page,
        PageSize: params.PageSize,
    })
}
// DeleteUser
//    //var oc = openCaptcha == 0 || convertx.InterfaceToInt(v) > openCaptcha // 0 表示每次登录都需要验证码 或者当前次数已超过防暴次数
//
//    @Tags        User
//    @Summary    删除用户
//    @Produce    application/json
//    @Param        object    body        request.DeleteUserReq    true    "查询参数"
//    @Success    200        {object}    contextx.Response{}        "成功"
//    @Router        /api/user/deleteUser [delete]
func (slf *BaseApi) DeleteUser(c *gin.Context) {
    var params request.DeleteUserReq
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    if len(params.UserId) <= 0 {
        ctx.Fail(ecode.ParamsErr)
        return
    }
    userInfo := utils.GetUserInfo(c)
    if userInfo.UserType != constvar.UserTypePrimary || userInfo.UserId == params.UserId {
        ctx.Fail(ecode.NoPowerErr)
        return
    }
    err := userService.DeleteUser(params.UserId)
    if err != nil {
        logx.Errorf("删除失败! err:%v", err)
        ctx.Fail(ecode.DBErr)
        return
    }
    ctx.Ok()
}
// SetUserInfo
//    //if !oc || store.Verify(params.CaptchaId, params.Captcha, true) {
//    u := &model.User{Username: params.Username, Password: params.Password}
//    user, errCode := userService.Login(u)
//    if errCode != ecode.OK {
//        logx.Errorf("登陆失败! 用户名不存在或者密码错误! errCode:%v", errCode)
//        // 验证码次数+1
//        _ = constvar.BlackCache.Increment(key, 1)
//        ctx.Fail(errCode)
//        return
//    }
//    // 赋值菜单ID列表
//    //user.MenuIds, _ = menuService.GetUserMenuIds(user.UUID, user.UserType)
//    slf.TokenNext(ctx, *user)
//    return
//    //}
//
//    @Tags        User
//    @Summary    设置用户信息
//    @Produce    application/json
//    @Param        object    body        request.ChangeUserInfo    true    "查询参数"
//    @Success    200        {object}    contextx.Response{}        "成功"
//    @Router        /api/user/setUserInfo [post]
func (slf *BaseApi) SetUserInfo(c *gin.Context) {
    var params request.ChangeUserInfo
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    err := userService.SetUserInfo(model.User{
        UUID:      params.ID,
        NickName:  params.NickName,
        HeaderImg: params.HeaderImg,
        Phone:     params.Phone,
        Email:     params.Email,
        Pos:       params.Pos,
    })
    if err != nil {
        logx.Errorf("设置失败! err:%v", err)
        ctx.Fail(ecode.DBErr)
        return
    }
    ctx.Ok()
}
// SetSelfInfo
//    // 验证码次数+1
//    //_ = constvar.BlackCache.Increment(key, 1)
//    //ctx.Fail(ecode.CaptchaErr)
//}
//
//    @Tags        User
//    @Summary    设置用户信息
//    @Produce    application/json
//    @Param        object    body        request.ChangeUserInfo    true    "查询参数"
//    @Success    200        {object}    contextx.Response{}        "成功"
//    @Router        /api/user/setSelfInfo [post]
func (slf *BaseApi) SetSelfInfo(c *gin.Context) {
    var params request.ChangeUserInfo
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    params.ID = utils.GetUserID(c)
    err := userService.SetUserInfo(model.User{
        UUID:      params.ID,
        NickName:  params.NickName,
        HeaderImg: params.HeaderImg,
        Phone:     params.Phone,
        Email:     params.Email,
        Pos:       params.Pos,
    })
    if err != nil {
        logx.Errorf("设置失败! err:%v", err)
        ctx.Fail(ecode.DBErr)
        return
    }
    ctx.Ok()
}
// GetUserInfo
//// TokenNext 登录以后签发jwt
//func (slf *BaseApi) TokenNext(ctx *contextx.Context, user model.User) {
//    logx.Infof("TokenNext user:%+v", user)
//    j := &utils.JWT{SigningKey: []byte(conf.Conf.JWT.SigningKey)} // 唯一签名
//    claims := j.CreateClaims(request.BaseClaims{
//        UserId:      user.UUID,
//        Username:    user.Username,
//        UserType:    user.UserType,
//        AuthorityId: user.AuthorityId,
//    })
//    token, err := j.CreateToken(claims)
//    if err != nil {
//        logx.Errorf("创建token失败! err:%v", err)
//        ctx.Fail(ecode.CreateTokenErr)
//        return
//    }
//    if !conf.Conf.System.UseMultipoint { // 不允许多点登录
//        ctx.OkWithDetailed(response.LoginResponse{
//            User:  user,
//            Token: token,
//            //ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
//        })
//        return
//    }
//
//    @Tags        User
//    @Summary    获取自身信息
//    @Produce    application/json
//    @Success    200    {object}    contextx.Response{}    "成功"
//    @Router        /api/user/getUserInfo [post]
func (slf *BaseApi) GetUserInfo(c *gin.Context) {
    ctx, ok := contextx.NewContext(c, nil)
    if !ok {
        return
    }
    id := utils.GetUserID(c)
    ReqUser, err := userService.GetUserInfo(id)
    if err != nil {
        logx.Errorf("获取失败! err:%v", err)
        ctx.Fail(ecode.DBErr)
        return
    }
    ctx.OkWithDetailed(response.UserResponse{
        User: *ReqUser,
    })
}
// ResetPassword
//    if jwtStr, err := jwtService.GetRedisJWT(user.Username); err == redis.Nil { // redis无JWT数据
//        if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
//            logx.Errorf("设置登录状态失败! err:%v", err)
//            ctx.Fail(ecode.RedisErr)
//            return
//        }
//        ctx.OkWithDetailed(response.LoginResponse{
//            User:  user,
//            Token: token,
//            //ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
//        })
//    } else if err != nil { // redis获取JWT报错
//        logx.Errorf("设置登录状态失败! err:%v", err)
//        ctx.Fail(ecode.RedisErr)
//    } else { // 成功获取redis的JWT,旧的作废
//        var blackJWT model.JwtBlacklist
//        blackJWT.Jwt = jwtStr
//        if err := jwtService.JsonInBlacklist(blackJWT); err != nil {
//            ctx.Fail(ecode.DBErr)
//            return
//        }
//        if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
//            ctx.Fail(ecode.RedisErr)
//            return
//        }
//        ctx.OkWithDetailed(response.LoginResponse{
//            User:  user,
//            Token: token,
//            //ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
//        })
//    }
//}
//
//    @Tags        User
//    @Summary    重置用户密码
//    @Produce    application/json
//    @Param        object    body        model.User            true    "查询参数"
//    @Success    200        {object}    contextx.Response{}    "成功"
//    @Router        /api/user/resetPassword [post]
func (slf *BaseApi) ResetPassword(c *gin.Context) {
    var params model.User
    ctx, ok := contextx.NewContext(c, &params)
    if !ok {
        return
    }
    err := userService.ResetPassword(params.UUID)
    if err != nil {
        logx.Errorf("重置失败! err:%v", err)
        ctx.Fail(ecode.DBErr)
        return
    }
    ctx.Ok()
}
//// Register
////
////    @Tags        User
////    @Summary    注册账号
////    @Produce    application/json
////    @Param        object    body        request.Register                                true    "查询参数"
////    @Success    200        {object}    contextx.Response{data=response.UserResponse}    "成功"
////    @Router        /api/user/register [post]
//func (slf *BaseApi) Register(c *gin.Context) {
//    var params request.Register
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    userInfo := utils.GetUserInfo(c)
//    if len(userInfo.UserId) <= 0 {
//        ctx.Fail(ecode.UnknownErr)
//        return
//    }
//
//    if len(params.Username) == 0 || len(params.Password) == 0 || len(params.NickName) == 0 || params.AuthorityId == 0 || len(params.RePassword) == 0 || params.DepartmentId == 0 {
//        ctx.Fail(ecode.ParamsErr)
//        return
//    }
//
//    var userId = fmt.Sprintf("u%v", snowflake.GenerateId())
//    var passWord = encrypt.BcryptHash(params.Password)
//    var userType constvar.UserType
//
//    user := &model.User{UUID: userId, Username: params.Username, UserType: userType, NickName: params.NickName, Password: passWord, HeaderImg: params.HeaderImg, Phone: params.Phone, Email: params.Email, DepartmentId: params.DepartmentId, AuthorityId: params.AuthorityId}
//    userReturn, errCode := userService.Register(user)
//    if errCode != ecode.OK {
//        ctx.Fail(errCode)
//        return
//    }
//
//    //if user.UserType == constvar.UserTypePrimary { // 主账户创建对应的数据库用户和排程数据库
//    //    err := model.NewMysql().CreateDatabase(user.Username)
//    //    if err != nil {
//    //        ctx.Fail(ecode.CreateDatabaseErr)
//    //        return
//    //    }
//    //
//    //    defaultPwd := fmt.Sprintf("%v@Basic2023", user.Username)
//    //    err = model.NewMysql().CreateUser(user.Username, defaultPwd, user.Username)
//    //    if err != nil {
//    //        ctx.Fail(ecode.CreateDatabaseUserErr)
//    //        return
//    //    }
//    //}
//
//    ctx.OkWithDetailed(response.UserResponse{User: *userReturn})
//}
//
//// ChangePassword
////
////    @Tags        User
////    @Summary    用户修改密码
////    @Produce    application/json
////    @Param        object    body        request.ChangePasswordReq    true    "查询参数"
////    @Success    200        {object}    contextx.Response{}            "成功"
////    @Router        /api/user/changePassword [post]
//func (slf *BaseApi) ChangePassword(c *gin.Context) {
//    var params request.ChangePasswordReq
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    u := &model.User{UUID: utils.GetUserID(c), Password: params.Password}
//    _, errCode := userService.ChangePassword(u, params.NewPassword)
//    if errCode != ecode.OK {
//        ctx.Fail(errCode)
//        return
//    }
//    ctx.Ok()
//}
//
//// GetUserList
////
////    @Tags        User
////    @Summary    分页获取用户列表(不传分页参数,获取全部)
////    @Produce    application/json
////    @Param        object    body        request.GetUserList                            true    "查询参数"
////    @Success    200        {object}    contextx.Response{data=response.PageResult}    "成功"
////    @Router        /api/user/getUserList [post]
//func (slf *BaseApi) GetUserList(c *gin.Context) {
//    var params request.GetUserList
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    userInfo := utils.GetUserInfo(c)
//    if len(userInfo.UserId) <= 0 || len(userInfo.ParentId) == 0 {
//        ctx.Fail(ecode.UnknownErr)
//        return
//    }
//
//    ctx.OkWithDetailed(response.PageResult{
//        Page:     params.Page,
//        PageSize: params.PageSize,
//    })
//}
//
//// DeleteUser
////
////    @Tags        User
////    @Summary    删除用户
////    @Produce    application/json
////    @Param        object    body        request.DeleteUserReq    true    "查询参数"
////    @Success    200        {object}    contextx.Response{}        "成功"
////    @Router        /api/user/deleteUser [delete]
//func (slf *BaseApi) DeleteUser(c *gin.Context) {
//    var params request.DeleteUserReq
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    if len(params.UserId) <= 0 {
//        ctx.Fail(ecode.ParamsErr)
//        return
//    }
//
//    userInfo := utils.GetUserInfo(c)
//    if userInfo.UserType != constvar.UserTypePrimary || userInfo.UserId == params.UserId {
//        ctx.Fail(ecode.NoPowerErr)
//        return
//    }
//
//    err := userService.DeleteUser(params.UserId)
//    if err != nil {
//        logx.Errorf("删除失败! err:%v", err)
//        ctx.Fail(ecode.DBErr)
//        return
//    }
//    ctx.Ok()
//}
//
//// SetUserInfo
////
////    @Tags        User
////    @Summary    设置用户信息
////    @Produce    application/json
////    @Param        object    body        request.ChangeUserInfo    true    "查询参数"
////    @Success    200        {object}    contextx.Response{}        "成功"
////    @Router        /api/user/setUserInfo [post]
//func (slf *BaseApi) SetUserInfo(c *gin.Context) {
//    var params request.ChangeUserInfo
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    err := userService.SetUserInfo(model.User{
//        UUID:      params.ID,
//        NickName:  params.NickName,
//        HeaderImg: params.HeaderImg,
//        Phone:     params.Phone,
//        Email:     params.Email,
//        Pos:       params.Pos,
//    })
//    if err != nil {
//        logx.Errorf("设置失败! err:%v", err)
//        ctx.Fail(ecode.DBErr)
//        return
//    }
//    ctx.Ok()
//}
//
//// SetSelfInfo
////
////    @Tags        User
////    @Summary    设置用户信息
////    @Produce    application/json
////    @Param        object    body        request.ChangeUserInfo    true    "查询参数"
////    @Success    200        {object}    contextx.Response{}        "成功"
////    @Router        /api/user/setSelfInfo [post]
//func (slf *BaseApi) SetSelfInfo(c *gin.Context) {
//    var params request.ChangeUserInfo
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    params.ID = utils.GetUserID(c)
//    err := userService.SetUserInfo(model.User{
//        UUID:      params.ID,
//        NickName:  params.NickName,
//        HeaderImg: params.HeaderImg,
//        Phone:     params.Phone,
//        Email:     params.Email,
//        Pos:       params.Pos,
//    })
//    if err != nil {
//        logx.Errorf("设置失败! err:%v", err)
//        ctx.Fail(ecode.DBErr)
//        return
//    }
//    ctx.Ok()
//}
//
//// GetUserInfo
////
////    @Tags        User
////    @Summary    获取自身信息
////    @Produce    application/json
////    @Success    200    {object}    contextx.Response{}    "成功"
////    @Router        /api/user/getUserInfo [post]
//func (slf *BaseApi) GetUserInfo(c *gin.Context) {
//    ctx, ok := contextx.NewContext(c, nil)
//    if !ok {
//        return
//    }
//
//    id := utils.GetUserID(c)
//    ReqUser, err := userService.GetUserInfo(id)
//    if err != nil {
//        logx.Errorf("获取失败! err:%v", err)
//        ctx.Fail(ecode.DBErr)
//        return
//    }
//    ctx.OkWithDetailed(response.UserResponse{
//        User: *ReqUser,
//    })
//}
//
//// ResetPassword
////
////    @Tags        User
////    @Summary    重置用户密码
////    @Produce    application/json
////    @Param        object    body        model.User            true    "查询参数"
////    @Success    200        {object}    contextx.Response{}    "成功"
////    @Router        /api/user/resetPassword [post]
//func (slf *BaseApi) ResetPassword(c *gin.Context) {
//    var params model.User
//    ctx, ok := contextx.NewContext(c, &params)
//    if !ok {
//        return
//    }
//
//    err := userService.ResetPassword(params.UUID)
//    if err != nil {
//        logx.Errorf("重置失败! err:%v", err)
//        ctx.Fail(ecode.DBErr)
//        return
//    }
//    ctx.Ok()
//}
middleware/jwt.go
@@ -105,11 +105,14 @@
            c.Next()
            return
        }
        c.Set("claims", claims)
        userInfo := service.GetUserBaseCache(claims.UserId)
        c.Set("user_id", userInfo.UserId)
        c.Set("user_name", userInfo.NickName)
        if userInfo == nil {
            SyncUserInfo()
            userInfo = service.GetUserBaseCache(claims.UserId)
        }
        claims.CrmUserId = userInfo.UserId
        claims.NickName = userInfo.NickName
        c.Set("claims", claims)
        if CheckAuth(c.Request.RequestURI, token) {
            c.Next()
        } else {
model/request/jwt.go
@@ -10,6 +10,8 @@
    BaseClaims
    BufferTime int64
    jwt.StandardClaims
    CrmUserId int
    NickName  string
}
type BaseClaims struct {
model/user.go
@@ -89,7 +89,7 @@
    var db = slf.Orm.Model(&User{}).Preload("Menus")
    if slf.UUID != "" {
        db = db.Where("id = ?", slf.UUID)
        db = db.Where("uuid = ?", slf.UUID)
    }
    if slf.Username != "" {
router/base.go
@@ -1,18 +1,18 @@
package router
import (
    "aps_crm/api/v1"
    "github.com/gin-gonic/gin"
)
type BaseRouter struct{}
func (s *BaseRouter) InitBaseRouter(Router *gin.RouterGroup) (R gin.IRoutes) {
    baseRouter := Router.Group("base")
    baseApi := v1.ApiGroup.BaseApi
    {
        baseRouter.POST("login", baseApi.Login)     // 用户登录
        baseRouter.POST("captcha", baseApi.Captcha) // 获取验证码
    }
    return baseRouter
}
//import (
//    "aps_crm/api/v1"
//    "github.com/gin-gonic/gin"
//)
//
//type BaseRouter struct{}
//
//func (s *BaseRouter) InitBaseRouter(Router *gin.RouterGroup) (R gin.IRoutes) {
//    baseRouter := Router.Group("base")
//    baseApi := v1.ApiGroup.BaseApi
//    {
//        baseRouter.POST("login", baseApi.Login)     // 用户登录
//        baseRouter.POST("captcha", baseApi.Captcha) // 获取验证码
//    }
//    return baseRouter
//}
router/image.go
@@ -1,17 +1,18 @@
package router
import (
    "aps_crm/api/v1"
    "github.com/gin-gonic/gin"
)
type ImageRouter struct{}
func (s *BaseRouter) InitImageRouter(Router *gin.RouterGroup) (R gin.IRoutes) {
    imageRouter := Router.Group("image")
    imageApi := v1.ApiGroup.ImageApi
    {
        imageRouter.POST("upload", imageApi.Upload) // 上传图像
    }
    return imageRouter
}
//
//import (
//    "aps_crm/api/v1"
//    "github.com/gin-gonic/gin"
//)
//
//type ImageRouter struct{}
//
//func (s *BaseRouter) InitImageRouter(Router *gin.RouterGroup) (R gin.IRoutes) {
//    imageRouter := Router.Group("image")
//    imageApi := v1.ApiGroup.ImageApi
//    {
//        imageRouter.POST("upload", imageApi.Upload) // 上传图像
//    }
//    return imageRouter
//}
router/index.go
@@ -27,8 +27,8 @@
    IsVisitRouter
    SolveRateRouter
    TimelyRateRouter
    BaseRouter
    UserRouter
    //BaseRouter
    //UserRouter
    JwtRouter
    CountryRouter
    ProvinceRouter
@@ -104,18 +104,18 @@
            c.JSON(http.StatusOK, "ok")
        })
    }
    {
        routerGroup.InitBaseRouter(PublicGroup)  // 注册基础功能路由 不做鉴权
        routerGroup.InitImageRouter(PublicGroup) // 图像功能路由
    }
    //{
    //    routerGroup.InitBaseRouter(PublicGroup)  // 注册基础功能路由 不做鉴权
    //    routerGroup.InitImageRouter(PublicGroup) // 图像功能路由
    //}
    PrivateGroup := Router.Group("api")
    //PrivateGroup.Use(middleware.JWTAuth()).Use(middleware.CasbinHandler())
    PrivateGroup.Use(middleware.JWTAuth2())
    //PrivateGroup.Use(middleware.CasbinHandler())
    {
        routerGroup.InitJwtRouter(PrivateGroup)                  // jwt相关路由
        routerGroup.InitUserRouter(PrivateGroup)                 // 注册用户路由
        routerGroup.InitJwtRouter(PrivateGroup) // jwt相关路由
        //routerGroup.InitUserRouter(PrivateGroup)                 // 注册用户路由
        routerGroup.InitCountryRouter(PrivateGroup)              // 注册country路由
        routerGroup.InitProvinceRouter(PrivateGroup)             // 注册province路由
        routerGroup.InitCityRouter(PrivateGroup)                 // 注册city路由
router/user.go
@@ -1,26 +1,26 @@
package router
import (
    "aps_crm/api/v1"
    "github.com/gin-gonic/gin"
)
type UserRouter struct{}
func (s *UserRouter) InitUserRouter(Router *gin.RouterGroup) {
    userRouter := Router.Group("user")
    userRouterWithoutRecord := Router.Group("user")
    baseApi := v1.ApiGroup.BaseApi
    {
        userRouter.POST("register", baseApi.Register) // 注册账号
        //userRouter.POST("changePassword", baseApi.ChangePassword) // 用户修改密码
        //userRouter.POST("resetPassword", baseApi.ResetPassword) // 重置用户密码
        userRouter.DELETE("deleteUser", baseApi.DeleteUser) // 删除用户
        userRouter.PUT("setUserInfo", baseApi.SetUserInfo)  // 设置用户信息
        //userRouter.PUT("setSelfInfo", baseApi.SetSelfInfo)  // 设置自身信息
    }
    {
        userRouterWithoutRecord.POST("getUserList", baseApi.GetUserList) // 分页获取用户列表(不传分页参数,获取全部)
        userRouterWithoutRecord.GET("getUserInfo", baseApi.GetUserInfo)  // 获取自身信息
    }
}
//import (
//    "aps_crm/api/v1"
//    "github.com/gin-gonic/gin"
//)
//
//type UserRouter struct{}
//
//func (s *UserRouter) InitUserRouter(Router *gin.RouterGroup) {
//    userRouter := Router.Group("user")
//    userRouterWithoutRecord := Router.Group("user")
//    baseApi := v1.ApiGroup.BaseApi
//    {
//        userRouter.POST("register", baseApi.Register) // 注册账号
//        //userRouter.POST("changePassword", baseApi.ChangePassword) // 用户修改密码
//        //userRouter.POST("resetPassword", baseApi.ResetPassword) // 重置用户密码
//        userRouter.DELETE("deleteUser", baseApi.DeleteUser) // 删除用户
//        userRouter.PUT("setUserInfo", baseApi.SetUserInfo)  // 设置用户信息
//        //userRouter.PUT("setSelfInfo", baseApi.SetSelfInfo)  // 设置自身信息
//    }
//    {
//        userRouterWithoutRecord.POST("getUserList", baseApi.GetUserList) // 分页获取用户列表(不传分页参数,获取全部)
//        userRouterWithoutRecord.GET("getUserInfo", baseApi.GetUserInfo)  // 获取自身信息
//    }
//}
utils/clamis.go
@@ -22,30 +22,18 @@
    return claims, err
}
// GetUserID 从Gin的Context中获取从jwt解析出来的用户ID
func GetUserID(c *gin.Context) string {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return ""
        } else {
            return cl.UserId
        }
    } else {
func GetUserID(c *gin.Context) int {
    if claims, exists := c.Get("claims"); exists {
        waitUse := claims.(*request.CustomClaims)
        return waitUse.UserId
        return waitUse.CrmUserId
    }
    return 0
}
// GetUserInfo 从Gin的Context中获取从jwt解析出来的用户信息
func GetUserInfo(c *gin.Context) *request.CustomClaims {
    if claims, exists := c.Get("claims"); !exists {
        if cl, err := GetClaims(c); err != nil {
            return nil
        } else {
            return cl
        }
    } else {
    if claims, exists := c.Get("claims"); exists {
        waitUse := claims.(*request.CustomClaims)
        return waitUse
    }
    return nil
}