-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
49 lines (39 loc) · 1.01 KB
/
middleware.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
package middleware
import (
"context"
"net/http"
"firebase.google.com/go/auth"
)
type Authenticator interface {
TokenVerifier(next http.Handler) http.Handler
}
type authMiddleware struct {
AuthClient *auth.Client
}
func NewGcpAuthMiddleware(client *auth.Client) *authMiddleware {
return &authMiddleware{
AuthClient: client,
}
}
func (a authMiddleware) TokenVerifier(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
bearerToken := a.tokenFromHeader(r)
if bearerToken == "" {
http.Error(w, "no token presented", http.StatusUnauthorized)
return
}
token, err := a.AuthClient.VerifyIDToken(ctx, bearerToken)
if err != nil {
http.Error(w, "unable to verify token", http.StatusUnauthorized)
return
}
ctx = context.WithValue(ctx, accountContextKey, Account{
UUID: token.UID,
Email: token.Claims["email"].(string),
TenantId: token.Firebase.Tenant,
})
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}