fix: enforce authentication by redirecting unauthenticated users to login
This commit is contained in:
@@ -2,19 +2,34 @@ package middleware
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"mal/internal/domain"
|
"mal/internal/domain"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func AuthMiddleware(svc domain.AuthService) gin.HandlerFunc {
|
func AuthMiddleware(svc domain.AuthService) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
sessionID, err := c.Cookie("session_id")
|
// Allow access to login and logout endpoints without authentication
|
||||||
if err == nil {
|
if c.Request.URL.Path == "/login" || c.Request.URL.Path == "/logout" {
|
||||||
user, err := svc.ValidateSession(c.Request.Context(), sessionID)
|
c.Next()
|
||||||
if err == nil {
|
return
|
||||||
c.Set("User", user)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
sessionID, err := c.Cookie("session_id")
|
||||||
|
if err != nil {
|
||||||
|
c.Redirect(http.StatusSeeOther, "/login")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := svc.ValidateSession(c.Request.Context(), sessionID)
|
||||||
|
if err != nil {
|
||||||
|
c.Redirect(http.StatusSeeOther, "/login")
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Set("User", user)
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user