51 lines
1.4 KiB
Go
51 lines
1.4 KiB
Go
package http
|
|
|
|
import (
|
|
"github.com/aykhans/oh-my-chat/internal/core/port"
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
type AuthHandler struct {
|
|
authService port.AuthService
|
|
validator *validator.Validate
|
|
}
|
|
|
|
func NewAuthHandler(authService port.AuthService, validator *validator.Validate) *AuthHandler {
|
|
return &AuthHandler{authService, validator}
|
|
}
|
|
|
|
type loginRequest struct {
|
|
Username string `json:"username"`
|
|
Email string `json:"email" validate:"email"`
|
|
Password string `json:"password" validate:"required"`
|
|
}
|
|
|
|
func (authHandler *AuthHandler) Login(ctx *fiber.Ctx) error {
|
|
loginBody := new(loginRequest)
|
|
if err := ctx.BodyParser(loginBody); err != nil {
|
|
return invalidRequestBodyResponse(ctx)
|
|
}
|
|
|
|
if err := authHandler.validator.Struct(loginBody); err != nil {
|
|
return validationErrorResponse(ctx, err)
|
|
}
|
|
|
|
loginField := loginBody.Email
|
|
loginFunc := authHandler.authService.LoginByEmail
|
|
if loginField == "" {
|
|
if loginBody.Username == "" {
|
|
return fiber.NewError(fiber.StatusBadRequest, "email or username is required")
|
|
}
|
|
loginField = loginBody.Username
|
|
loginFunc = authHandler.authService.LoginByUsername
|
|
}
|
|
|
|
serviceCtx := ctx.Context()
|
|
token, err := loginFunc(serviceCtx, loginField, loginBody.Password)
|
|
if err != nil {
|
|
return fiber.NewError(fiber.StatusUnauthorized, err.Error())
|
|
}
|
|
return ctx.JSON(fiber.Map{"token": token})
|
|
}
|