firebase

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 24, 2025 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetTokenFromContext

func GetTokenFromContext(ctx context.Context) (*auth.Token, error)

GetTokenFromContext extracts the token from the context

func GetTokenFromRequest

func GetTokenFromRequest(r *http.Request) (string, error)

GetTokenFromRequest extracts the ID token from the Authorization header

func GetUIDFromContext

func GetUIDFromContext(ctx context.Context) (string, error)

GetUIDFromContext extracts the user ID from the context

func RequireAuth

func RequireAuth(fa *FirebaseAuth, next http.HandlerFunc) http.HandlerFunc

RequireAuth is a utility function to be used with http handlers as middleware Example usage:

http.HandleFunc("/protected", RequireAuth(firebaseAuth, protectedHandlerFunc))

Types

type BaseUser

type BaseUser[T any] struct {
	// Core identifiers
	ID          string `json:"id"`    // Database primary key/ID
	Email       string `json:"email"` // User's email address
	PhoneNumber string `json:"phoneNumber,omitempty"`

	// Common user metadata
	DisplayName string     `json:"displayName,omitempty"`
	PhotoURL    string     `json:"photoUrl,omitempty"`
	CreatedAt   time.Time  `json:"createdAt"`
	UpdatedAt   time.Time  `json:"updatedAt"`
	LastLoginAt *time.Time `json:"lastLoginAt,omitempty"`
	Disabled    bool       `json:"disabled"`

	// Authentication properties
	EmailVerified bool                   `json:"emailVerified"`
	PhoneVerified bool                   `json:"phoneVerified"`
	Claims        map[string]interface{} `json:"claims,omitempty"`

	// Application-specific user data
	Data T `json:"data"`
}

BaseUser contains universal user properties across any application

func FromFirebaseUser

func FromFirebaseUser[T any](user *auth.UserRecord, data T) *BaseUser[T]

FromFirebaseUser converts a Firebase UserRecord to a BaseUser

func (*BaseUser[T]) GetClaim

func (u *BaseUser[T]) GetClaim(key string) (interface{}, bool)

GetClaim retrieves a specific claim value with type safety

func (*BaseUser[T]) HasRole

func (u *BaseUser[T]) HasRole(role string) bool

HasRole checks if a user has a specific role

func (*BaseUser[T]) ToFirebaseUpdate

func (u *BaseUser[T]) ToFirebaseUpdate() *auth.UserToUpdate

ToFirebaseUpdate converts a BaseUser to auth.UserToUpdate for Firebase updates

type FirebaseAuth

type FirebaseAuth struct {
	App  *firebase.App
	Auth *auth.Client
}

FirebaseAuth holds the Firebase client and auth client instances

func InitFirebase

func InitFirebase(ctx context.Context, serviceAccountKeyPath string) (*FirebaseAuth, error)

InitFirebase initializes Firebase with the provided service account key file Example usage:

ctx := context.Background()
firebaseAuth, err := InitFirebase(ctx, "path/to/service-account.json")
if err != nil {
    log.Fatalf("Failed to initialize Firebase: %v", err)
}

func InitFirebaseWithCredentials

func InitFirebaseWithCredentials(ctx context.Context, credentialsJSON []byte) (*FirebaseAuth, error)

InitFirebaseWithCredentials initializes Firebase with a Google credentials JSON string

func (*FirebaseAuth) AuthMiddleware

func (fa *FirebaseAuth) AuthMiddleware(next http.Handler) http.Handler

AuthMiddleware is a middleware to verify Firebase authentication tokens Example usage with standard http:

http.Handle("/protected", firebaseAuth.AuthMiddleware(protectedHandler))

Example with Gorilla mux:

router.Handle("/protected", firebaseAuth.AuthMiddleware(protectedHandler))

func (*FirebaseAuth) CreateUser

func (fa *FirebaseAuth) CreateUser(ctx context.Context, params *auth.UserToCreate) (string, error)

CreateUser creates a new Firebase user

func (*FirebaseAuth) DeleteUser

func (fa *FirebaseAuth) DeleteUser(ctx context.Context, uid string) error

DeleteUser deletes a Firebase user

func (*FirebaseAuth) GetUserByEmail

func (fa *FirebaseAuth) GetUserByEmail(ctx context.Context, email string) (*auth.UserRecord, error)

GetUserByEmail gets a user by their email address

func (*FirebaseAuth) GetUserByPhoneNumber added in v0.3.0

func (fa *FirebaseAuth) GetUserByPhoneNumber(ctx context.Context, phone string) (*auth.UserRecord, error)

func (*FirebaseAuth) GetUserByUID

func (fa *FirebaseAuth) GetUserByUID(ctx context.Context, uid string) (*auth.UserRecord, error)

GetUserByUID gets a user by their Firebase UID

func (*FirebaseAuth) RevokeTokens

func (fa *FirebaseAuth) RevokeTokens(ctx context.Context, uid string) error

RevokeTokens revokes all refresh tokens for a user

func (*FirebaseAuth) SetCustomClaims

func (fa *FirebaseAuth) SetCustomClaims(ctx context.Context, uid string, claims map[string]interface{}) error

SetCustomClaims sets custom claims on a user's Firebase account These claims will be included in the user's ID token when they sign in Example usage:

claims := map[string]interface{}{
    "admin": true,
    "accessLevel": 5,
}
err := firebaseAuth.SetCustomClaims(ctx, uid, claims)

func (*FirebaseAuth) UpdateUser

func (fa *FirebaseAuth) UpdateUser(ctx context.Context, uid string, params *auth.UserToUpdate) error

UpdateUser updates an existing Firebase user

func (*FirebaseAuth) VerifyIDToken

func (fa *FirebaseAuth) VerifyIDToken(ctx context.Context, idToken string) (*auth.Token, error)

VerifyIDToken verifies the ID token and returns the Firebase token Example usage:

token, err := firebaseAuth.VerifyIDToken(ctx, idToken)
if err != nil {
    http.Error(w, "Unauthorized", http.StatusUnauthorized)
    return
}
// Use token.UID to identify the user

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL