sys_user.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package system
  2. import (
  3. "server/dao"
  4. "server/utils/logger"
  5. "strconv"
  6. "time"
  7. "server/global"
  8. "server/model/common/request"
  9. "server/model/common/response"
  10. systemReq "server/model/system/request"
  11. systemRes "server/model/system/response"
  12. "server/utils"
  13. "github.com/gin-gonic/gin"
  14. "github.com/redis/go-redis/v9"
  15. "go.uber.org/zap"
  16. )
  17. // 框架自带的登录无加密 返回公钥
  18. func (b *BaseApi) ReturnPublicKey(c *gin.Context) {
  19. rsa := utils.RSA{}
  20. publicKey := rsa.ReturnPublicKey()
  21. response.OkWithData(gin.H{"publicKey": publicKey}, c)
  22. }
  23. // Login
  24. // @Tags Base
  25. // @Summary 用户登录
  26. // @Produce application/json
  27. // @Param data body systemReq.Login true "用户名, 密码, 验证码"
  28. // @Success 200 {object} response.Response{data=systemRes.LoginResponse,msg=string} "返回包括用户信息,token,过期时间"
  29. // @Router /base/login [post]
  30. func (b *BaseApi) Login(c *gin.Context) {
  31. var l systemReq.Login
  32. err := c.ShouldBindJSON(&l)
  33. key := c.ClientIP()
  34. if err != nil {
  35. response.FailWithMessage(err.Error(), c)
  36. return
  37. }
  38. err = utils.Verify(l, utils.LoginVerify)
  39. if err != nil {
  40. response.FailWithMessage(err.Error(), c)
  41. return
  42. }
  43. // 判断验证码是否开启
  44. openCaptcha := global.GVA_CONFIG.Captcha.OpenCaptcha // 是否开启防爆次数
  45. openCaptchaTimeOut := global.GVA_CONFIG.Captcha.OpenCaptchaTimeOut // 缓存超时时间
  46. v, ok := global.BlackCache.Get(key)
  47. if !ok {
  48. global.BlackCache.Set(key, 1, time.Second*time.Duration(openCaptchaTimeOut))
  49. }
  50. var oc bool = openCaptcha == 0 || openCaptcha < interfaceToInt(v)
  51. //解密
  52. rsa := utils.RSA{}
  53. l.Password = rsa.Encryption(l.Password)
  54. if !oc || (l.CaptchaId != "" && l.Captcha != "" && store.Verify(l.CaptchaId, l.Captcha, true)) {
  55. u := &dao.SysUser{Username: l.Username, Password: l.Password}
  56. user, err := userService.Login(u)
  57. if err != nil {
  58. global.GVA_LOG.Error("登陆失败! 用户名不存在或者密码错误!", zap.Error(err))
  59. // 验证码次数+1
  60. global.BlackCache.Increment(key, 1)
  61. response.FailWithMessage("用户名不存在或者密码错误", c)
  62. return
  63. }
  64. if user.Enable != 1 {
  65. global.GVA_LOG.Error("登陆失败! 用户被禁止登录!")
  66. // 验证码次数+1
  67. global.BlackCache.Increment(key, 1)
  68. response.FailWithMessage("用户被禁止登录", c)
  69. return
  70. }
  71. b.TokenNext(c, *user)
  72. return
  73. }
  74. // 验证码次数+1
  75. global.BlackCache.Increment(key, 1)
  76. response.FailWithMessage("验证码错误", c)
  77. }
  78. // TokenNext 登录以后签发jwt
  79. func (b *BaseApi) TokenNext(c *gin.Context, user dao.SysUser) {
  80. j := &utils.JWT{SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey)} // 唯一签名
  81. claims := j.CreateClaims(systemReq.BaseClaims{
  82. UUID: user.UUID,
  83. ID: user.ID,
  84. NickName: user.NickName,
  85. Username: user.Username,
  86. AuthorityId: user.AuthorityId,
  87. })
  88. token, err := j.CreateToken(claims)
  89. if err != nil {
  90. global.GVA_LOG.Error("获取token失败!", zap.Error(err))
  91. response.FailWithMessage("获取token失败", c)
  92. return
  93. }
  94. if !global.GVA_CONFIG.System.UseMultipoint {
  95. utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
  96. response.OkWithDetailed(systemRes.LoginResponse{
  97. User: user,
  98. Token: token,
  99. ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
  100. }, "登录成功", c)
  101. return
  102. }
  103. if jwtStr, err := jwtService.GetRedisJWT(user.Username); err == redis.Nil {
  104. if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
  105. global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
  106. response.FailWithMessage("设置登录状态失败", c)
  107. return
  108. }
  109. utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
  110. response.OkWithDetailed(systemRes.LoginResponse{
  111. User: user,
  112. Token: token,
  113. ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
  114. }, "登录成功", c)
  115. } else if err != nil {
  116. global.GVA_LOG.Error("设置登录状态失败!", zap.Error(err))
  117. response.FailWithMessage("设置登录状态失败", c)
  118. } else {
  119. var blackJWT dao.JwtBlacklist
  120. blackJWT.Jwt = jwtStr
  121. if err := jwtService.JsonInBlacklist(blackJWT); err != nil {
  122. response.FailWithMessage("jwt作废失败", c)
  123. return
  124. }
  125. if err := jwtService.SetRedisJWT(token, user.Username); err != nil {
  126. response.FailWithMessage("设置登录状态失败", c)
  127. return
  128. }
  129. utils.SetToken(c, token, int(claims.RegisteredClaims.ExpiresAt.Unix()-time.Now().Unix()))
  130. response.OkWithDetailed(systemRes.LoginResponse{
  131. User: user,
  132. Token: token,
  133. ExpiresAt: claims.RegisteredClaims.ExpiresAt.Unix() * 1000,
  134. }, "登录成功", c)
  135. }
  136. }
  137. // Register
  138. // @Tags SysUser
  139. // @Summary 用户注册账号
  140. // @Produce application/json
  141. // @Param data body systemReq.Register true "用户名, 昵称, 密码, 角色ID"
  142. // @Success 200 {object} response.Response{data=systemRes.SysUserResponse,msg=string} "用户注册账号,返回包括用户信息"
  143. // @Router /user/admin_register [post]
  144. func (b *BaseApi) Register(c *gin.Context) {
  145. var r systemReq.Register
  146. err := c.ShouldBindJSON(&r)
  147. if err != nil {
  148. response.FailWithMessage(err.Error(), c)
  149. return
  150. }
  151. err = utils.Verify(r, utils.RegisterVerify)
  152. if err != nil {
  153. response.FailWithMessage(err.Error(), c)
  154. return
  155. }
  156. user := &dao.SysUser{Username: r.Username, NickName: r.NickName, Password: r.Password, HeaderImg: r.HeaderImg, AuthorityId: r.AuthorityId, Enable: r.Enable, Phone: r.Phone, Email: r.Email}
  157. userReturn, err := userService.Register(*user)
  158. if err != nil {
  159. global.GVA_LOG.Error("注册失败!", zap.Error(err))
  160. response.FailWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册失败", c)
  161. return
  162. }
  163. response.OkWithDetailed(systemRes.SysUserResponse{User: userReturn}, "注册成功", c)
  164. }
  165. // ChangePassword
  166. // @Tags SysUser
  167. // @Summary 用户修改密码
  168. // @Security ApiKeyAuth
  169. // @Produce application/json
  170. // @Param data body systemReq.ChangePasswordReq true "用户名, 原密码, 新密码"
  171. // @Success 200 {object} response.Response{msg=string} "用户修改密码"
  172. // @Router /user/changePassword [post]
  173. func (b *BaseApi) ChangePassword(c *gin.Context) {
  174. var req systemReq.ChangePasswordReq
  175. err := c.ShouldBindJSON(&req)
  176. if err != nil {
  177. response.FailWithMessage(err.Error(), c)
  178. return
  179. }
  180. err = utils.Verify(req, utils.ChangePasswordVerify)
  181. if err != nil {
  182. response.FailWithMessage(err.Error(), c)
  183. return
  184. }
  185. uid := utils.GetUserID(c)
  186. u := &dao.SysUser{GVA_MODEL: global.GVA_MODEL{ID: uid}, Password: req.Password}
  187. _, err = userService.ChangePassword(u, req.NewPassword)
  188. if err != nil {
  189. global.GVA_LOG.Error("修改失败!", zap.Error(err))
  190. response.FailWithMessage("修改失败,原密码与当前账户不符", c)
  191. return
  192. }
  193. response.OkWithMessage("修改成功", c)
  194. }
  195. // GetUserList
  196. // @Tags SysUser
  197. // @Summary 分页获取用户列表
  198. // @Security ApiKeyAuth
  199. // @accept application/json
  200. // @Produce application/json
  201. // @Param data body request.PageInfo true "页码, 每页大小"
  202. // @Success 200 {object} response.Response{data=response.PageResult,msg=string} "分页获取用户列表,返回包括列表,总数,页码,每页数量"
  203. // @Router /user/getUserList [post]
  204. func (b *BaseApi) GetUserList(c *gin.Context) {
  205. var pageInfo request.PageInfo
  206. err := c.ShouldBindJSON(&pageInfo)
  207. if err != nil {
  208. response.FailWithMessage(err.Error(), c)
  209. return
  210. }
  211. err = utils.Verify(pageInfo, utils.PageInfoVerify)
  212. if err != nil {
  213. response.FailWithMessage(err.Error(), c)
  214. return
  215. }
  216. list, total, err := userService.GetUserInfoList(pageInfo)
  217. if err != nil {
  218. global.GVA_LOG.Error("获取失败!", zap.Error(err))
  219. response.FailWithMessage("获取失败", c)
  220. return
  221. }
  222. response.OkWithDetailed(response.PageResult{
  223. List: list,
  224. Total: total,
  225. Page: pageInfo.Page,
  226. PageSize: pageInfo.PageSize,
  227. }, "获取成功", c)
  228. }
  229. func (b *BaseApi) CreateUserTunnels(c *gin.Context) {
  230. var info request.UserTunnels
  231. err := c.ShouldBindJSON(&info)
  232. if err != nil {
  233. response.FailWithMessage(err.Error(), c)
  234. return
  235. }
  236. err = userService.CreateUserTunnels(info)
  237. if err != nil {
  238. logger.Get().Errorf("分配隧道失败! %v", err)
  239. response.FailWithMessage("分配隧道失败", c)
  240. return
  241. }
  242. response.OkWithMessage("分配隧道成功", c)
  243. }
  244. // SetUserAuthority
  245. // @Tags SysUser
  246. // @Summary 更改用户权限
  247. // @Security ApiKeyAuth
  248. // @accept application/json
  249. // @Produce application/json
  250. // @Param data body systemReq.SetUserAuth true "用户UUID, 角色ID"
  251. // @Success 200 {object} response.Response{msg=string} "设置用户权限"
  252. // @Router /user/setUserAuthority [post]
  253. func (b *BaseApi) SetUserAuthority(c *gin.Context) {
  254. var sua systemReq.SetUserAuth
  255. err := c.ShouldBindJSON(&sua)
  256. if err != nil {
  257. response.FailWithMessage(err.Error(), c)
  258. return
  259. }
  260. if UserVerifyErr := utils.Verify(sua, utils.SetUserAuthorityVerify); UserVerifyErr != nil {
  261. response.FailWithMessage(UserVerifyErr.Error(), c)
  262. return
  263. }
  264. userID := utils.GetUserID(c)
  265. err = userService.SetUserAuthority(userID, sua.AuthorityId)
  266. if err != nil {
  267. global.GVA_LOG.Error("修改失败!", zap.Error(err))
  268. response.FailWithMessage(err.Error(), c)
  269. return
  270. }
  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.Error(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.Unix(), 10))
  280. utils.SetToken(c, token, int((claims.ExpiresAt.Unix()-time.Now().Unix())/60))
  281. response.OkWithMessage("修改成功", c)
  282. }
  283. }
  284. // SetUserAuthorities
  285. // @Tags SysUser
  286. // @Summary 设置用户权限
  287. // @Security ApiKeyAuth
  288. // @accept application/json
  289. // @Produce application/json
  290. // @Param data body systemReq.SetUserAuthorities true "用户UUID, 角色ID"
  291. // @Success 200 {object} response.Response{msg=string} "设置用户权限"
  292. // @Router /user/setUserAuthorities [post]
  293. func (b *BaseApi) SetUserAuthorities(c *gin.Context) {
  294. var sua systemReq.SetUserAuthorities
  295. err := c.ShouldBindJSON(&sua)
  296. if err != nil {
  297. response.FailWithMessage(err.Error(), c)
  298. return
  299. }
  300. err = userService.SetUserAuthorities(sua.ID, sua.AuthorityId)
  301. if err != nil {
  302. global.GVA_LOG.Error("修改失败!", zap.Error(err))
  303. response.FailWithMessage("修改失败", c)
  304. return
  305. }
  306. response.OkWithMessage("修改成功", c)
  307. }
  308. // DeleteUser
  309. // @Tags SysUser
  310. // @Summary 删除用户
  311. // @Security ApiKeyAuth
  312. // @accept application/json
  313. // @Produce application/json
  314. // @Param data body request.GetById true "用户ID"
  315. // @Success 200 {object} response.Response{msg=string} "删除用户"
  316. // @Router /user/deleteUser [delete]
  317. func (b *BaseApi) DeleteUser(c *gin.Context) {
  318. var reqId request.GetById
  319. err := c.ShouldBindJSON(&reqId)
  320. if err != nil {
  321. response.FailWithMessage(err.Error(), c)
  322. return
  323. }
  324. err = utils.Verify(reqId, utils.IdVerify)
  325. if err != nil {
  326. response.FailWithMessage(err.Error(), c)
  327. return
  328. }
  329. jwtId := utils.GetUserID(c)
  330. if jwtId == uint(reqId.ID) {
  331. response.FailWithMessage("删除失败, 自杀失败", c)
  332. return
  333. }
  334. err = userService.DeleteUser(reqId.ID)
  335. if err != nil {
  336. global.GVA_LOG.Error("删除失败!", zap.Error(err))
  337. response.FailWithMessage("删除失败", c)
  338. return
  339. }
  340. response.OkWithMessage("删除成功", c)
  341. }
  342. // SetUserInfo
  343. // @Tags SysUser
  344. // @Summary 设置用户信息
  345. // @Security ApiKeyAuth
  346. // @accept application/json
  347. // @Produce application/json
  348. // @Param data body system.SysUser true "ID, 用户名, 昵称, 头像链接"
  349. // @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "设置用户信息"
  350. // @Router /user/setUserInfo [put]
  351. func (b *BaseApi) SetUserInfo(c *gin.Context) {
  352. var user systemReq.ChangeUserInfo
  353. err := c.ShouldBindJSON(&user)
  354. if err != nil {
  355. response.FailWithMessage(err.Error(), c)
  356. return
  357. }
  358. err = utils.Verify(user, utils.IdVerify)
  359. if err != nil {
  360. response.FailWithMessage(err.Error(), c)
  361. return
  362. }
  363. if user.AuthorityIds != 0 {
  364. err = userService.SetUserAuthorities(user.ID, user.AuthorityIds)
  365. if err != nil {
  366. global.GVA_LOG.Error("设置失败!", zap.Error(err))
  367. response.FailWithMessage("设置失败", c)
  368. return
  369. }
  370. }
  371. err = userService.SetUserInfo(dao.SysUser{
  372. GVA_MODEL: global.GVA_MODEL{
  373. ID: user.ID,
  374. },
  375. NickName: user.NickName,
  376. HeaderImg: user.HeaderImg,
  377. Phone: user.Phone,
  378. Email: user.Email,
  379. SideMode: user.SideMode,
  380. Enable: user.Enable,
  381. })
  382. if err != nil {
  383. global.GVA_LOG.Error("设置失败!", zap.Error(err))
  384. response.FailWithMessage("设置失败", c)
  385. return
  386. }
  387. response.OkWithMessage("设置成功", c)
  388. }
  389. // SetSelfInfo
  390. // @Tags SysUser
  391. // @Summary 设置用户信息
  392. // @Security ApiKeyAuth
  393. // @accept application/json
  394. // @Produce application/json
  395. // @Param data body system.SysUser true "ID, 用户名, 昵称, 头像链接"
  396. // @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "设置用户信息"
  397. // @Router /user/SetSelfInfo [put]
  398. func (b *BaseApi) SetSelfInfo(c *gin.Context) {
  399. var user systemReq.ChangeUserInfo
  400. err := c.ShouldBindJSON(&user)
  401. if err != nil {
  402. response.FailWithMessage(err.Error(), c)
  403. return
  404. }
  405. user.ID = utils.GetUserID(c)
  406. err = userService.SetSelfInfo(dao.SysUser{
  407. GVA_MODEL: global.GVA_MODEL{
  408. ID: user.ID,
  409. },
  410. NickName: user.NickName,
  411. HeaderImg: user.HeaderImg,
  412. Phone: user.Phone,
  413. Email: user.Email,
  414. SideMode: user.SideMode,
  415. Enable: user.Enable,
  416. })
  417. if err != nil {
  418. global.GVA_LOG.Error("设置失败!", zap.Error(err))
  419. response.FailWithMessage("设置失败", c)
  420. return
  421. }
  422. response.OkWithMessage("设置成功", c)
  423. }
  424. // GetUserInfo
  425. // @Tags SysUser
  426. // @Summary 获取用户信息
  427. // @Security ApiKeyAuth
  428. // @accept application/json
  429. // @Produce application/json
  430. // @Success 200 {object} response.Response{data=map[string]interface{},msg=string} "获取用户信息"
  431. // @Router /user/getUserInfo [get]
  432. func (b *BaseApi) GetUserInfo(c *gin.Context) {
  433. uuid := utils.GetUserUuid(c)
  434. ReqUser, err := userService.GetUserInfo(uuid)
  435. if err != nil {
  436. global.GVA_LOG.Error("获取失败!", zap.Error(err))
  437. response.FailWithMessage("获取失败", c)
  438. return
  439. }
  440. response.OkWithDetailed(gin.H{"userInfo": ReqUser}, "获取成功", c)
  441. }
  442. // ResetPassword
  443. // @Tags SysUser
  444. // @Summary 重置用户密码
  445. // @Security ApiKeyAuth
  446. // @Produce application/json
  447. // @Param data body system.SysUser true "ID"
  448. // @Success 200 {object} response.Response{msg=string} "重置用户密码"
  449. // @Router /user/resetPassword [post]
  450. func (b *BaseApi) ResetPassword(c *gin.Context) {
  451. var user dao.SysUser
  452. err := c.ShouldBindJSON(&user)
  453. if err != nil {
  454. response.FailWithMessage(err.Error(), c)
  455. return
  456. }
  457. err = userService.ResetPassword(user.ID)
  458. if err != nil {
  459. global.GVA_LOG.Error("重置失败!", zap.Error(err))
  460. response.FailWithMessage("重置失败"+err.Error(), c)
  461. return
  462. }
  463. response.OkWithMessage("重置成功", c)
  464. }