- Added FirebaseAuth struct and TokenVerifier interface for verifying Firebase ID tokens. - Introduced FirebaseConfig struct in config to manage Firebase credentials and project ID. - Implemented OAuth handler for Firebase ID token verification in HTTP handlers. - Added middleware for authenticating requests using Firebase tokens. - Updated router to conditionally apply authentication based on configuration. - Created tests for the new authentication middleware. - Added request and response types for Firebase OAuth handling. - Included a sample JSON file for testing purposes.
34 lines
911 B
Go
34 lines
911 B
Go
package httpapi
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"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()
|
|
}
|
|
}
|