sys_user.go 15 KB

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