/
accesstoken.go
64 lines (52 loc) · 1.25 KB
/
accesstoken.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
package types
import (
"encoding/json"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
type AccessToken string
func (t AccessToken) GetTokenTenantId() (string, error) {
claims, err := t.GetTokenClaims()
if err != nil {
return "", err
}
tenantID, ok := claims["tid"].(string)
if ok {
return tenantID, nil
}
tenantID, ok = claims["tenant"].(string)
if ok {
return tenantID, nil
}
return "", fmt.Errorf("token has no tenant ID")
}
func (t AccessToken) GetTokenClaims() (jwt.MapClaims, error) {
p := &jwt.Parser{}
skipValidations := jwt.WithoutClaimsValidation()
skipValidations(p)
token, _, err := p.ParseUnverified(string(t), jwt.MapClaims{})
if err != nil {
return nil, fmt.Errorf("failed to parse token")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("unexpected claim type from token")
}
return claims, nil
}
func (t AccessToken) GetTokenExp() (time.Time, error) {
claims, err := t.GetTokenClaims()
if err != nil {
return time.Time{}, err
}
switch exp := claims["exp"].(type) {
case float64:
return time.Unix(int64(exp), 0), nil
case json.Number:
timestamp, _ := exp.Int64()
return time.Unix(timestamp, 0), nil
default:
return time.Time{}, fmt.Errorf("failed to parse token experation")
}
}