-
Notifications
You must be signed in to change notification settings - Fork 5
/
token.go
55 lines (44 loc) · 1.4 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
package mnemosyne
import (
"crypto/rand"
"encoding/hex"
"io"
"golang.org/x/crypto/sha3"
"golang.org/x/net/context"
)
const (
// AccessTokenMetadataKey is used by Mnemosyne to retrieve session token from gRPC metadata object.
AccessTokenMetadataKey = "authorization"
)
type key struct{}
var accessTokenContextKey = key{}
// NewAccessTokenContext returns a new Context that carries token value.
func NewAccessTokenContext(ctx context.Context, at string) context.Context {
return context.WithValue(ctx, accessTokenContextKey, at)
}
// AccessTokenFromContext returns the token value stored in context, if any.
func AccessTokenFromContext(ctx context.Context) (string, bool) {
at, ok := ctx.Value(accessTokenContextKey).(string)
return at, ok
}
// RandomAccessToken generate Access Token with given key and generated hash of length 64.
func RandomAccessToken() (string, error) {
buf, err := generateRandomBytes(128)
if err != nil {
return "", err
}
// A hash needs to be 64 bytes long to have 256-bit collision resistance.
hash := make([]byte, 64)
// Compute a 64-byte hash of buf and put it in h.
sha3.ShakeSum256(hash, buf)
hash2 := make([]byte, hex.EncodedLen(len(hash)))
hex.Encode(hash2, hash)
return string(hash2), nil
}
func generateRandomBytes(length int) ([]byte, error) {
k := make([]byte, length)
if _, err := io.ReadFull(rand.Reader, k); err != nil {
return nil, err
}
return k, nil
}