This repository has been archived by the owner on Nov 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
tokens.go
108 lines (86 loc) · 2.19 KB
/
tokens.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package tugboat
import (
"errors"
"github.com/dgrijalva/jwt-go"
)
// ErrInvalidToken is returned when the token provided is not valid.
var ErrInvalidToken = errors.New("invalid token")
// Token represents an authentication token for external providers.
type Token struct {
Provider string
Token string
}
// tokensService represents a service for creating and finding provider tokens.
type tokensService interface {
TokensCreate(*Token) error
TokensFind(id string) (*Token, error)
}
func newTokensService(secret []byte) tokensService {
return &jwtTokensService{
secret: secret,
}
}
// jwtTokensService is a tokensService implementation backed by jwt.
type jwtTokensService struct {
secret []byte
}
func (s *jwtTokensService) TokensCreate(token *Token) error {
signed, err := signToken(s.secret, token)
if err != nil {
return err
}
token.Token = signed
return nil
}
func (s *jwtTokensService) TokensFind(token string) (*Token, error) {
t, err := parseToken(s.secret, token)
if err != nil {
switch err.(type) {
case *jwt.ValidationError:
return t, ErrInvalidToken
default:
return t, err
}
}
if t != nil {
t.Token = token
}
return t, nil
}
// signToken jwt signs the token and adds the signature to the Token field.
func signToken(secret []byte, token *Token) (string, error) {
t := tokenToJWT(token)
return t.SignedString(secret)
}
// parseToken parses a string token, verifies it, and returns an Token
// instance.
func parseToken(secret []byte, token string) (*Token, error) {
t, err := jwtParse(secret, token)
if err != nil {
return nil, err
}
if !t.Valid {
return nil, nil
}
return jwtToToken(t)
}
func tokenToJWT(token *Token) *jwt.Token {
t := jwt.New(jwt.SigningMethodHS256)
t.Claims["Provider"] = token.Provider
return t
}
// jwtToToken maps a jwt.Token to an AccessToken.
func jwtToToken(t *jwt.Token) (*Token, error) {
var token Token
if p, ok := t.Claims["Provider"].(string); ok {
token.Provider = p
} else {
return &token, errors.New("missing provider")
}
return &token, nil
}
func jwtParse(secret []byte, token string) (*jwt.Token, error) {
return jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
return secret, nil
})
}