sonda/internal/auth/token.go
tgiachi 3a739dc3ae feat: add sondad server with config, storage, auth and listening API
- feat(config): TOML config with env overrides, strict parsing and validation
- feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun,
  embedded per-driver SQL migrations with a transactional runner
- feat(schema): catalog tables (artists, albums, tracks, audio_files with
  per-root paths), users and listening events with idempotency keys
- feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only
  registration and login
- feat(api): gin REST API under /api/v1 (health, register, login, listens)
  with a consistent error envelope, body limit and request logging
- feat(sondad): zap logger, graceful shutdown, composition root in main
- chore: example config, .gitignore for secrets, DB files, IDE and agent files
2026-11-11 12:06:15 +01:00

71 lines
1.9 KiB
Go

package auth
import (
"fmt"
"strconv"
"time"
"github.com/golang-jwt/jwt/v5"
)
const tokenIssuerName = "sonda"
// Claims is what a valid access token tells us about the caller.
type Claims struct {
UserID int64
Username string
}
type tokenClaims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
// TokenIssuer creates and verifies HS256 JWT access tokens.
type TokenIssuer struct {
secret []byte
ttl time.Duration
now func() time.Time
}
// NewTokenIssuer builds an issuer. The secret must be long and random.
func NewTokenIssuer(secret string, ttl time.Duration) *TokenIssuer {
return &TokenIssuer{secret: []byte(secret), ttl: ttl, now: time.Now}
}
// Issue signs a token for user and returns it with its expiry time.
func (i *TokenIssuer) Issue(user User) (string, time.Time, error) {
now := i.now()
exp := now.Add(i.ttl)
claims := tokenClaims{Username: user.Username,
Issuer: tokenIssuerName,
Subject: strconv.FormatInt(user.ID, 10),
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(exp)}
signed, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(i.secret)
if err != nil {
return "", time.Time{}, fmt.Errorf("sign token: %w", err)
}
return signed, exp, nil
}
// Parse verifies the signature, algorithm, issuer and expiry of token.
func (i *TokenIssuer) Parse(token string) (Claims, error) {
var tc tokenClaims
_, err := jwt.ParseWithClaims(token, &tc,
func(*jwt.Token) (any, error) { return i.secret, nil },
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
jwt.WithIssuer(tokenIssuerName),
jwt.WithExpirationRequired(),
jwt.WithTimeFunc(i.now),
)
if err != nil {
return Claims{}, fmt.Errorf("invalid token: %w", err)
}
id, err := strconv.ParseInt(tc.Subject, 10, 64)
if err != nil || id <= 0 {
return Claims{}, fmt.Errorf("invalid token: bad subject")
}
return Claims{UserID: id, Username: tc.Username}, nil
}