123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- package handlers
- import (
- "github.com/gofiber/fiber/v2"
- "github.com/golang-jwt/jwt/v4"
- "notabug.org/alimiracle/my-website-api/hash"
- "notabug.org/alimiracle/my-website-api/models"
- )
- func (self Handler) GetAllUsers(c *fiber.Ctx) error {
- var users []models.User
- self.Database.FindAll(&users)
- return c.Status(fiber.StatusOK).JSON(&users)
- }
- func (self Handler) AddUser(c *fiber.Ctx) error {
- jwt_user := c.Locals("user").(*jwt.Token)
- claims := jwt_user.Claims.(jwt.MapClaims)
- is_admin := claims["admin"].(bool)
- if is_admin != true {
- c.Status(fiber.StatusBadRequest)
- return c.JSON(fiber.Map{
- "error": "your not admin",
- })
- }
- body := models.User{}
- if err := c.BodyParser(&body); err != nil {
- return fiber.NewError(fiber.StatusBadRequest, err.Error())
- }
- body.Pass = hash.HashPassword(body.Pass)
- // insert new db entry
- err := self.Database.Create(&body)
- if err != nil {
- return fiber.NewError(fiber.StatusNotFound, err.Error())
- }
- return c.Status(fiber.StatusCreated).JSON(&body)
- }
- func (self Handler) UpdateUser(c *fiber.Ctx) error {
- jwt_user := c.Locals("user").(*jwt.Token)
- claims := jwt_user.Claims.(jwt.MapClaims)
- is_admin := claims["admin"].(bool)
- if is_admin != true {
- c.Status(fiber.StatusBadRequest)
- return c.JSON(fiber.Map{
- "error": "your not admin",
- })
- }
- id := c.Params("id")
- body := models.User{}
- if err := c.BodyParser(&body); err != nil {
- return fiber.NewError(fiber.StatusBadRequest, err.Error())
- }
- body.Pass = hash.HashPassword(body.Pass)
- err := self.Database.Update(&body, id)
- if err != nil {
- return fiber.NewError(fiber.StatusNotFound, err.Error())
- }
- return c.SendStatus(fiber.StatusOK)
- }
- func (self Handler) DeleteUser(c *fiber.Ctx) error {
- jwt_user := c.Locals("user").(*jwt.Token)
- claims := jwt_user.Claims.(jwt.MapClaims)
- is_admin := claims["admin"].(bool)
- if is_admin != true {
- c.Status(fiber.StatusBadRequest)
- return c.JSON(fiber.Map{
- "error": "your not admin",
- })
- }
- id := c.Params("id")
- var user models.User
- err := self.Database.Delete(&user, id)
- if err != nil {
- return fiber.NewError(fiber.StatusNotFound, err.Error())
- }
- return c.SendStatus(fiber.StatusOK)
- }
|