sys_user.go 14 KB

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