owl-blogs/web/login_handler.go

49 lines
982 B
Go
Raw Normal View History

2023-06-25 19:32:36 +00:00
package web
import (
"owl-blogs/app"
2023-07-08 12:28:15 +00:00
"time"
2023-06-25 19:32:36 +00:00
"github.com/gofiber/fiber/v2"
)
type LoginHandler struct {
2023-07-08 12:28:15 +00:00
authorService *app.AuthorService
2023-06-25 19:32:36 +00:00
}
2023-07-08 12:28:15 +00:00
func NewLoginHandler(authorService *app.AuthorService) *LoginHandler {
return &LoginHandler{authorService: authorService}
2023-06-25 19:32:36 +00:00
}
func (h *LoginHandler) HandleGet(c *fiber.Ctx) error {
2023-07-08 12:28:15 +00:00
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
return RenderTemplate(c, "views/login", nil)
2023-06-25 19:32:36 +00:00
}
func (h *LoginHandler) HandlePost(c *fiber.Ctx) error {
2023-07-08 12:28:15 +00:00
c.Set(fiber.HeaderContentType, fiber.MIMETextHTML)
name := c.FormValue("name")
password := c.FormValue("password")
valid := h.authorService.Authenticate(name, password)
if !valid {
return c.Redirect("/auth/login")
}
token, err := h.authorService.CreateToken(name)
if err != nil {
return err
}
cookie := fiber.Cookie{
Name: "token",
Value: token,
Expires: time.Now().Add(30 * 24 * time.Hour),
HTTPOnly: true,
}
c.Cookie(&cookie)
return c.Redirect("/editor/")
2023-06-25 19:32:36 +00:00
}