szuntis-backend/router/auth.go
KoCoder 1e41dd833f
Some checks failed
build-docker-imge / Build the docker container (push) Failing after 2m24s
Experiment with Authentication and Websockets
2024-08-27 18:20:17 +02:00

71 lines
1.6 KiB
Go

package router
import (
"errors"
"git.kocoder.xyz/kocoded/szuntis-backend/middleware"
"git.kocoder.xyz/kocoded/szuntis-backend/repository"
"github.com/gofiber/fiber/v2"
)
type AuthRouter struct {
authRepo repository.AuthRepository
}
func NewAuthRouter(authRepo repository.AuthRepository, authMiddleware middleware.AuthMiddleware, auth fiber.Router) error {
router := &AuthRouter{authRepo: authRepo}
auth.Post("/login", router.HandleLogin)
auth.Post("/register", router.HandleRegister)
auth.Get("/username", authMiddleware.IsAuthenticated, router.GetName)
return nil
}
func (ar AuthRouter) GetName(ctx *fiber.Ctx) error {
user, ok := ctx.Locals("user").(repository.User)
if !ok {
return ctx.SendStatus(fiber.StatusUnauthorized)
}
return ctx.SendString(user.Username)
}
func (ar AuthRouter) HandleLogin(ctx *fiber.Ctx) error {
params := repository.LoginParams{}
if err := ctx.BodyParser(&params); err != nil {
return err
}
token, err := ar.authRepo.Login(ctx.Context(), &params)
if err != nil {
return err
}
cookie := &fiber.Cookie{
Name: "session-token",
Value: token.String(),
MaxAge: 5,
}
ctx.Cookie(cookie)
return ctx.SendString("Success!!!!!")
}
func (ar AuthRouter) HandleRegister(ctx *fiber.Ctx) error {
params := repository.RegisterParams{}
if err := ctx.BodyParser(&params); err != nil {
return err
}
ok, err := ar.authRepo.Register(ctx.Context(), &params)
if err != nil {
return err
}
if ok {
return ctx.SendString("User registered successfully, please check your inbox & proceed to login.")
}
return errors.New("")
}