sys_user.go 16 KB

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