Initial chaos
This commit is contained in:
46
pkg/handler/userLogin.go
Normal file
46
pkg/handler/userLogin.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"twitch-clone/pkg/database"
|
||||
"twitch-clone/pkg/jwt"
|
||||
"twitch-clone/pkg/models"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username" validate:"required,min=4,max=32"`
|
||||
Password string `json:"password" validate:"required,min=8,max=128"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"access_token"`
|
||||
}
|
||||
|
||||
func Login(ctx *fiber.Ctx) error {
|
||||
db := database.Db()
|
||||
body := LoginRequest{}
|
||||
|
||||
if err := ctx.BodyParser(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := models.Validate.Struct(body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
user := new(models.User)
|
||||
result := db.Where(&models.User{Username: body.Username, Password: body.Password}).Select("id").First(user)
|
||||
|
||||
if result.Error != nil {
|
||||
return errors.New("invalid combination of username and password")
|
||||
}
|
||||
|
||||
token, err := jwt.GenerateJWT(models.Claim{ID: user.ID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return ctx.JSON(LoginResponse{Token: token})
|
||||
}
|
45
pkg/handler/userRegister.go
Normal file
45
pkg/handler/userRegister.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"twitch-clone/pkg/database"
|
||||
"twitch-clone/pkg/jwt"
|
||||
"twitch-clone/pkg/models"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
type RegisterRequest struct {
|
||||
Email string `json:"email" validate:"required,email"`
|
||||
Username string `json:"username" validate:"required,min=4,max=32"`
|
||||
Password string `json:"password" validate:"required,min=8,max=128"`
|
||||
}
|
||||
|
||||
type RegisterResponse struct {
|
||||
Token string `json:"access_token"`
|
||||
}
|
||||
|
||||
func Register(ctx *fiber.Ctx) error {
|
||||
db := database.Db()
|
||||
body := RegisterRequest{}
|
||||
|
||||
if err := ctx.BodyParser(&body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := models.Validate.Struct(body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
user := models.User{ID: database.GetID(), Username: body.Username, Password: body.Password, Email: body.Email}
|
||||
result := db.Create(&user)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
|
||||
token, err := jwt.GenerateJWT(models.Claim{ID: user.ID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return ctx.JSON(LoginResponse{Token: token})
|
||||
}
|
Reference in New Issue
Block a user