/
token.go
63 lines (53 loc) · 1.46 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
package manager
import (
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func init() {
// Assert that a cryptographically secure PRNG is available.
buf := make([]byte, 1)
_, err := io.ReadFull(rand.Reader, buf)
if err != nil {
panic(fmt.Sprintf("crypto/rand is unavailable: Read() failed with %#v", err))
}
}
// Token struct hold the token
type Token struct {
Value []byte
}
// NewToken creates a new token
func NewToken(n int) (*Token, error) {
token, err := GenerateRandomBytes(n)
if err != nil {
return nil, fmt.Errorf("Token generation error: %v", err)
}
return &Token{token}, nil
}
// ToURLSafeString returns a base64 encoded URL safe random string
func (t *Token) ToURLSafeString() string {
return base64.URLEncoding.EncodeToString(t.Value)
}
// ToString converts and returns the string representation
// of the generated token
func (t *Token) ToString() string {
return string(t.Value)
}
// Compare compares this token with another token
func (t *Token) Compare(anotherToken string) bool {
return t.ToURLSafeString() == anotherToken
}
// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return nil, err
}
return b, nil
}