auth.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package admin
  2. import (
  3. "database/sql"
  4. "errors"
  5. "time"
  6. "github.com/go-playground/validator/v10"
  7. "github.com/gofiber/fiber/v2"
  8. "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models"
  9. )
  10. func LoginHandler(
  11. envService EnvService,
  12. authService AuthService,
  13. userRepository UserRepository,
  14. ) fiber.Handler {
  15. return func(fctx *fiber.Ctx) error {
  16. ctx := fctx.Context()
  17. var validate = validator.New()
  18. var hasErrors bool
  19. form := models.LoginForm{}
  20. if fctx.Method() == fiber.MethodPost {
  21. if err := fctx.BodyParser(&form); err != nil {
  22. return err
  23. }
  24. if err := validate.Struct(form); err != nil {
  25. hasErrors = true
  26. }
  27. if !hasErrors {
  28. user, err := userRepository.Get(ctx, form.Username)
  29. if err != nil {
  30. if !errors.Is(err, sql.ErrNoRows) {
  31. return err
  32. }
  33. hasErrors = true
  34. }
  35. if !hasErrors {
  36. if authService.IsCorrectPassword(form.Password, user.Password) {
  37. token, err := authService.GenerateToken(*user)
  38. if err != nil {
  39. return err
  40. }
  41. cookie := new(fiber.Cookie)
  42. cookie.Name = envService.JWTCookie()
  43. cookie.Value = token
  44. cookie.Expires = time.Now().Add(time.Duration(envService.JWTLifetime()) * time.Second)
  45. fctx.Cookie(cookie)
  46. return fctx.Redirect("/admin")
  47. }
  48. hasErrors = true
  49. }
  50. }
  51. }
  52. return fctx.Render("admin/login", fiber.Map{
  53. "form": form,
  54. "hasErrors": hasErrors,
  55. })
  56. }
  57. }
  58. func LogoutHandler(
  59. envService EnvService,
  60. ) fiber.Handler {
  61. return func(fctx *fiber.Ctx) error {
  62. cookie := new(fiber.Cookie)
  63. cookie.Name = envService.JWTCookie()
  64. cookie.Expires = time.Now().Add(-1 * time.Second)
  65. fctx.Cookie(cookie)
  66. return fctx.Redirect("/admin/login")
  67. }
  68. }