-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmiddleware.go
69 lines (59 loc) · 2.07 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package validateiap
import (
"context"
"log"
"net/http"
"github.com/a1comms/gcp-iap-auth/jwt"
"github.com/urfave/negroni"
)
type emailValFunc func(context.Context, string) (bool, error)
var (
ValidateIAPMiddleware negroni.HandlerFunc = GetValidateIAPMiddleware(emailNotEmpty)
ValidateIAPAppEngineMiddleware negroni.HandlerFunc = GetValidateIAPAppEngineMiddleware(emailNotEmpty)
)
func GetValidateIAPMiddleware(emailVal emailValFunc) negroni.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if claims, err := jwt.RequestClaims(r, cfg); err != nil {
log.Printf("ValidateIAP: Failed to validate request claims: %s", err)
} else {
if ok, err := emailVal(r.Context(), claims.Email); err != nil {
log.Printf("ValidateIAP: Failed to call email validation function: %s", err)
} else if ok {
ctx, _ := setUserEmailToContext(r.Context(), claims.Email)
ctx, _ = setGoogleClaimToContext(ctx, claims.Google)
next(w, r.WithContext(ctx))
return
}
}
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
}
func GetValidateIAPAppEngineMiddleware(emailVal emailValFunc) negroni.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if val := r.Header.Get("X-AppEngine-Cron"); val != "" {
next(w, r)
return
} else if val := r.Header.Get("X-AppEngine-QueueName"); val != "" {
next(w, r)
return
} else if claims, err := jwt.RequestClaims(r, cfg); err == nil {
if ok, err := emailVal(r.Context(), claims.Email); err != nil {
log.Printf("ValidateIAP: Failed to call email validation function: %s", err)
} else if ok {
ctx, _ := setUserEmailToContext(r.Context(), claims.Email)
ctx, _ = setGoogleClaimToContext(ctx, claims.Google)
next(w, r.WithContext(ctx))
return
}
} else {
log.Printf("ValidateIAP: Failed to validate request claims: %s", err)
}
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}
}
func emailNotEmpty(ctx context.Context, email string) (bool, error) {
if email != "" {
return true, nil
}
return false, nil
}