feat: a new account is confirmed with a code sent to its e-mail
All checks were successful
Build and deploy / Validate source (push) Successful in 17s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m22s
All checks were successful
Build and deploy / Validate source (push) Successful in 17s
Build and deploy / Integration suite on a real stack (push) Successful in 4m25s
Build and deploy / Secret scan and release gate (push) Successful in 9s
Build and deploy / Publish images (push) Successful in 1m22s
Anyone could open an account on someone else's e-mail. Now "Criar conta" e-mails a 6-digit code, and the account exists only once it is entered: one big field that takes a paste or the phone's autofill and confirms by itself, "Reenviar código" after 60 s, "Trocar e-mail", and the sign-in box hidden meanwhile. Security: 15 minutes per code, 5 wrong attempts, at most 5 codes, limits per address and per source; the password is hashed at the first step and the code stored only as a hash, its e-mail erased once sent. An address that already has an account gets the same answer on screen and a "você já tem conta" e-mail instead of a code, so the form does not reveal who is registered. Without e-mail (MAIL_ADAPTER=off) the account is created at once, as before. The browser test reads the code from a local-only endpoint that exists only where e-mail stays in the log. Tested: mail_test (wrong, locked, resent, expired codes, existing address, erasure after SMTP), the full suite and the browser test in a CI-style stack, and the screens in Brave on desktop and phone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,9 +15,9 @@ from ..artwork import submit_files
|
||||
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner, login_failed, password_hash,
|
||||
password_matches, rate_limit, session_row, throttle, transfer_guest)
|
||||
from ..core.models import (ArtworkSubmission, EmailChange, ForgotPassword, Login, PasswordChange, PasswordReset,
|
||||
ProfileUpdate, Register)
|
||||
ProfileUpdate, Register, SignupCode, SignupResend)
|
||||
from .. import mail
|
||||
from ..runtime import PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
||||
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
||||
from ..scanning import require_clean
|
||||
|
||||
router = APIRouter()
|
||||
@@ -28,6 +28,36 @@ def current(request):
|
||||
except HTTPException: return None
|
||||
|
||||
|
||||
# Signup: with e-mail on, the account exists only once the code sent to the
|
||||
# address is entered, so nobody opens an account on someone else's e-mail. The
|
||||
# answer is the same whether or not the address already has an account: that
|
||||
# address gets a notice to sign in instead of a code, and no code works.
|
||||
CODE_ATTEMPTS = 5
|
||||
CODE_SENDS = 5
|
||||
RESEND_SECONDS = 60
|
||||
|
||||
|
||||
def signup_code(c, signup_id, email, exists):
|
||||
"""A fresh code for a signup (or the notice for an address that already has
|
||||
an account), queued by e-mail. Returns the code's hash, None for the notice."""
|
||||
if exists:
|
||||
mail.queue(c, 'account', email, 'Você já tem conta · DTF Dropstar',
|
||||
'Olá!\n\nAlguém tentou criar uma conta no DTF Dropstar com este e-mail, mas ele já tem conta.\n\n'
|
||||
f'Para entrar: {PUBLIC_ORIGIN}/conta/entrar\n'
|
||||
'Esqueceu a senha? Na mesma página, clique em “Esqueci minha senha”.\n\n'
|
||||
'Se não foi você, ignore este e-mail: nada muda na sua conta.')
|
||||
return None
|
||||
code = f'{secrets.randbelow(10 ** 6):06d}'
|
||||
mail.queue(c, 'code', email, f'{code} é o seu código · DTF Dropstar',
|
||||
f'Olá!\n\nO seu código para criar a conta no DTF Dropstar é:\n\n{code}\n\n'
|
||||
f'Ele vale por {mail.CODE_MINUTES} minutos. Se não foi você, ignore este e-mail.')
|
||||
return code_digest(signup_id, code)
|
||||
|
||||
|
||||
def code_digest(signup_id, code):
|
||||
return hashlib.sha256(f'{signup_id}:{code}'.encode()).hexdigest()
|
||||
|
||||
|
||||
@router.post('/api/account/register')
|
||||
def register(body: Register, request: Request, response: Response):
|
||||
email = body.customer.mail.strip().lower()
|
||||
@@ -35,15 +65,32 @@ def register(body: Register, request: Request, response: Response):
|
||||
# Registration attempts keep counting against the email, as before.
|
||||
login_failed(email)
|
||||
previous = current(request)
|
||||
encoded = password_hash(body.password)
|
||||
identity = uuid4()
|
||||
profile = body.customer.model_dump()
|
||||
profile['mail'] = email
|
||||
with db.connect() as c:
|
||||
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
|
||||
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
|
||||
if mail.configured():
|
||||
rate_limit('signup-account', email, CODE_SENDS, 3600)
|
||||
signup_id = uuid4()
|
||||
with db.connect() as c:
|
||||
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
|
||||
digest = signup_code(c, signup_id, email, exists)
|
||||
c.execute('''INSERT INTO dtf_local.account_signups(id,email,profile,password_hash,code_hash,expires_at)
|
||||
VALUES(%s,%s,%s,%s,%s,now() + %s * interval '1 minute')''',
|
||||
(signup_id, email, Jsonb(profile), password_hash(body.password), digest, mail.CODE_MINUTES))
|
||||
audit('account_signup_started', ip=client_ip(request))
|
||||
return {'verify': str(signup_id), 'email': email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||
# Without e-mail there is no code to send: the account is created at once.
|
||||
return create_account(profile=profile, password=password_hash(body.password), previous=previous, response=response)
|
||||
|
||||
|
||||
def create_account(profile, password, previous, response):
|
||||
identity = uuid4()
|
||||
try:
|
||||
with db.connect() as c:
|
||||
if previous and c.execute('SELECT id FROM dtf_local.accounts WHERE id=%s', (previous['owner'],)).fetchone():
|
||||
raise HTTPException(409, 'Saia da conta atual antes de criar outra.')
|
||||
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile)))
|
||||
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)',
|
||||
(identity, profile['mail'], password, Jsonb(profile)))
|
||||
if previous: transfer_guest(c, previous, identity)
|
||||
new_session(c, response, identity)
|
||||
except UniqueViolation:
|
||||
@@ -51,6 +98,69 @@ def register(body: Register, request: Request, response: Response):
|
||||
audit('account_registered', account=str(identity))
|
||||
return {'customer': profile}
|
||||
|
||||
|
||||
@router.post('/api/account/register/verify')
|
||||
def register_verify(body: SignupCode, request: Request, response: Response):
|
||||
rate_limit('signup-verify', client_ip(request), 30)
|
||||
with db.connect() as c:
|
||||
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
|
||||
(body.signup,)).fetchone()
|
||||
if not signup or signup['expires_at'] <= datetime.now(timezone.utc):
|
||||
raise HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
|
||||
if signup['attempts'] >= CODE_ATTEMPTS:
|
||||
raise HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
|
||||
right = signup['code_hash'] and secrets.compare_digest(signup['code_hash'], code_digest(signup['id'], body.code))
|
||||
if not right:
|
||||
c.execute('UPDATE dtf_local.account_signups SET attempts=attempts+1 WHERE id=%s', (signup['id'],))
|
||||
left = CODE_ATTEMPTS - signup['attempts'] - 1
|
||||
audit('account_signup_code_wrong', ip=client_ip(request))
|
||||
# Committed with the attempt: the connection's block ends cleanly.
|
||||
wrong = HTTPException(400, 'Código incorreto. ' + (f'Restam {left} tentativas.' if left > 1 else
|
||||
'Resta 1 tentativa.' if left == 1 else 'Clique em “Reenviar código”.'))
|
||||
else:
|
||||
wrong = None
|
||||
c.execute('UPDATE dtf_local.account_signups SET done_at=now() WHERE id=%s', (signup['id'],))
|
||||
if wrong:
|
||||
raise wrong
|
||||
return create_account(profile=signup['profile'], password=signup['password_hash'],
|
||||
previous=current(request), response=response)
|
||||
|
||||
|
||||
@router.get('/api/account/register/dev-code')
|
||||
def register_dev_code(signup: UUID):
|
||||
"""The local stack's last code for a signup, for the browser test, which
|
||||
cannot read the database. Only where e-mail stays in the log; elsewhere
|
||||
the code exists only in the customer's inbox."""
|
||||
if ENVIRONMENT != 'local' or mail.ADAPTER != 'log':
|
||||
raise HTTPException(404, 'Not found')
|
||||
with db.connect() as c:
|
||||
row = c.execute('''SELECT m.body FROM dtf_local.account_signups s JOIN dtf_local.mail_queue m
|
||||
ON m.to_addr=s.email AND m.kind='code' WHERE s.id=%s ORDER BY m.id DESC LIMIT 1''', (signup,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, 'Not found')
|
||||
return {'code': next(word for word in row['body'].split() if word.isdigit() and len(word) == 6)}
|
||||
|
||||
|
||||
@router.post('/api/account/register/resend')
|
||||
def register_resend(body: SignupResend, request: Request):
|
||||
rate_limit('signup-verify', client_ip(request), 30)
|
||||
with db.connect() as c:
|
||||
signup = c.execute('SELECT * FROM dtf_local.account_signups WHERE id=%s AND done_at IS NULL FOR UPDATE',
|
||||
(body.signup,)).fetchone()
|
||||
if not signup:
|
||||
raise HTTPException(410, 'Este cadastro venceu. Preencha os dados de novo.')
|
||||
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - signup['sent_at']).total_seconds()
|
||||
if wait > 0:
|
||||
raise HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
|
||||
if signup['sends'] >= CODE_SENDS:
|
||||
raise HTTPException(429, 'Limite de códigos atingido. Preencha os dados de novo em alguns minutos.')
|
||||
exists = c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (signup['email'],)).fetchone()
|
||||
digest = signup_code(c, signup['id'], signup['email'], exists)
|
||||
c.execute('''UPDATE dtf_local.account_signups SET code_hash=%s, attempts=0, sends=sends+1, sent_at=now(),
|
||||
expires_at=now() + %s * interval '1 minute' WHERE id=%s''', (digest, mail.CODE_MINUTES, signup['id']))
|
||||
audit('account_signup_code_resent', ip=client_ip(request))
|
||||
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||
|
||||
@router.post('/api/account/login')
|
||||
def login(body: Login, request: Request, response: Response):
|
||||
email = body.email.strip().lower()
|
||||
|
||||
Reference in New Issue
Block a user