77 lines
2.1 KiB
Go
77 lines
2.1 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
fbauth "firebase.google.com/go/v4/auth"
|
|
"watch-party-backend/internal/auth"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// AuthMiddleware validates Bearer tokens with the provided verifier.
|
|
func AuthMiddleware(verifier auth.TokenVerifier) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
header := c.GetHeader("Authorization")
|
|
if header == "" || !strings.HasPrefix(header, "Bearer ") {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing or invalid authorization header"})
|
|
return
|
|
}
|
|
raw := strings.TrimSpace(strings.TrimPrefix(header, "Bearer"))
|
|
if raw == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
|
|
return
|
|
}
|
|
token, err := verifier.Verify(c.Request.Context(), raw)
|
|
if err != nil {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
c.Set("firebaseToken", token)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RequireAdmin enforces a custom claim "admin": true on the Firebase token.
|
|
func RequireAdmin() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
val, ok := c.Get("firebaseToken")
|
|
if !ok {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
token, ok := val.(*fbauth.Token)
|
|
if !ok {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
if isAdmin, ok := token.Claims["admin"].(bool); !ok || !isAdmin {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// RequireRootUID enforces that the caller's UID matches the configured root admin UID.
|
|
func RequireRootUID(rootUID string) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
val, ok := c.Get("firebaseToken")
|
|
if !ok {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
token, ok := val.(*fbauth.Token)
|
|
if !ok || token.UID == "" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
if token.UID != rootUID {
|
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
|
|
return
|
|
}
|
|
c.Next()
|
|
}
|
|
}
|