-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.go
55 lines (44 loc) · 1.65 KB
/
firebase.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package auth
import (
"context"
"fmt"
"time"
firebase "firebase.google.com/go"
auth "firebase.google.com/go/auth"
"google.golang.org/api/option"
)
// FirebaseAuthenticator is a authenticator for Firebase.
type FirebaseAuthenticator struct {
client *auth.Client
}
func NewFirebaseAuthenticator(cred []byte) (*FirebaseAuthenticator, error) {
app, err := firebase.NewApp(context.Background(), nil, option.WithCredentialsJSON(cred))
if err != nil {
return nil, fmt.Errorf("firebase app init failed: %w", err)
}
client, err := app.Auth(context.Background())
if err != nil {
return nil, fmt.Errorf("firebase auth init failed: %w", err)
}
return &FirebaseAuthenticator{client}, nil
}
// Authenticate returns a new context with the user ID if the session is valid.
func (f *FirebaseAuthenticator) Authenticate(ctx context.Context, session string) (context.Context, error) {
tk, err := f.client.VerifySessionCookieAndCheckRevoked(ctx, session)
if err != nil {
return nil, fmt.Errorf("verify session cookie: %w", err)
}
return SetUserID(ctx, UserID(tk.UID)), nil
}
// VerifyIDToken returns a new session if the ID token is valid.
func (f *FirebaseAuthenticator) SessionCookie(ctx context.Context, idToken string) (string, error) {
return f.client.SessionCookie(ctx, idToken, time.Hour*24*14)
}
// DeleteUser deletes the user from Firebase.
func (f *FirebaseAuthenticator) DeleteUser(ctx context.Context, uid UserID) error {
return f.client.DeleteUser(ctx, string(uid))
}
// GetUser returns the user from Firebase.
func (f *FirebaseAuthenticator) GetUser(ctx context.Context, uid UserID) (*auth.UserRecord, error) {
return f.client.GetUser(ctx, string(uid))
}