You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

292 lines
8.9 KiB

  1. package v1
  2. import (
  3. "fmt"
  4. "gin-vue-admin/global"
  5. "gin-vue-admin/global/response"
  6. "gin-vue-admin/middleware"
  7. "gin-vue-admin/model"
  8. "gin-vue-admin/model/request"
  9. resp "gin-vue-admin/model/response"
  10. "gin-vue-admin/service"
  11. "gin-vue-admin/utils"
  12. "github.com/dgrijalva/jwt-go"
  13. "github.com/gin-gonic/gin"
  14. "github.com/go-redis/redis"
  15. "mime/multipart"
  16. "time"
  17. )
  18. // @Tags Base
  19. // @Summary 用户注册账号
  20. // @Produce application/json
  21. // @Param data body model.SysUser true "用户注册接口"
  22. // @Success 200 {string} string "{"success":true,"data":{},"msg":"注册成功"}"
  23. // @Router /base/register [post]
  24. func Register(c *gin.Context) {
  25. var R request.RegisterStruct
  26. _ = c.ShouldBindJSON(&R)
  27. UserVerify := utils.Rules{
  28. "Username": {utils.NotEmpty()},
  29. "NickName": {utils.NotEmpty()},
  30. "Password": {utils.NotEmpty()},
  31. "AuthorityId": {utils.NotEmpty()},
  32. }
  33. UserVerifyErr := utils.Verify(R, UserVerify)
  34. if UserVerifyErr != nil {
  35. response.FailWithMessage(UserVerifyErr.Error(), c)
  36. return
  37. }
  38. user := &model.SysUser{Username: R.Username, NickName: R.NickName, Password: R.Password, HeaderImg: R.HeaderImg, AuthorityId: R.AuthorityId}
  39. err, userReturn := service.Register(*user)
  40. if err != nil {
  41. response.FailWithDetailed(response.ERROR, resp.SysUserResponse{User: userReturn}, fmt.Sprintf("%v", err), c)
  42. } else {
  43. response.OkDetailed(resp.SysUserResponse{User: userReturn}, "注册成功", c)
  44. }
  45. }
  46. // @Tags Base
  47. // @Summary 用户登录
  48. // @Produce application/json
  49. // @Param data body request.RegisterAndLoginStruct true "用户登录接口"
  50. // @Success 200 {string} string "{"success":true,"data":{},"msg":"登陆成功"}"
  51. // @Router /base/login [post]
  52. func Login(c *gin.Context) {
  53. var L request.RegisterAndLoginStruct
  54. _ = c.ShouldBindJSON(&L)
  55. UserVerify := utils.Rules{
  56. "CaptchaId": {utils.NotEmpty()},
  57. "Captcha": {utils.NotEmpty()},
  58. "Username": {utils.NotEmpty()},
  59. "Password": {utils.NotEmpty()},
  60. }
  61. UserVerifyErr := utils.Verify(L, UserVerify)
  62. if UserVerifyErr != nil {
  63. response.FailWithMessage(UserVerifyErr.Error(), c)
  64. return
  65. }
  66. if store.Verify(L.CaptchaId, L.Captcha, true) {
  67. U := &model.SysUser{Username: L.Username, Password: L.Password}
  68. if err, user := service.Login(U); err != nil {
  69. response.FailWithMessage(fmt.Sprintf("用户名密码错误或%v", err), c)
  70. } else {
  71. tokenNext(c, *user)
  72. }
  73. } else {
  74. response.FailWithMessage("验证码错误", c)
  75. }
  76. }
  77. // 登录以后签发jwt
  78. func tokenNext(c *gin.Context, user model.SysUser) {
  79. j := &middleware.JWT{
  80. SigningKey: []byte(global.GVA_CONFIG.JWT.SigningKey), // 唯一签名
  81. }
  82. clams := request.CustomClaims{
  83. UUID: user.UUID,
  84. ID: user.ID,
  85. NickName: user.NickName,
  86. AuthorityId: user.AuthorityId,
  87. StandardClaims: jwt.StandardClaims{
  88. NotBefore: time.Now().Unix() - 1000, // 签名生效时间
  89. ExpiresAt: time.Now().Unix() + 60*60*24*7, // 过期时间 一周
  90. Issuer: "qmPlus", // 签名的发行者
  91. },
  92. }
  93. token, err := j.CreateToken(clams)
  94. if err != nil {
  95. response.FailWithMessage("获取token失败", c)
  96. return
  97. }
  98. if !global.GVA_CONFIG.System.UseMultipoint {
  99. response.OkWithData(resp.LoginResponse{
  100. User: user,
  101. Token: token,
  102. ExpiresAt: clams.StandardClaims.ExpiresAt * 1000,
  103. }, c)
  104. return
  105. }
  106. var loginJwt model.JwtBlacklist
  107. loginJwt.Jwt = token
  108. err, jwtStr := service.GetRedisJWT(user.Username)
  109. if err == redis.Nil {
  110. if err := service.SetRedisJWT(loginJwt, user.Username); err != nil {
  111. response.FailWithMessage("设置登录状态失败", c)
  112. return
  113. }
  114. response.OkWithData(resp.LoginResponse{
  115. User: user,
  116. Token: token,
  117. ExpiresAt: clams.StandardClaims.ExpiresAt * 1000,
  118. }, c)
  119. } else if err != nil {
  120. response.FailWithMessage(fmt.Sprintf("%v", err), c)
  121. } else {
  122. var blackJWT model.JwtBlacklist
  123. blackJWT.Jwt = jwtStr
  124. if err := service.JsonInBlacklist(blackJWT); err != nil {
  125. response.FailWithMessage("jwt作废失败", c)
  126. return
  127. }
  128. if err := service.SetRedisJWT(loginJwt, user.Username); err != nil {
  129. response.FailWithMessage("设置登录状态失败", c)
  130. return
  131. }
  132. response.OkWithData(resp.LoginResponse{
  133. User: user,
  134. Token: token,
  135. ExpiresAt: clams.StandardClaims.ExpiresAt * 1000,
  136. }, c)
  137. }
  138. }
  139. // @Tags SysUser
  140. // @Summary 用户修改密码
  141. // @Security ApiKeyAuth
  142. // @Produce application/json
  143. // @Param data body request.ChangePasswordStruct true "用户修改密码"
  144. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  145. // @Router /user/changePassword [put]
  146. func ChangePassword(c *gin.Context) {
  147. var params request.ChangePasswordStruct
  148. _ = c.ShouldBindJSON(&params)
  149. UserVerify := utils.Rules{
  150. "Username": {utils.NotEmpty()},
  151. "Password": {utils.NotEmpty()},
  152. "NewPassword": {utils.NotEmpty()},
  153. }
  154. UserVerifyErr := utils.Verify(params, UserVerify)
  155. if UserVerifyErr != nil {
  156. response.FailWithMessage(UserVerifyErr.Error(), c)
  157. return
  158. }
  159. U := &model.SysUser{Username: params.Username, Password: params.Password}
  160. if err, _ := service.ChangePassword(U, params.NewPassword); err != nil {
  161. response.FailWithMessage("修改失败,请检查用户名密码", c)
  162. } else {
  163. response.OkWithMessage("修改成功", c)
  164. }
  165. }
  166. type UserHeaderImg struct {
  167. HeaderImg multipart.File `json:"headerImg"`
  168. }
  169. // @Tags SysUser
  170. // @Summary 用户上传头像
  171. // @Security ApiKeyAuth
  172. // @accept multipart/form-data
  173. // @Produce application/json
  174. // @Param headerImg formData file true "用户上传头像"
  175. // @Param username formData string true "用户上传头像"
  176. // @Success 200 {string} string "{"success":true,"data":{},"msg":"上传成功"}"
  177. // @Router /user/uploadHeaderImg [post]
  178. func UploadHeaderImg(c *gin.Context) {
  179. claims, _ := c.Get("claims")
  180. // 获取头像文件
  181. // 这里我们通过断言获取 claims内的所有内容
  182. waitUse := claims.(*request.CustomClaims)
  183. uuid := waitUse.UUID
  184. _, header, err := c.Request.FormFile("headerImg")
  185. // 便于找到用户 以后从jwt中取
  186. if err != nil {
  187. response.FailWithMessage(fmt.Sprintf("上传文件失败,%v", err), c)
  188. } else {
  189. // 文件上传后拿到文件路径
  190. err, filePath, _ := utils.Upload(header)
  191. if err != nil {
  192. response.FailWithMessage(fmt.Sprintf("接收返回值失败,%v", err), c)
  193. } else {
  194. // 修改数据库后得到修改后的user并且返回供前端使用
  195. err, user := service.UploadHeaderImg(uuid, filePath)
  196. if err != nil {
  197. response.FailWithMessage(fmt.Sprintf("修改数据库链接失败,%v", err), c)
  198. } else {
  199. response.OkWithData(resp.SysUserResponse{User: *user}, c)
  200. }
  201. }
  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 GetUserList(c *gin.Context) {
  213. var pageInfo request.PageInfo
  214. _ = c.ShouldBindJSON(&pageInfo)
  215. PageVerifyErr := utils.Verify(pageInfo, utils.CustomizeMap["PageVerify"])
  216. if PageVerifyErr != nil {
  217. response.FailWithMessage(PageVerifyErr.Error(), c)
  218. return
  219. }
  220. err, list, total := service.GetUserInfoList(pageInfo)
  221. if err != nil {
  222. response.FailWithMessage(fmt.Sprintf("获取数据失败,%v", err), c)
  223. } else {
  224. response.OkWithData(resp.PageResult{
  225. List: list,
  226. Total: total,
  227. Page: pageInfo.Page,
  228. PageSize: pageInfo.PageSize,
  229. }, c)
  230. }
  231. }
  232. // @Tags SysUser
  233. // @Summary 设置用户权限
  234. // @Security ApiKeyAuth
  235. // @accept application/json
  236. // @Produce application/json
  237. // @Param data body request.SetUserAuth true "设置用户权限"
  238. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  239. // @Router /user/setUserAuthority [post]
  240. func SetUserAuthority(c *gin.Context) {
  241. var sua request.SetUserAuth
  242. _ = c.ShouldBindJSON(&sua)
  243. UserVerify := utils.Rules{
  244. "UUID": {utils.NotEmpty()},
  245. "AuthorityId": {utils.NotEmpty()},
  246. }
  247. UserVerifyErr := utils.Verify(sua, UserVerify)
  248. if UserVerifyErr != nil {
  249. response.FailWithMessage(UserVerifyErr.Error(), c)
  250. return
  251. }
  252. err := service.SetUserAuthority(sua.UUID, sua.AuthorityId)
  253. if err != nil {
  254. response.FailWithMessage(fmt.Sprintf("修改失败,%v", err), c)
  255. } else {
  256. response.OkWithMessage("修改成功", c)
  257. }
  258. }
  259. // @Tags SysUser
  260. // @Summary 删除用户
  261. // @Security ApiKeyAuth
  262. // @accept application/json
  263. // @Produce application/json
  264. // @Param data body request.GetById true "删除用户"
  265. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  266. // @Router /user/deleteUser [delete]
  267. func DeleteUser(c *gin.Context) {
  268. var reqId request.GetById
  269. _ = c.ShouldBindJSON(&reqId)
  270. IdVerifyErr := utils.Verify(reqId, utils.CustomizeMap["IdVerify"])
  271. if IdVerifyErr != nil {
  272. response.FailWithMessage(IdVerifyErr.Error(), c)
  273. return
  274. }
  275. err := service.DeleteUser(reqId.Id)
  276. if err != nil {
  277. response.FailWithMessage(fmt.Sprintf("删除失败,%v", err), c)
  278. } else {
  279. response.OkWithMessage("删除成功", c)
  280. }
  281. }