sys_user.go 16 KB

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