Add login route

This commit is contained in:
nikurasu 2023-11-19 16:37:52 +01:00
parent 525bfc59d2
commit f814888f1e
Signed by: Nikurasu
GPG key ID: 9E7F14C03EF1F271
5 changed files with 49 additions and 2 deletions

View file

@ -46,3 +46,38 @@ func CreateUser(c *fiber.Ctx) error {
})
return c.SendStatus(fiber.StatusOK)
}
func LoginUser(c *fiber.Ctx) error {
credentials := new(entities.User)
if err := c.BodyParser(credentials); err != nil {
return &fiber.Error{
Code: fiber.ErrUnauthorized.Code,
Message: "Unauthorized",
}
}
user, err := service.GetUserByEmail(credentials.Email)
if err != nil {
return &fiber.Error{
Code: fiber.ErrUnauthorized.Code,
Message: "Unauthorized",
}
}
err = bcrypt.CompareHashAndPassword(user.HashedPassword, []byte(credentials.Password))
if err != nil {
return &fiber.Error{
Code: fiber.ErrUnauthorized.Code,
Message: "Unauthorized",
}
}
token, err := util.CreateToken(&user)
if err != nil {
return &fiber.Error{
Code: fiber.ErrInternalServerError.Code,
Message: "Internal Server Error",
}
}
c.JSON(responses.UserResponse{
Token: token,
})
return c.SendStatus(fiber.StatusOK)
}

View file

@ -9,7 +9,7 @@ import (
func PrivateRoutes(app *fiber.App) {
apiv1 := app.Group("/api/v1")
event := apiv1.Group("/event")
event.Use(config.AuthMiddleware)
event.Use(config.JwtMiddleware)
//app.Get("/events", controller.ReturnEventsTableView)
event.Get("", controller.ReturnAllEvents)
event.Get("/:id", controller.ReturnEventById)

View file

@ -8,6 +8,7 @@ import (
func PublicRoutes(app *fiber.App) {
apiv1 := app.Group("/api/v1")
attendies := apiv1.Group("/attendies")
apiv1.Post("/login", controller.LoginUser)
apiv1.Get("/ping", controller.Ping)
attendies.Get("/:name", controller.GetAttendiesByEvent)
}

View file

@ -1,6 +1,8 @@
package service
import (
"errors"
"ulmer-furs.de/pretix-proxy/v2/config"
"ulmer-furs.de/pretix-proxy/v2/entities"
)
@ -12,3 +14,12 @@ func Create_User(user *entities.User) error {
}
return nil
}
func GetUserByEmail(email string) (entities.User, error) {
var user entities.User
result := config.Database.Where("email = ?", email).First(&user)
if result.RowsAffected == 0 {
return user, errors.New("user not found")
}
return user, nil
}

View file

@ -4,7 +4,7 @@ import "gorm.io/gorm"
type User struct {
gorm.Model
Email string `gorm:"column:email;not null" validate:"required"`
Email string `gorm:"column:email;not null;unique" validate:"required"`
Password string `gorm:"-" validate:"required"`
HashedPassword []byte `gorm:"column:hashed_password;not null"`
}