-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathauth.go
38 lines (34 loc) · 941 Bytes
/
auth.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
package main
import (
"encoding/json"
"log"
"net/http"
"time"
"github.com/imkira/gcp-iap-auth/jwt"
)
type userIdentity struct {
Subject string `json:"sub,omitempty"`
Email string `json:"email,omitempty"`
}
func authHandler(res http.ResponseWriter, req *http.Request) {
claims, err := jwt.RequestClaims(req, cfg)
if err != nil {
if claims == nil || len(claims.Email) == 0 {
log.Printf("Failed to authenticate (%v)\n", err)
} else {
log.Printf("Failed to authenticate %q (%v)\n", claims.Email, err)
}
res.WriteHeader(http.StatusUnauthorized)
return
}
user := &userIdentity{
Subject: claims.Subject,
Email: claims.Email,
}
res.Header().Add("email", user.Email)
res.Header().Add("subject", user.Subject)
expiresAt := time.Unix(claims.ExpiresAt, 0).UTC()
log.Printf("Authenticated %q (token expires at %v)\n", user.Email, expiresAt)
res.WriteHeader(http.StatusOK)
json.NewEncoder(res).Encode(user)
}