package admin import ( "database/sql" "errors" "time" "git.dmitriygnatenko.ru/dima/go-common/logger" "github.com/go-playground/validator/v10" "github.com/gofiber/fiber/v2" "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models" ) func LoginHandler( configService ConfigService, 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 { logger.Info(ctx, err.Error()) 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) { logger.Error(ctx, err.Error()) return err } hasErrors = true } if !hasErrors { if authService.IsCorrectPassword(form.Password, user.Password) { token, err := authService.GenerateToken(*user) if err != nil { logger.Error(ctx, err.Error()) return err } cookie := new(fiber.Cookie) cookie.Name = configService.JWTCookie() cookie.Value = token cookie.Expires = time.Now().Add(configService.JWTLifeTime()) fctx.Cookie(cookie) return fctx.Redirect("/admin") } hasErrors = true } } } return fctx.Render("admin/login", fiber.Map{ "form": form, "hasErrors": hasErrors, }) } } func LogoutHandler( configService ConfigService, ) fiber.Handler { return func(fctx *fiber.Ctx) error { cookie := new(fiber.Cookie) cookie.Name = configService.JWTCookie() cookie.Expires = time.Now().Add(-1 * time.Second) fctx.Cookie(cookie) return fctx.Redirect("/admin/login") } }