diff --git a/src/app/controller/user_controller.go b/src/app/controller/user_controller.go index 2a8891b..13a2c26 100644 --- a/src/app/controller/user_controller.go +++ b/src/app/controller/user_controller.go @@ -6,6 +6,7 @@ import ( "ulmer-furs.de/pretix-proxy/v2/app/service" "ulmer-furs.de/pretix-proxy/v2/app/util" "ulmer-furs.de/pretix-proxy/v2/entities" + "ulmer-furs.de/pretix-proxy/v2/entities/responses" ) func CreateUser(c *fiber.Ctx) error { @@ -27,11 +28,21 @@ func CreateUser(c *fiber.Ctx) error { } else { user.HashedPassword = hashedPassword } - if err := service.Create_User(*user); err != nil { + if err := service.Create_User(user); err != nil { return &fiber.Error{ Code: fiber.ErrInternalServerError.Code, 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) } diff --git a/src/app/service/user.go b/src/app/service/user.go index a9563b5..d33631f 100644 --- a/src/app/service/user.go +++ b/src/app/service/user.go @@ -5,7 +5,7 @@ import ( "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) if result.Error != nil { return result.Error diff --git a/src/app/util/createToken.go b/src/app/util/createToken.go new file mode 100644 index 0000000..478736b --- /dev/null +++ b/src/app/util/createToken.go @@ -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 +} diff --git a/src/entities/responses/user_response.go b/src/entities/responses/user_response.go new file mode 100644 index 0000000..8e87449 --- /dev/null +++ b/src/entities/responses/user_response.go @@ -0,0 +1,5 @@ +package responses + +type UserResponse struct { + Token string `json:"token"` +} diff --git a/src/entities/user.go b/src/entities/user.go index 71f28b4..47a0f5e 100644 --- a/src/entities/user.go +++ b/src/entities/user.go @@ -1,7 +1,9 @@ package entities +import "gorm.io/gorm" + type User struct { - Id int `gorm:"column:id;unique;not null"` + gorm.Model Email string `gorm:"column:email;not null" validate:"required"` Password string `gorm:"-" validate:"required"` HashedPassword []byte `gorm:"column:hashed_password;not null"`