Files
mygo/internal/auth/token.go
Huxley 3eeb9f6d26 Implement JWT authentication and app passkey support
- 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
2026-04-29 11:50:09 +08:00

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[:])
}