current_user.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package user
  2. import (
  3. "net/http"
  4. "github.com/0xJacky/Nginx-UI/api"
  5. "github.com/0xJacky/Nginx-UI/model"
  6. "github.com/gin-gonic/gin"
  7. "github.com/uozi-tech/cosy"
  8. "golang.org/x/crypto/bcrypt"
  9. )
  10. func GetCurrentUser(c *gin.Context) {
  11. user := api.CurrentUser(c)
  12. c.JSON(http.StatusOK, user)
  13. }
  14. func UpdateCurrentUser(c *gin.Context) {
  15. cosy.Core[model.User](c).
  16. SetValidRules(gin.H{
  17. "name": "required",
  18. }).
  19. Custom(func(c *cosy.Ctx[model.User]) {
  20. user := api.CurrentUser(c.Context)
  21. user.Name = c.Model.Name
  22. db := cosy.UseDB()
  23. err := db.Where("id = ?", user.ID).Updates(user).Error
  24. if err != nil {
  25. cosy.ErrHandler(c.Context, err)
  26. return
  27. }
  28. c.JSON(http.StatusOK, user)
  29. })
  30. }
  31. func UpdateCurrentUserPassword(c *gin.Context) {
  32. var json struct {
  33. OldPassword string `json:"old_password" binding:"required"`
  34. NewPassword string `json:"new_password" binding:"required"`
  35. }
  36. if !cosy.BindAndValid(c, &json) {
  37. return
  38. }
  39. user := api.CurrentUser(c)
  40. if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(json.OldPassword)); err != nil {
  41. cosy.ErrHandler(c, err)
  42. return
  43. }
  44. user.Password = json.NewPassword
  45. pwdBytes, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
  46. if err != nil {
  47. cosy.ErrHandler(c, err)
  48. return
  49. }
  50. db := cosy.UseDB()
  51. err = db.Where("id = ?", user.ID).Updates(&model.User{
  52. Password: string(pwdBytes),
  53. }).Error
  54. if err != nil {
  55. cosy.ErrHandler(c, err)
  56. return
  57. }
  58. c.JSON(http.StatusOK, gin.H{
  59. "message": "ok",
  60. })
  61. }