-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
62 lines (53 loc) · 1.48 KB
/
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package firebase
import (
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"net/http"
jwt "github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
)
// AuthUserID return firebase auth user id.
func AuthUserID(c *http.Client, r *http.Request, id string) (uid string, err error) {
keyLists := "https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com"
url := "https://securetoken.google.com/"
token, err := request.ParseFromRequestWithClaims(r, request.ArgumentExtractor{"token"}, jwt.StandardClaims{}, func(t *jwt.Token) (interface{}, error) {
res, err := c.Get(keyLists)
if err != nil {
return nil, err
}
defer res.Body.Close()
var keyList map[string]string
if err := json.NewDecoder(res.Body).Decode(keyList); err != nil {
return nil, err
}
kid, ok := t.Header["kid"].(string)
if !ok {
return nil, errors.New("kid is not string")
}
keyString := keyList[kid]
block, _ := pem.Decode([]byte(keyString))
cert, _ := x509.ParseCertificate(block.Bytes)
pubKey := cert.PublicKey
return pubKey, nil
})
if err != nil {
return
}
claims, ok := token.Claims.(jwt.StandardClaims)
if !ok {
err = fmt.Errorf("token[%#v] is something wrong", token)
return
}
if claims.Audience != id {
err = errors.New("firebase project id is not matched")
return
} else if claims.Issuer != fmt.Sprintf(url+"%s", id) {
err = errors.New("firebase project id is not matched")
return
}
uid = claims.Subject
return
}