- 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.
72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
fbauth "firebase.google.com/go/v4/auth"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type fakeVerifier struct {
|
|
token *fbauth.Token
|
|
err error
|
|
}
|
|
|
|
func (f fakeVerifier) Verify(_ context.Context, _ string) (*fbauth.Token, error) {
|
|
return f.token, f.err
|
|
}
|
|
|
|
func TestAuthMiddleware_MissingHeader(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(AuthMiddleware(fakeVerifier{}))
|
|
r.GET("/", func(c *gin.Context) {})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, w.Code)
|
|
}
|
|
}
|
|
|
|
func TestAuthMiddleware_InvalidToken(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(AuthMiddleware(fakeVerifier{err: errors.New("boom")}))
|
|
r.GET("/", func(c *gin.Context) {})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
req.Header.Set("Authorization", "Bearer invalid")
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusUnauthorized {
|
|
t.Fatalf("expected status %d, got %d", http.StatusUnauthorized, w.Code)
|
|
}
|
|
}
|
|
|
|
func TestAuthMiddleware_Success(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(AuthMiddleware(fakeVerifier{token: &fbauth.Token{UID: "user-123"}}))
|
|
r.GET("/", func(c *gin.Context) {
|
|
c.Status(http.StatusOK)
|
|
})
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
req.Header.Set("Authorization", "Bearer validtoken")
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("expected status %d, got %d", http.StatusOK, w.Code)
|
|
}
|
|
}
|