2023-06-25 19:32:36 +00:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"owl-blogs/app"
|
2023-07-17 18:44:59 +00:00
|
|
|
"owl-blogs/app/repository"
|
2023-07-09 17:51:49 +00:00
|
|
|
"owl-blogs/render"
|
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-19 18:25:42 +00:00
|
|
|
configRepo repository.ConfigRepository
|
2023-07-08 12:28:15 +00:00
|
|
|
authorService *app.AuthorService
|
2023-06-25 19:32:36 +00:00
|
|
|
}
|
|
|
|
|
2023-07-17 18:44:59 +00:00
|
|
|
func NewLoginHandler(
|
|
|
|
authorService *app.AuthorService,
|
2023-07-19 18:25:42 +00:00
|
|
|
configRepo repository.ConfigRepository,
|
2023-07-17 18:44:59 +00:00
|
|
|
) *LoginHandler {
|
|
|
|
return &LoginHandler{
|
|
|
|
authorService: authorService,
|
|
|
|
configRepo: configRepo,
|
|
|
|
}
|
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)
|
2023-07-19 18:25:42 +00:00
|
|
|
return render.RenderTemplateWithBase(c, getSiteConfig(h.configRepo), "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)
|
|
|
|
|
2023-07-27 19:19:52 +00:00
|
|
|
return c.Redirect("/admin/")
|
2023-07-08 12:28:15 +00:00
|
|
|
|
2023-06-25 19:32:36 +00:00
|
|
|
}
|