auth.go 1.8 KB

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