sys_user.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. package system
  2. import (
  3. "context"
  4. weapp "github.com/medivhzhan/weapp/v2"
  5. "strconv"
  6. "time"
  7. "github.com/flipped-aurora/gin-vue-admin/server/global"
  8. "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
  9. "github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
  10. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  11. systemReq "github.com/flipped-aurora/gin-vue-admin/server/model/system/request"
  12. systemRes "github.com/flipped-aurora/gin-vue-admin/server/model/system/response"
  13. "github.com/flipped-aurora/gin-vue-admin/server/utils"
  14. "github.com/dgrijalva/jwt-go"
  15. "github.com/gin-gonic/gin"
  16. "github.com/go-redis/redis/v8"
  17. "go.uber.org/zap"
  18. )
  19. // @Tags Base
  20. // @Summary 用户登录
  21. // @Produce application/json
  22. // @Param data body systemReq.Login true "用户名, 密码, 验证码"
  23. // @Success 200 {string} string "{"success":true,"data":{},"msg":"登陆成功"}"
  24. // @Router /base/login [post]
  25. func (b *BaseApi) Login(c *gin.Context) {
  26. var l systemReq.Login
  27. _ = c.ShouldBindJSON(&l)
  28. if err := utils.Verify(l, utils.LoginVerify); err != nil {
  29. response.FailWithMessage(err.Error(), c)
  30. return
  31. }
  32. if store.Verify(l.CaptchaId, l.Captcha, true) {
  33. u := &system.SysUser{Username: l.Username, Password: l.Password}
  34. if err, user := userService.Login(u); err != nil {
  35. global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Any("err", err))
  36. response.FailWithMessage("用户名不存在或者密码错误", c)
  37. } else {
  38. b.tokenNext(c, *user)
  39. }
  40. } else {
  41. response.FailWithMessage("验证码错误", c)
  42. }
  43. }
  44. func (b *BaseApi) LoginWx(c *gin.Context) {
  45. var l systemReq.LoginWx
  46. _ = c.ShouldBindJSON(&l)
  47. res, err := weapp.Login(global.GVA_CONFIG.Wxxcx.Appid, global.GVA_CONFIG.Wxxcx.Secret, l.Code)
  48. if err != nil {
  49. global.GVA_LOG.Error("登陆小程序失败!", zap.Any("err", err))
  50. response.FailWithMessage("小程序信息获取异常", c)
  51. return
  52. }
  53. global.GVA_LOG.Info("小程序登录", zap.Any("res", res))
  54. global.GVA_REDIS.Set(context.Background(), "wxssk:"+res.OpenID, res.SessionKey, 0)
  55. if err, user := userService.FindUserByOpenId(res.OpenID); err != nil {
  56. response.CodeWithDetailed(1, res, "未注册", c)
  57. return
  58. } else {
  59. if user.AuthorityId == "100" {
  60. response.CodeMessage(2, "请等待审核", c)
  61. return
  62. }
  63. if user.UnionId == "" {
  64. user.UnionId = res.UnionID
  65. userService.SetUserInfo(*user)
  66. }
  67. b.tokenNext(c, *user)
  68. }
  69. }
  70. func (b *BaseApi) RegisterWx(c *gin.Context) {
  71. var r systemReq.RegisterWx
  72. _ = c.ShouldBindJSON(&r)
  73. if err := utils.Verify(r, utils.RegisterWxVerify); err != nil {
  74. response.FailWithMessage(err.Error(), c)
  75. return
  76. }
  77. if err, sysUser := userService.GetUserInfoByUnionId(r.UnionId); err != nil {
  78. authorityId := "100"
  79. user := &system.SysUser{Username: r.Username, OpenId: r.OpenId, UnionId: r.UnionId, NickName: r.NickName, Password: utils.RandomString(10), HeaderImg: r.HeaderImg, AuthorityId: authorityId, Authorities: nil}
  80. regErr, userReturn := userService.Register(*user)
  81. if regErr != nil {
  82. global.GVA_LOG.Error("注册失败!", zap.Any("err", err))
  83. response.CodeMessage(2, "您已经申请过了,请耐心等待审核!", c)
  84. } else {
  85. response.CodeWithDetailed(2, systemRes.SysUserResponse{User: userReturn}, "申请登陆成功,请等待审核", c)
  86. }
  87. } else {
  88. sysUser.OpenId = r.OpenId
  89. sysUser.NickName = r.NickName
  90. sysUser.Username = r.Username
  91. sysUser.HeaderImg = r.HeaderImg
  92. userService.SetUserInfo(sysUser)
  93. response.CodeMessage(2, "资料已提交,请耐心等待审核!", c)
  94. }
  95. }
  96. // 登录以后签发jwt
  97. func (b *BaseApi) tokenNext(c *gin.Context, user system.SysUser) {
  98. j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
  99. claims := systemReq.CustomClaims{
  100. UUID: user.UUID,
  101. ID: user.ID,
  102. NickName: user.NickName,
  103. Username: user.Username,
  104. AuthorityId: user.AuthorityId,
  105. BufferTime: global.GVA_CONFIG.JWT.BufferTime, // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
  106. StandardClaims: jwt.StandardClaims{
  107. NotBefore: time.Now().Unix() - 1000, // 签名生效时间
  108. ExpiresAt: time.Now().Unix() + global.GVA_CONFIG.JWT.ExpiresTime, // 过期时间 7天 配置文件
  109. Issuer: "qmPlus", // 签名的发行者
  110. },
  111. }
  112. token, err := j.CreateToken(claims)
  113. if err != nil {
  114. global.GVA_LOG.Error("获取token失败!", zap.Any("err", err))
  115. response.FailWithMessage("获取token失败", c)
  116. return
  117. }
  118. if !global.GVA_CONFIG.System.UseMultipoint {
  119. response.OkWithDetailed(systemRes.LoginResponse{
  120. User: user,
  121. Token: token,
  122. ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
  123. }, "登录成功", c)
  124. return
  125. }
  126. if err, jwtStr := jwtService.GetRedisJWT(user.Username); err == redis.Nil {
  127. if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
  128. global.GVA_LOG.Error("设置登录状态失败!", zap.Any("err", err))
  129. response.FailWithMessage("设置登录状态失败", c)
  130. return
  131. }
  132. response.OkWithDetailed(systemRes.LoginResponse{
  133. User: user,
  134. Token: token,
  135. ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
  136. }, "登录成功", c)
  137. } else if err != nil {
  138. global.GVA_LOG.Error("设置登录状态失败!", zap.Any("err", err))
  139. response.FailWithMessage("设置登录状态失败", c)
  140. } else {
  141. var blackJWT system.JwtBlacklist
  142. blackJWT.Jwt = jwtStr
  143. if err := jwtService.JsonInBlacklist(blackJWT); err != nil {
  144. response.FailWithMessage("jwt作废失败", c)
  145. return
  146. }
  147. if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
  148. response.FailWithMessage("设置登录状态失败", c)
  149. return
  150. }
  151. response.OkWithDetailed(systemRes.LoginResponse{
  152. User: user,
  153. Token: token,
  154. ExpiresAt: claims.StandardClaims.ExpiresAt * 1000,
  155. }, "登录成功", c)
  156. }
  157. }
  158. // @Tags SysUser
  159. // @Summary 用户注册账号
  160. // @Produce application/json
  161. // @Param data body systemReq.Register true "用户名, 昵称, 密码, 角色ID"
  162. // @Success 200 {string} string "{"success":true,"data":{},"msg":"注册成功"}"
  163. // @Router /user/register [post]
  164. func (b *BaseApi) Register(c *gin.Context) {
  165. var r systemReq.Register
  166. _ = c.ShouldBindJSON(&r)
  167. if err := utils.Verify(r, utils.RegisterVerify); err != nil {
  168. response.FailWithMessage(err.Error(), c)
  169. return
  170. }
  171. var authorities []system.SysAuthority
  172. for _, v := range r.AuthorityIds {
  173. authorities = append(authorities, system.SysAuthority{
  174. AuthorityId: v,
  175. })
  176. }
  177. user := &system.SysUser{Username: r.Username, NickName: r.NickName, Password: r.Password, HeaderImg: r.HeaderImg, AuthorityId: r.AuthorityId, Authorities: authorities}
  178. err, userReturn := userService.Register(*user)
  179. if err != nil {
  180. global.GVA_LOG.Error("注册失败!", zap.Any("err", err))
  181. response.FailWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册失败", c)
  182. } else {
  183. response.OkWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册成功", c)
  184. }
  185. }
  186. // @Tags SysUser
  187. // @Summary 用户修改密码
  188. // @Security ApiKeyAuth
  189. // @Produce application/json
  190. // @Param data body systemReq.ChangePasswordStruct true "用户名, 原密码, 新密码"
  191. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  192. // @Router /user/changePassword [post]
  193. func (b *BaseApi) ChangePassword(c *gin.Context) {
  194. var user systemReq.ChangePasswordStruct
  195. _ = c.ShouldBindJSON(&user)
  196. if err := utils.Verify(user, utils.ChangePasswordVerify); err != nil {
  197. response.FailWithMessage(err.Error(), c)
  198. return
  199. }
  200. u := &system.SysUser{Username: user.Username, Password: user.Password}
  201. if err, _ := userService.ChangePassword(u, user.NewPassword); err != nil {
  202. global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
  203. response.FailWithMessage("修改失败,原密码与当前账户不符", c)
  204. } else {
  205. response.OkWithMessage("修改成功", c)
  206. }
  207. }
  208. // @Tags SysUser
  209. // @Summary 分页获取用户列表
  210. // @Security ApiKeyAuth
  211. // @accept application/json
  212. // @Produce application/json
  213. // @Param data body request.PageInfo true "页码, 每页大小"
  214. // @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
  215. // @Router /user/getUserList [post]
  216. func (b *BaseApi) GetUserList(c *gin.Context) {
  217. var pageInfo request.PageInfo
  218. _ = c.ShouldBindJSON(&pageInfo)
  219. if err := utils.Verify(pageInfo, utils.PageInfoVerify); err != nil {
  220. response.FailWithMessage(err.Error(), c)
  221. return
  222. }
  223. if err, list, total := userService.GetUserInfoList(pageInfo); err != nil {
  224. global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
  225. response.FailWithMessage("获取失败", c)
  226. } else {
  227. response.OkWithDetailed(response.PageResult{
  228. List: list,
  229. Total: total,
  230. Page: pageInfo.Page,
  231. PageSize: pageInfo.PageSize,
  232. }, "获取成功", c)
  233. }
  234. }
  235. func (b *BaseApi) GetUserPList(c *gin.Context) {
  236. var pageInfo systemReq.UserSearch
  237. _ = c.ShouldBindJSON(&pageInfo)
  238. if err := utils.Verify(pageInfo, utils.PageInfoVerify); err != nil {
  239. response.FailWithMessage(err.Error(), c)
  240. return
  241. }
  242. if err, list, total := userService.GetUserPInfoList(pageInfo); err != nil {
  243. global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
  244. response.FailWithMessage("获取失败", c)
  245. } else {
  246. response.OkWithDetailed(response.PageResult{
  247. List: list,
  248. Total: total,
  249. Page: pageInfo.Page,
  250. PageSize: pageInfo.PageSize,
  251. }, "获取成功", c)
  252. }
  253. }
  254. // @Tags SysUser
  255. // @Summary 更改用户权限
  256. // @Security ApiKeyAuth
  257. // @accept application/json
  258. // @Produce application/json
  259. // @Param data body systemReq.SetUserAuth true "用户UUID, 角色ID"
  260. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  261. // @Router /user/setUserAuthority [post]
  262. func (b *BaseApi) SetUserAuthority(c *gin.Context) {
  263. var sua systemReq.SetUserAuth
  264. _ = c.ShouldBindJSON(&sua)
  265. if UserVerifyErr := utils.Verify(sua, utils.SetUserAuthorityVerify); UserVerifyErr != nil {
  266. response.FailWithMessage(UserVerifyErr.Error(), c)
  267. return
  268. }
  269. userID := utils.GetUserID(c)
  270. uuid := utils.GetUserUuid(c)
  271. if err := userService.SetUserAuthority(userID, uuid, sua.AuthorityId); err != nil {
  272. global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
  273. response.FailWithMessage(err.Error(), c)
  274. } else {
  275. claims := utils.GetUserInfo(c)
  276. j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
  277. claims.AuthorityId = sua.AuthorityId
  278. if token, err := j.CreateToken(*claims); err != nil {
  279. global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
  280. response.FailWithMessage(err.Error(), c)
  281. } else {
  282. c.Header("new-token", token)
  283. c.Header("new-expires-at", strconv.FormatInt(claims.ExpiresAt, 10))
  284. response.OkWithMessage("修改成功", c)
  285. }
  286. }
  287. }
  288. // @Tags SysUser
  289. // @Summary 设置用户权限
  290. // @Security ApiKeyAuth
  291. // @accept application/json
  292. // @Produce application/json
  293. // @Param data body systemReq.SetUserAuthorities true "用户UUID, 角色ID"
  294. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  295. // @Router /user/setUserAuthorities [post]
  296. func (b *BaseApi) SetUserAuthorities(c *gin.Context) {
  297. var sua systemReq.SetUserAuthorities
  298. _ = c.ShouldBindJSON(&sua)
  299. if err := userService.SetUserAuthorities(sua.ID, sua.AuthorityIds); err != nil {
  300. global.GVA_LOG.Error("修改失败!", zap.Any("err", err))
  301. response.FailWithMessage("修改失败", c)
  302. } else {
  303. response.OkWithMessage("修改成功", c)
  304. }
  305. }
  306. // @Tags SysUser
  307. // @Summary 删除用户
  308. // @Security ApiKeyAuth
  309. // @accept application/json
  310. // @Produce application/json
  311. // @Param data body request.GetById true "用户ID"
  312. // @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
  313. // @Router /user/deleteUser [delete]
  314. func (b *BaseApi) DeleteUser(c *gin.Context) {
  315. var reqId request.GetById
  316. _ = c.ShouldBindJSON(&reqId)
  317. if err := utils.Verify(reqId, utils.IdVerify); err != nil {
  318. response.FailWithMessage(err.Error(), c)
  319. return
  320. }
  321. jwtId := utils.GetUserID(c)
  322. if jwtId == uint(reqId.ID) {
  323. response.FailWithMessage("删除失败, 自杀失败", c)
  324. return
  325. }
  326. if err := userService.DeleteUser(reqId.ID); err != nil {
  327. global.GVA_LOG.Error("删除失败!", zap.Any("err", err))
  328. response.FailWithMessage("删除失败", c)
  329. } else {
  330. response.OkWithMessage("删除成功", c)
  331. }
  332. }
  333. // @Tags SysUser
  334. // @Summary 设置用户信息
  335. // @Security ApiKeyAuth
  336. // @accept application/json
  337. // @Produce application/json
  338. // @Param data body system.SysUser true "ID, 用户名, 昵称, 头像链接"
  339. // @Success 200 {string} string "{"success":true,"data":{},"msg":"设置成功"}"
  340. // @Router /user/setUserInfo [put]
  341. func (b *BaseApi) SetUserInfo(c *gin.Context) {
  342. var user system.SysUser
  343. _ = c.ShouldBindJSON(&user)
  344. if err := utils.Verify(user, utils.IdVerify); err != nil {
  345. response.FailWithMessage(err.Error(), c)
  346. return
  347. }
  348. if err, ReqUser := userService.SetUserInfo(user); err != nil {
  349. global.GVA_LOG.Error("设置失败!", zap.Any("err", err))
  350. response.FailWithMessage("设置失败", c)
  351. } else {
  352. response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "设置成功", c)
  353. }
  354. }
  355. func (b *BaseApi) SetUserName(c *gin.Context) {
  356. var user system.SysUser
  357. _ = c.ShouldBindJSON(&user)
  358. if err := utils.Verify(user, utils.IdVerify); err != nil {
  359. response.FailWithMessage(err.Error(), c)
  360. return
  361. }
  362. _, userNow := userService.FindUserById(int(user.ID))
  363. userNow.Username = user.Username
  364. if err, ReqUser := userService.SetUserName(userNow); err != nil {
  365. global.GVA_LOG.Error("设置失败!", zap.Any("err", err))
  366. response.FailWithMessage("设置失败", c)
  367. } else {
  368. response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "设置成功", c)
  369. }
  370. }
  371. // @Tags SysUser
  372. // @Summary 获取用户信息
  373. // @Security ApiKeyAuth
  374. // @accept application/json
  375. // @Produce application/json
  376. // @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
  377. // @Router /user/getUserInfo [get]
  378. func (b *BaseApi) GetUserInfo(c *gin.Context) {
  379. uuid := utils.GetUserUuid(c)
  380. if err, ReqUser := userService.GetUserInfo(uuid); err != nil {
  381. global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
  382. response.FailWithMessage("获取失败", c)
  383. } else {
  384. response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "获取成功", c)
  385. }
  386. }
  387. func (b *BaseApi) GetUserInfoById(c *gin.Context) {
  388. var user system.SysUser
  389. _ = c.ShouldBindQuery(&user)
  390. if err, ReqUser := userService.FindUserById(int(user.ID)); err != nil {
  391. global.GVA_LOG.Error("获取失败!", zap.Any("err", err))
  392. response.FailWithMessage("获取失败", c)
  393. } else {
  394. response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "获取成功", c)
  395. }
  396. }