users.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package handlers
  2. import (
  3. "github.com/gofiber/fiber/v2"
  4. "github.com/golang-jwt/jwt/v4"
  5. "notabug.org/alimiracle/my-website-api/hash"
  6. "notabug.org/alimiracle/my-website-api/models"
  7. )
  8. func (self Handler) GetAllUsers(c *fiber.Ctx) error {
  9. var users []models.User
  10. self.Database.FindAll(&users)
  11. return c.Status(fiber.StatusOK).JSON(&users)
  12. }
  13. func (self Handler) AddUser(c *fiber.Ctx) error {
  14. jwt_user := c.Locals("user").(*jwt.Token)
  15. claims := jwt_user.Claims.(jwt.MapClaims)
  16. is_admin := claims["admin"].(bool)
  17. if is_admin != true {
  18. c.Status(fiber.StatusBadRequest)
  19. return c.JSON(fiber.Map{
  20. "error": "your not admin",
  21. })
  22. }
  23. body := models.User{}
  24. if err := c.BodyParser(&body); err != nil {
  25. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  26. }
  27. body.Pass = hash.HashPassword(body.Pass)
  28. // insert new db entry
  29. err := self.Database.Create(&body)
  30. if err != nil {
  31. return fiber.NewError(fiber.StatusNotFound, err.Error())
  32. }
  33. return c.Status(fiber.StatusCreated).JSON(&body)
  34. }
  35. func (self Handler) UpdateUser(c *fiber.Ctx) error {
  36. jwt_user := c.Locals("user").(*jwt.Token)
  37. claims := jwt_user.Claims.(jwt.MapClaims)
  38. is_admin := claims["admin"].(bool)
  39. if is_admin != true {
  40. c.Status(fiber.StatusBadRequest)
  41. return c.JSON(fiber.Map{
  42. "error": "your not admin",
  43. })
  44. }
  45. id := c.Params("id")
  46. body := models.User{}
  47. if err := c.BodyParser(&body); err != nil {
  48. return fiber.NewError(fiber.StatusBadRequest, err.Error())
  49. }
  50. body.Pass = hash.HashPassword(body.Pass)
  51. err := self.Database.Update(&body, id)
  52. if err != nil {
  53. return fiber.NewError(fiber.StatusNotFound, err.Error())
  54. }
  55. return c.SendStatus(fiber.StatusOK)
  56. }
  57. func (self Handler) DeleteUser(c *fiber.Ctx) error {
  58. jwt_user := c.Locals("user").(*jwt.Token)
  59. claims := jwt_user.Claims.(jwt.MapClaims)
  60. is_admin := claims["admin"].(bool)
  61. if is_admin != true {
  62. c.Status(fiber.StatusBadRequest)
  63. return c.JSON(fiber.Map{
  64. "error": "your not admin",
  65. })
  66. }
  67. id := c.Params("id")
  68. var user models.User
  69. err := self.Database.Delete(&user, id)
  70. if err != nil {
  71. return fiber.NewError(fiber.StatusNotFound, err.Error())
  72. }
  73. return c.SendStatus(fiber.StatusOK)
  74. }