package admin import ( "database/sql" "time" "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/interfaces" "git.dmitriygnatenko.ru/dima/dmitriygnatenko-v2/internal/models" "github.com/go-playground/validator/v10" "github.com/gofiber/fiber/v2" ) func LoginHandler(sp interfaces.ServiceProvider) 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 := sp.GetUserRepository().Get(ctx, form.Username) if err != nil { if err != sql.ErrNoRows { return err } hasErrors = true } if !hasErrors { if sp.GetAuthService().IsCorrectPassword(form.Password, user.Password) { token, err := sp.GetAuthService().GenerateToken(*user) if err != nil { return err } cookie := new(fiber.Cookie) cookie.Name = sp.GetEnvService().GetJWTCookie() cookie.Value = token cookie.Expires = time.Now().Add(time.Duration(sp.GetEnvService().GetJWTLifetime()) * time.Second) fctx.Cookie(cookie) return fctx.Redirect("/admin") } hasErrors = true } } } return fctx.Render("admin/login", fiber.Map{ "form": form, "hasErrors": hasErrors, }) } } func LogoutHandler(sp interfaces.ServiceProvider) fiber.Handler { return func(fctx *fiber.Ctx) error { cookie := new(fiber.Cookie) cookie.Name = sp.GetEnvService().GetJWTCookie() cookie.Expires = time.Now().Add(-1 * time.Second) fctx.Cookie(cookie) return fctx.Redirect("/admin/login") } }