55 lines
1.5 KiB
Go
55 lines
1.5 KiB
Go
// Filename: internal/middleware/web.go
|
|
package middleware
|
|
|
|
import (
|
|
"gemini-balancer/internal/service"
|
|
"log"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
const (
|
|
AdminSessionCookie = "gemini_admin_session"
|
|
)
|
|
|
|
func SetAdminSessionCookie(c *gin.Context, adminToken string) {
|
|
c.SetCookie(AdminSessionCookie, adminToken, 3600*24*7, "/", "", false, true)
|
|
}
|
|
|
|
func ClearAdminSessionCookie(c *gin.Context) {
|
|
c.SetCookie(AdminSessionCookie, "", -1, "/", "", false, true)
|
|
}
|
|
|
|
func ExtractTokenFromCookie(c *gin.Context) string {
|
|
cookie, err := c.Cookie(AdminSessionCookie)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return cookie
|
|
}
|
|
|
|
func WebAdminAuthMiddleware(authService *service.SecurityService) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
cookie := ExtractTokenFromCookie(c)
|
|
log.Printf("[WebAuth_Guard] Intercepting request for: %s", c.Request.URL.Path)
|
|
log.Printf("[WebAuth_Guard] Found session cookie value: '%s'", cookie)
|
|
authToken, err := authService.AuthenticateToken(cookie)
|
|
if err != nil {
|
|
log.Printf("[WebAuth_Guard] FATAL: AuthenticateToken FAILED. Error: %v. Redirecting to /login.", err)
|
|
} else if !authToken.IsAdmin {
|
|
log.Printf("[WebAuth_Guard] FATAL: Token validated, but IsAdmin is FALSE. Redirecting to /login.")
|
|
} else {
|
|
log.Printf("[WebAuth_Guard] SUCCESS: Token validated and IsAdmin is TRUE. Allowing access.")
|
|
}
|
|
if err != nil || !authToken.IsAdmin {
|
|
ClearAdminSessionCookie(c)
|
|
c.Redirect(http.StatusFound, "/login")
|
|
c.Abort()
|
|
return
|
|
}
|
|
c.Set("adminUser", authToken)
|
|
c.Next()
|
|
}
|
|
}
|