-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.go
70 lines (55 loc) · 1.77 KB
/
token.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 auth
import (
"crypto/subtle"
"encoding/base64"
"errors"
"strings"
"github.com/nano-interactive/go-utils/v2"
)
var (
ErrInvalidToken = errors.New("invalid token")
ErrInvalidAuthType = errors.New("invalid authorization type")
)
func ExtractTokenFromHeader(header string, authType AuthType) (string, error) {
components := strings.SplitN(header, " ", 2)
if len(components) < 2 {
return "", ErrInvalidToken
}
headerAuthType := components[0]
headerToken := components[1]
if !strings.EqualFold(headerAuthType, string(authType)) {
return "", ErrInvalidAuthType
}
return headerToken, nil
}
func ParseTokenFromHeader(header string, authType AuthType) ([]byte, error) {
headerToken, err := ExtractTokenFromHeader(header, authType)
if err != nil {
return nil, err
}
var tokenBytes [32]byte
if base64.RawURLEncoding.DecodedLen(len(headerToken)) != 32 {
return nil, ErrInvalidToken
}
_, err = base64.RawURLEncoding.Decode(tokenBytes[:], utils.UnsafeBytes(headerToken))
if err != nil {
return nil, ErrInvalidToken
}
return tokenBytes[:], nil
}
func CompareTokens(token1 []byte, token2 []byte) int {
// Now, you may wonder why we need this function if all it does
// is call a library function. Well my dear reader, do you think
// that everyone will remember to compare tokens in constant time?
//
// Correct, neither do I.
return subtle.ConstantTimeCompare(token1, token2)
}
func CompareTokenStrings(token1 string, token2 string) int {
// Now, you may wonder why we need this function if all it does
// is call a library function. Well my dear reader, do you think
// that everyone will remember to compare tokens in constant time?
//
// Correct, neither do I.
return subtle.ConstantTimeCompare(utils.UnsafeBytes(token1), utils.UnsafeBytes(token2))
}