sonda/internal/auth/token.go
tgiachi 96ad8b1f62 feat(auth): accounts are identified by an email address
Registration, login and the admin's create-user call take `email` instead of
`username`, and the user object returns `email`. The address is checked for its
shape (a plain address, no display name, at most 254 bytes), trimmed, lowercased
and unique. Sonda sends no mail and does not verify it.

- Migration 0018 renames the users column (and the PostgreSQL index); values are
  kept, so an account made before keeps its plain name and still logs in with it
  (login does not check the shape).
- Error code username_taken becomes email_taken; the JWT claim is now `email`,
  so access tokens issued before the upgrade are refused once and clients refresh.
- OpenAPI spec, README, the web login form (type email), strings (en, it) and
  the generated API types follow.

Closes #65
2026-11-12 14:40:33 +01:00

78 lines
2.1 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
Email string
// IssuedAt is when the token was signed. An account created after that moment
// cannot be the one the token was issued for.
IssuedAt time.Time
}
type tokenClaims struct {
Email string `json:"email"`
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{Email: user.Email,
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")
}
var issued time.Time
if tc.IssuedAt != nil {
issued = tc.IssuedAt.Time
}
return Claims{UserID: id, Email: tc.Email, IssuedAt: issued}, nil
}