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.

296 lines
9.1 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. []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: int64(time.Now().Unix() - 1000), // 签名生效时间
  90. ExpiresAt: int64(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. } else {
  98. if global.GVA_CONFIG.System.UseMultipoint {
  99. var loginJwt model.JwtBlacklist
  100. loginJwt.Jwt = token
  101. err, jwtStr := service.GetRedisJWT(user.Username)
  102. if err == redis.Nil {
  103. err2 := service.SetRedisJWT(loginJwt, user.Username)
  104. if err2 != nil {
  105. response.FailWithMessage("设置登录状态失败", c)
  106. } else {
  107. response.OkWithData(resp.LoginResponse{
  108. User: user,
  109. Token: token,
  110. ExpiresAt: clams.StandardClaims.ExpiresAt * 1000,
  111. }, c)
  112. }
  113. } else if err != nil {
  114. response.FailWithMessage(fmt.Sprintf("%v", err), c)
  115. } else {
  116. var blackJWT model.JwtBlacklist
  117. blackJWT.Jwt = jwtStr
  118. err3 := service.JsonInBlacklist(blackJWT)
  119. if err3 != nil {
  120. response.FailWithMessage("jwt作废失败", c)
  121. } else {
  122. err2 := service.SetRedisJWT(loginJwt, user.Username)
  123. if err2 != nil {
  124. response.FailWithMessage("设置登录状态失败", c)
  125. } else {
  126. response.OkWithData(resp.LoginResponse{
  127. User: user,
  128. Token: token,
  129. ExpiresAt: clams.StandardClaims.ExpiresAt * 1000,
  130. }, c)
  131. }
  132. }
  133. }
  134. } else {
  135. response.OkWithData(resp.LoginResponse{
  136. User: user,
  137. Token: token,
  138. ExpiresAt: clams.StandardClaims.ExpiresAt * 1000,
  139. }, c)
  140. }
  141. }
  142. }
  143. // @Tags SysUser
  144. // @Summary 用户修改密码
  145. // @Security ApiKeyAuth
  146. // @Produce application/json
  147. // @Param data body request.ChangePasswordStruct true "用户修改密码"
  148. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  149. // @Router /user/changePassword [put]
  150. func ChangePassword(c *gin.Context) {
  151. var params request.ChangePasswordStruct
  152. _ = c.ShouldBindJSON(&params)
  153. UserVerify := utils.Rules{
  154. "Username": {utils.NotEmpty()},
  155. "Password": {utils.NotEmpty()},
  156. "NewPassword": {utils.NotEmpty()},
  157. }
  158. UserVerifyErr := utils.Verify(params, UserVerify)
  159. if UserVerifyErr != nil {
  160. response.FailWithMessage(UserVerifyErr.Error(), c)
  161. return
  162. }
  163. U := &model.SysUser{Username: params.Username, Password: params.Password}
  164. if err, _ := service.ChangePassword(U, params.NewPassword); err != nil {
  165. response.FailWithMessage("修改失败,请检查用户名密码", c)
  166. } else {
  167. response.OkWithMessage("修改成功", c)
  168. }
  169. }
  170. type UserHeaderImg struct {
  171. HeaderImg multipart.File `json:"headerImg"`
  172. }
  173. // @Tags SysUser
  174. // @Summary 用户上传头像
  175. // @Security ApiKeyAuth
  176. // @accept multipart/form-data
  177. // @Produce application/json
  178. // @Param headerImg formData file true "用户上传头像"
  179. // @Param username formData string true "用户上传头像"
  180. // @Success 200 {string} string "{"success":true,"data":{},"msg":"上传成功"}"
  181. // @Router /user/uploadHeaderImg [post]
  182. func UploadHeaderImg(c *gin.Context) {
  183. claims, _ := c.Get("claims")
  184. //获取头像文件
  185. // 这里我们通过断言获取 claims内的所有内容
  186. waitUse := claims.(*request.CustomClaims)
  187. uuid := waitUse.UUID
  188. _, header, err := c.Request.FormFile("headerImg")
  189. //便于找到用户 以后从jwt中取
  190. if err != nil {
  191. response.FailWithMessage(fmt.Sprintf("上传文件失败,%v", err), c)
  192. } else {
  193. //文件上传后拿到文件路径
  194. err, filePath, _ := utils.Upload(header)
  195. if err != nil {
  196. response.FailWithMessage(fmt.Sprintf("接收返回值失败,%v", err), c)
  197. } else {
  198. //修改数据库后得到修改后的user并且返回供前端使用
  199. err, user := service.UploadHeaderImg(uuid, filePath)
  200. if err != nil {
  201. response.FailWithMessage(fmt.Sprintf("修改数据库链接失败,%v", err), c)
  202. } else {
  203. response.OkWithData(resp.SysUserResponse{User: *user}, c)
  204. }
  205. }
  206. }
  207. }
  208. // @Tags SysUser
  209. // @Summary 分页获取用户列表
  210. // @Security ApiKeyAuth
  211. // @accept application/json
  212. // @Produce application/json
  213. // @Param data body request.PageInfo true "分页获取用户列表"
  214. // @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
  215. // @Router /user/getUserList [post]
  216. func GetUserList(c *gin.Context) {
  217. var pageInfo request.PageInfo
  218. _ = c.ShouldBindJSON(&pageInfo)
  219. PageVerifyErr := utils.Verify(pageInfo, utils.CustomizeMap["PageVerify"])
  220. if PageVerifyErr != nil {
  221. response.FailWithMessage(PageVerifyErr.Error(), c)
  222. return
  223. }
  224. err, list, total := service.GetUserInfoList(pageInfo)
  225. if err != nil {
  226. response.FailWithMessage(fmt.Sprintf("获取数据失败,%v", err), c)
  227. } else {
  228. response.OkWithData(resp.PageResult{
  229. List: list,
  230. Total: total,
  231. Page: pageInfo.Page,
  232. PageSize: pageInfo.PageSize,
  233. }, c)
  234. }
  235. }
  236. // @Tags SysUser
  237. // @Summary 设置用户权限
  238. // @Security ApiKeyAuth
  239. // @accept application/json
  240. // @Produce application/json
  241. // @Param data body request.SetUserAuth true "设置用户权限"
  242. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  243. // @Router /user/setUserAuthority [post]
  244. func SetUserAuthority(c *gin.Context) {
  245. var sua request.SetUserAuth
  246. _ = c.ShouldBindJSON(&sua)
  247. UserVerify := utils.Rules{
  248. "UUID": {utils.NotEmpty()},
  249. "AuthorityId": {utils.NotEmpty()},
  250. }
  251. UserVerifyErr := utils.Verify(sua, UserVerify)
  252. if UserVerifyErr != nil {
  253. response.FailWithMessage(UserVerifyErr.Error(), c)
  254. return
  255. }
  256. err := service.SetUserAuthority(sua.UUID, sua.AuthorityId)
  257. if err != nil {
  258. response.FailWithMessage(fmt.Sprintf("修改失败,%v", err), c)
  259. } else {
  260. response.OkWithMessage("修改成功", c)
  261. }
  262. }
  263. // @Tags SysUser
  264. // @Summary 删除用户
  265. // @Security ApiKeyAuth
  266. // @accept application/json
  267. // @Produce application/json
  268. // @Param data body request.GetById true "删除用户"
  269. // @Success 200 {string} string "{"success":true,"data":{},"msg":"修改成功"}"
  270. // @Router /user/deleteUser [delete]
  271. func DeleteUser(c *gin.Context) {
  272. var reqId request.GetById
  273. _ = c.ShouldBindJSON(&reqId)
  274. IdVerifyErr := utils.Verify(reqId, utils.CustomizeMap["IdVerify"])
  275. if IdVerifyErr != nil {
  276. response.FailWithMessage(IdVerifyErr.Error(), c)
  277. return
  278. }
  279. err := service.DeleteUser(reqId.Id)
  280. if err != nil {
  281. response.FailWithMessage(fmt.Sprintf("删除失败,%v", err), c)
  282. } else {
  283. response.OkWithMessage("删除成功", c)
  284. }
  285. }