owl-blogs/web/middleware/auth.go

35 lines
643 B
Go
Raw Normal View History

2023-07-08 11:28:06 +00:00
package middleware
import (
"owl-blogs/app"
"github.com/gofiber/fiber/v2"
)
type AuthMiddleware struct {
authorService *app.AuthorService
}
func NewAuthMiddleware(authorService *app.AuthorService) *AuthMiddleware {
return &AuthMiddleware{authorService: authorService}
}
func (m *AuthMiddleware) Handle(c *fiber.Ctx) error {
// get token from cookie
token := c.Cookies("token")
if token == "" {
return c.Redirect("/auth/login")
}
// check token
2023-07-13 19:55:08 +00:00
valid, name := m.authorService.ValidateToken(token)
2023-07-08 11:28:06 +00:00
if !valid {
return c.Redirect("/auth/login")
}
2023-07-13 19:55:08 +00:00
// set author name to context
c.Locals("author", name)
2023-07-08 11:28:06 +00:00
return c.Next()
}