Return JWT at user creation

This commit is contained in:
nikurasu 2023-11-19 11:32:57 +01:00
parent 82b335c8cb
commit 525bfc59d2
Signed by: Nikurasu
GPG key ID: 9E7F14C03EF1F271
5 changed files with 44 additions and 3 deletions

View file

@ -6,6 +6,7 @@ import (
"ulmer-furs.de/pretix-proxy/v2/app/service" "ulmer-furs.de/pretix-proxy/v2/app/service"
"ulmer-furs.de/pretix-proxy/v2/app/util" "ulmer-furs.de/pretix-proxy/v2/app/util"
"ulmer-furs.de/pretix-proxy/v2/entities" "ulmer-furs.de/pretix-proxy/v2/entities"
"ulmer-furs.de/pretix-proxy/v2/entities/responses"
) )
func CreateUser(c *fiber.Ctx) error { func CreateUser(c *fiber.Ctx) error {
@ -27,11 +28,21 @@ func CreateUser(c *fiber.Ctx) error {
} else { } else {
user.HashedPassword = hashedPassword user.HashedPassword = hashedPassword
} }
if err := service.Create_User(*user); err != nil { if err := service.Create_User(user); err != nil {
return &fiber.Error{ return &fiber.Error{
Code: fiber.ErrInternalServerError.Code, Code: fiber.ErrInternalServerError.Code,
Message: "Internal Server Error", Message: "Internal Server Error",
} }
} }
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) return c.SendStatus(fiber.StatusOK)
} }

View file

@ -5,7 +5,7 @@ import (
"ulmer-furs.de/pretix-proxy/v2/entities" "ulmer-furs.de/pretix-proxy/v2/entities"
) )
func Create_User(user entities.User) error { func Create_User(user *entities.User) error {
result := config.Database.Create(&user) result := config.Database.Create(&user)
if result.Error != nil { if result.Error != nil {
return result.Error return result.Error

View file

@ -0,0 +1,23 @@
package util
import (
"time"
"github.com/golang-jwt/jwt/v5"
"ulmer-furs.de/pretix-proxy/v2/config"
"ulmer-furs.de/pretix-proxy/v2/entities"
)
func CreateToken(user *entities.User) (string, error) {
day := time.Hour * 24
claims := jwt.MapClaims{
"email": user.Email,
"exp": time.Now().Add(day * 1).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
t, err := token.SignedString([]byte(config.Env.Secret))
if err != nil {
return "", jwt.ErrTokenUnverifiable
}
return t, nil
}

View file

@ -0,0 +1,5 @@
package responses
type UserResponse struct {
Token string `json:"token"`
}

View file

@ -1,7 +1,9 @@
package entities package entities
import "gorm.io/gorm"
type User struct { type User struct {
Id int `gorm:"column:id;unique;not null"` gorm.Model
Email string `gorm:"column:email;not null" validate:"required"` Email string `gorm:"column:email;not null" validate:"required"`
Password string `gorm:"-" validate:"required"` Password string `gorm:"-" validate:"required"`
HashedPassword []byte `gorm:"column:hashed_password;not null"` HashedPassword []byte `gorm:"column:hashed_password;not null"`