- Add JWT token generation and validation - Implement bcrypt password hashing - Create auth service with register/login/refresh/logout - Add app passkey generation and management - Implement protected routes and auth middleware - Add comprehensive tests for new functionality
31 lines
746 B
Go
31 lines
746 B
Go
package auth
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
)
|
|
|
|
const tokenPrefix = "mygo_"
|
|
const tokenByteLen = 24
|
|
|
|
// GenerateToken creates a random token with the "mygo_" prefix.
|
|
// Returns the raw token (shown to the user) and its SHA-256 hash (stored in DB).
|
|
func GenerateToken() (raw, hash string, err error) {
|
|
bytes := make([]byte, tokenByteLen)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return "", "", fmt.Errorf("generate random bytes: %w", err)
|
|
}
|
|
|
|
raw = tokenPrefix + hex.EncodeToString(bytes)
|
|
hash = HashToken(raw)
|
|
return raw, hash, nil
|
|
}
|
|
|
|
// HashToken returns the SHA-256 hex digest of a token.
|
|
func HashToken(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|