auth.go 1.8 KB

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