-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase.go
86 lines (75 loc) · 2.53 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package auth
import (
"context"
"net/http"
"strings"
firebase "firebase.google.com/go"
firebaseauth "firebase.google.com/go/auth"
"github.com/TosinShada/stellar-core/support/errors"
"github.com/TosinShada/stellar-core/support/http/httpauthz"
"github.com/TosinShada/stellar-core/support/log"
"google.golang.org/api/option"
)
type FirebaseTokenVerifier interface {
Verify(r *http.Request) (*firebaseauth.Token, bool)
}
type FirebaseTokenVerifierFunc func(r *http.Request) (*firebaseauth.Token, bool)
func (v FirebaseTokenVerifierFunc) Verify(r *http.Request) (*firebaseauth.Token, bool) {
return v(r)
}
func FirebaseMiddleware(v FirebaseTokenVerifier) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if token, ok := v.Verify(r); ok {
ctx := r.Context()
auth, _ := FromContext(ctx)
auth.PhoneNumber, _ = token.Claims["phone_number"].(string)
if emailVerified, _ := token.Claims["email_verified"].(bool); emailVerified {
auth.Email, _ = token.Claims["email"].(string)
}
authTypes := []string{}
if auth.PhoneNumber != "" {
authTypes = append(authTypes, "phone_number")
}
if auth.Email != "" {
authTypes = append(authTypes, "email")
}
log.Ctx(ctx).
WithField("auth_types", strings.Join(authTypes, ", ")).
Info("Firebase JWT verified.")
ctx = NewContext(ctx, auth)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
}
func NewFirebaseAuthClient(firebaseProjectID string) (*firebaseauth.Client, error) {
credentialsJSON := `{"type":"service_account","project_id":"` + firebaseProjectID + `"}`
firebaseCredentials := option.WithCredentialsJSON([]byte(credentialsJSON))
firebaseApp, err := firebase.NewApp(context.Background(), nil, firebaseCredentials)
if err != nil {
return nil, errors.Wrap(err, "instantiating firebase app")
}
firebaseAuthClient, err := firebaseApp.Auth(context.Background())
if err != nil {
return nil, errors.Wrap(err, "instantiating firebase auth client")
}
return firebaseAuthClient, nil
}
type FirebaseTokenVerifierLive struct {
AuthClient *firebaseauth.Client
}
func (v FirebaseTokenVerifierLive) Verify(r *http.Request) (*firebaseauth.Token, bool) {
ctx := r.Context()
authHeader := r.Header.Get("Authorization")
tokenEncoded := httpauthz.ParseBearerToken(authHeader)
if tokenEncoded == "" {
return nil, false
}
token, err := v.AuthClient.VerifyIDToken(ctx, tokenEncoded)
if err != nil {
return nil, false
}
return token, true
}