25 lines
709 B
Go
25 lines
709 B
Go
package auth
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"crypto/rand"
|
||
|
|
"crypto/sha256"
|
||
|
|
"encoding/base64"
|
||
|
|
)
|
||
|
|
|
||
|
|
// NewSessionToken creates a random bearer token and its SHA-256 storage hash.
|
||
|
|
// Store only the hash; return the raw token to the caller that sets the cookie
|
||
|
|
// or authorization header.
|
||
|
|
func NewSessionToken() (raw string, hash string, err error) {
|
||
|
|
bytes := make([]byte, 32)
|
||
|
|
if _, err := rand.Read(bytes); err != nil {
|
||
|
|
return "", "", err
|
||
|
|
}
|
||
|
|
raw = base64.RawURLEncoding.EncodeToString(bytes)
|
||
|
|
return raw, HashToken(raw), nil
|
||
|
|
}
|
||
|
|
|
||
|
|
// HashToken creates the stable database key for a raw session/API token.
|
||
|
|
func HashToken(raw string) string {
|
||
|
|
sum := sha256.Sum256([]byte(raw))
|
||
|
|
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||
|
|
}
|