2024-02-24 16:01:08 +01:00
|
|
|
package controllers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.gnous.eu/Rick/calendrier/models"
|
|
|
|
"git.gnous.eu/Rick/calendrier/services"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
2024-02-24 20:30:31 +01:00
|
|
|
"github.com/golang-jwt/jwt/v5"
|
2024-02-24 16:01:08 +01:00
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
|
|
|
// @Summary Créer un nouvel utilisateur
|
|
|
|
// @Tag user
|
|
|
|
// @Param user body models.User true "L'utilisateur à créer"
|
|
|
|
// @Success 200 int
|
|
|
|
// @Failure 400 "Mauvaise structure"
|
|
|
|
// @Failure 401 "Token mal formaté"
|
|
|
|
// @Failure 500 "Erreur dans la base de données"
|
|
|
|
// @Router /user [post]
|
|
|
|
func CreateUser(c *fiber.Ctx) error {
|
|
|
|
tmp := new(models.User)
|
|
|
|
err := c.BodyParser(tmp)
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"err": err.Error()})
|
|
|
|
}
|
|
|
|
|
|
|
|
err = tmp.HashPassword()
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"err": err.Error()})
|
|
|
|
}
|
|
|
|
|
|
|
|
err = services.CreateUser(tmp)
|
|
|
|
if err != nil {
|
|
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"err": err.Error()})
|
|
|
|
}
|
|
|
|
|
|
|
|
return c.SendStatus(fiber.StatusOK)
|
|
|
|
}
|
|
|
|
|
|
|
|
// @Summary Connexion
|
|
|
|
// @Tag user
|
|
|
|
// @Param user body models.User true "L'utilisateur voulant se connecter"
|
|
|
|
// @Success 200 string
|
|
|
|
// @Failure 401 "Mauvais mot de passe"
|
|
|
|
// @Failure 500 "Erreur dans la base de données"
|
|
|
|
// @Router /login [post]
|
|
|
|
func GetToken(c *fiber.Ctx) error {
|
|
|
|
log := new(models.User)
|
|
|
|
err := c.BodyParser(log)
|
|
|
|
|
|
|
|
tmp, err := services.GetUserByName(log.Name)
|
|
|
|
if err != nil {
|
|
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"err": err.Error()})
|
|
|
|
}
|
|
|
|
|
|
|
|
err = bcrypt.CompareHashAndPassword([]byte(tmp.Password), []byte(log.Password))
|
|
|
|
if err != nil {
|
|
|
|
return c.SendStatus(fiber.StatusUnauthorized)
|
|
|
|
} else {
|
2024-02-24 20:30:31 +01:00
|
|
|
claims := jwt.MapClaims{
|
2024-02-24 16:01:08 +01:00
|
|
|
"name": tmp.Name,
|
|
|
|
"exp": time.Now().Add(time.Hour * 72).Unix(),
|
|
|
|
}
|
|
|
|
|
2024-02-24 20:30:31 +01:00
|
|
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
2024-02-24 16:01:08 +01:00
|
|
|
t, err := token.SignedString([]byte(os.Getenv("JWT_SECRET")))
|
|
|
|
if err != nil {
|
|
|
|
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"err": err.Error()})
|
|
|
|
} else {
|
|
|
|
return c.Status(fiber.StatusOK).JSON(fiber.Map{"token": t})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|