users_controller.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package v1
  2. import (
  3. "github.com/runningwater/gohub/app/models/user"
  4. "github.com/runningwater/gohub/app/requests"
  5. "github.com/runningwater/gohub/pkg/auth"
  6. "github.com/runningwater/gohub/pkg/config"
  7. "github.com/runningwater/gohub/pkg/file"
  8. "github.com/runningwater/gohub/pkg/response"
  9. "github.com/gin-gonic/gin"
  10. )
  11. type UsersController struct {
  12. BaseApiController
  13. }
  14. // CurrentUser 当前登录用户信息
  15. func (ctrl *UsersController) CurrentUser(c *gin.Context) {
  16. users := auth.CurrentUser(c)
  17. response.Data(c, users)
  18. }
  19. // Index 所有用户
  20. func (ctrl *UsersController) Index(c *gin.Context) {
  21. // 输入参数校验
  22. request := requests.PaginationRequest{}
  23. if ok := requests.Validate(c, &request, requests.Pagination); !ok {
  24. return
  25. }
  26. data, pager := user.Paginate(c, 2)
  27. response.JSON(c, gin.H{
  28. "data": data,
  29. "pager": pager,
  30. })
  31. }
  32. // UpdateProfile 更新用户信息
  33. func (ctrl *UsersController) UpdateProfile(c *gin.Context) {
  34. request := requests.UserUpdateProfileRequest{}
  35. if ok := requests.Validate(c, &request, requests.UserUpdateProfile); !ok {
  36. return
  37. }
  38. currentUser := auth.CurrentUser(c)
  39. currentUser.Name = request.Name
  40. currentUser.City = request.City
  41. currentUser.Introduction = request.Introduction
  42. affected := currentUser.Save()
  43. if affected > 0 {
  44. response.Data(c, currentUser)
  45. } else {
  46. response.Abort500(c, "更新失败,请稍后尝试")
  47. }
  48. }
  49. // UpdateEmail 更新用户邮箱
  50. func (ctrl *UsersController) UpdateEmail(c *gin.Context) {
  51. request := requests.UserUpdateEmailRequest{}
  52. if ok := requests.Validate(c, &request, requests.UserUpdateEmail); !ok {
  53. return
  54. }
  55. currentUser := auth.CurrentUser(c)
  56. currentUser.Email = request.Email
  57. affected := currentUser.Save()
  58. if affected > 0 {
  59. response.Success(c)
  60. return
  61. }
  62. response.Abort500(c, "更新失败,请稍后尝试")
  63. }
  64. // UpdateAvatar 更新用户头像
  65. func (ctrl *UsersController) UpdateAvatar(c *gin.Context) {
  66. request := requests.UserUpdateAvatarRequest{}
  67. if ok := requests.Validate(c, &request, requests.UserUpdateAvatar); !ok {
  68. return
  69. }
  70. avatar, err := file.SaveUploadAvatar(c, request.Avatar)
  71. if err != nil {
  72. response.Abort500(c, "上传头像失败,请稍后尝试")
  73. return
  74. }
  75. currentUser := auth.CurrentUser(c)
  76. currentUser.Avatar = config.GetString("app.url") + "/" + avatar
  77. _ = currentUser.Save()
  78. response.Data(c, currentUser)
  79. }