owl-blogs/web/middleware/auth.go

51 lines
952 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
}
2023-07-25 19:31:03 +00:00
type UserMiddleware struct {
authorService *app.AuthorService
}
2023-07-08 11:28:06 +00:00
func NewAuthMiddleware(authorService *app.AuthorService) *AuthMiddleware {
return &AuthMiddleware{authorService: authorService}
}
2023-07-25 19:31:03 +00:00
func NewUserMiddleware(authorService *app.AuthorService) *UserMiddleware {
return &UserMiddleware{authorService: authorService}
}
2023-07-08 11:28:06 +00:00
func (m *AuthMiddleware) Handle(c *fiber.Ctx) error {
2023-07-25 19:31:03 +00:00
if c.Locals("author") == nil {
return c.Redirect("/auth/login")
}
return c.Next()
}
func (m *UserMiddleware) Handle(c *fiber.Ctx) error {
2023-07-08 11:28:06 +00:00
// get token from cookie
token := c.Cookies("token")
if token == "" {
2023-07-25 19:31:03 +00:00
return c.Next()
2023-07-08 11:28:06 +00:00
}
// 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 {
2023-07-25 19:31:03 +00:00
return c.Next()
2023-07-08 11:28:06 +00:00
}
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()
}