12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- package admin
- import (
- "database/sql"
- "errors"
- "time"
- "github.com/go-playground/validator/v10"
- "github.com/gofiber/fiber/v2"
- "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
- )
- func LoginHandler(
- envService EnvService,
- authService AuthService,
- userRepository UserRepository,
- ) fiber.Handler {
- return func(fctx *fiber.Ctx) error {
- ctx := fctx.Context()
- var validate = validator.New()
- var hasErrors bool
- form := models.LoginForm{}
- if fctx.Method() == fiber.MethodPost {
- if err := fctx.BodyParser(&form); err != nil {
- return err
- }
- if err := validate.Struct(form); err != nil {
- hasErrors = true
- }
- if !hasErrors {
- user, err := userRepository.Get(ctx, form.Username)
- if err != nil {
- if !errors.Is(err, sql.ErrNoRows) {
- return err
- }
- hasErrors = true
- }
- if !hasErrors {
- if authService.IsCorrectPassword(form.Password, user.Password) {
- token, err := authService.GenerateToken(*user)
- if err != nil {
- return err
- }
- cookie := new(fiber.Cookie)
- cookie.Name = envService.JwtCookie()
- cookie.Value = token
- cookie.Expires = time.Now().Add(envService.JwtLifeTime() * time.Second)
- fctx.Cookie(cookie)
- return fctx.Redirect("/admin")
- }
- hasErrors = true
- }
- }
- }
- return fctx.Render("admin/login", fiber.Map{
- "form": form,
- "hasErrors": hasErrors,
- })
- }
- }
- func LogoutHandler(
- envService EnvService,
- ) fiber.Handler {
- return func(fctx *fiber.Ctx) error {
- cookie := new(fiber.Cookie)
- cookie.Name = envService.JwtCookie()
- cookie.Expires = time.Now().Add(-1 * time.Second)
- fctx.Cookie(cookie)
- return fctx.Redirect("/admin/login")
- }
- }
|