-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathauth0.go
70 lines (55 loc) · 1.3 KB
/
auth0.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"go.uber.org/zap"
)
type auth0Authenticator struct {
logger *zap.Logger
domain string
client *http.Client
tokens map[string]string
}
func (a *auth0Authenticator) Validate(ctx context.Context, token string) (string, error) {
a.logger.Debug("validate",
zap.String("token", token),
)
if userid, found := a.tokens[token]; found {
return userid, nil
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://%s/userinfo", a.domain), nil)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := a.client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", nil
}
contentType := resp.Header.Get("content-type")
if !strings.Contains(contentType, "application/json") {
return "", errors.New("content not json")
}
var respPayload struct {
Sub string `json:"sub"`
Email string `json:"email"`
}
err = json.NewDecoder(resp.Body).Decode(&respPayload)
if err != nil {
return "", err
}
a.logger.Info("token validated",
zap.String("userid", respPayload.Sub),
zap.String("email", respPayload.Email),
)
a.tokens[token] = respPayload.Sub
return respPayload.Sub, nil
}