Files
uptimesebi/internal/auth/totp.go
Sebastian UnterschützandClaude Opus 5.5 d20225982a refactor: follow the google go style guide
Document every package and exported identifier, return the log level
from NewLogger instead of keeping it in a package variable, and stop
tests from mutating the argon2 parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 00:18:02 +01:00

48 lines
1.4 KiB
Go

package auth
import (
"context"
"time"
"github.com/google/uuid"
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"github.com/redis/go-redis/v9"
)
const totpIssuer = "uptimesebi"
// NewTOTPKey generates a secret for account using the defaults every common
// authenticator app supports (SHA-1, 6 digits, 30 s).
func NewTOTPKey(account string) (*otp.Key, error) {
return totp.Generate(totp.GenerateOpts{Issuer: totpIssuer, AccountName: account})
}
// TOTPVerifier rejects a code that was already accepted once, so an observed
// code cannot be replayed within its validity window.
type TOTPVerifier struct {
rdb redis.UniversalClient
now func() time.Time
}
// NewTOTPVerifier returns a verifier that records used codes in rdb.
func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier {
return &TOTPVerifier{rdb: rdb, now: time.Now}
}
// Verify accepts code for secret within one step of clock skew, at most once
// per user.
func (v *TOTPVerifier) Verify(ctx context.Context, user uuid.UUID, secret, code string) (bool, error) {
ok, err := totp.ValidateCustom(code, secret, v.now(), totp.ValidateOpts{
Period: 30, Skew: 1, Digits: otp.DigitsSix, Algorithm: otp.AlgorithmSHA1,
})
if err != nil || !ok {
return false, nil
}
fresh, err := v.rdb.SetNX(ctx, "totp_used:"+user.String()+":"+code, 1, 2*time.Minute).Result()
if err != nil {
return false, err
}
return fresh, nil
}