Refs #3 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
43 lines
1.1 KiB
Go
43 lines
1.1 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"
|
|
|
|
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
|
|
}
|
|
|
|
func NewTOTPVerifier(rdb redis.UniversalClient) *TOTPVerifier {
|
|
return &TOTPVerifier{rdb: rdb, now: time.Now}
|
|
}
|
|
|
|
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
|
|
}
|