Nik Afiq 8a549504a4 feat(auth): implement Firebase authentication and token verification
- 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.
2025-12-10 19:05:11 +09:00

49 lines
1.3 KiB
Go

package auth
import (
"context"
"errors"
"fmt"
firebase "firebase.google.com/go/v4"
fbauth "firebase.google.com/go/v4/auth"
"google.golang.org/api/option"
"watch-party-backend/internal/config"
)
// TokenVerifier hides Firebase client behind a small interface for testing.
type TokenVerifier interface {
Verify(ctx context.Context, token string) (*fbauth.Token, error)
}
// FirebaseAuth verifies Firebase ID tokens.
type FirebaseAuth struct {
client *fbauth.Client
}
// NewFirebaseAuth builds the Firebase client from config.
func NewFirebaseAuth(ctx context.Context, cfg config.FirebaseConfig) (*FirebaseAuth, error) {
creds, err := cfg.CredentialsBytes()
if err != nil {
return nil, err
}
if len(creds) == 0 {
return nil, errors.New("firebase credentials empty")
}
app, err := firebase.NewApp(ctx, &firebase.Config{ProjectID: cfg.ProjectID}, option.WithCredentialsJSON(creds))
if err != nil {
return nil, fmt.Errorf("init firebase app: %w", err)
}
client, err := app.Auth(ctx)
if err != nil {
return nil, fmt.Errorf("init firebase auth client: %w", err)
}
return &FirebaseAuth{client: client}, nil
}
// Verify checks a Firebase ID token and returns its claims.
func (f *FirebaseAuth) Verify(ctx context.Context, token string) (*fbauth.Token, error) {
return f.client.VerifyIDToken(ctx, token)
}