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.

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