feat: a new account e-mail is confirmed with a code, and the old one is told
Changing the e-mail in Dados da conta took effect at once, with nothing checking the new address: a typo locked the customer out, and anyone at a signed-in computer who knew the password could move the account to their own e-mail and then reset its password. Now the code goes to the new address, the account changes only once it is entered (same screen and limits as signup, and only the account that asked can complete it), and the old address gets "O e-mail da sua conta foi trocado", with the WhatsApp to call if it was not them. Without e-mail on, it changes at once as before. Signup and e-mail change share one code check (expiry, five attempts, the 60 s resend wait). Tested: mail_test (wrong password, same and taken e-mail, wrong code, another account's attempt, resend wait, the notice), the full suite in a CI-style stack, and the screen in Brave. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -14,8 +14,8 @@ from ..core import db
|
||||
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, SignupCode, SignupResend)
|
||||
from ..core.models import (ArtworkSubmission, EmailChange, EmailCode, EmailResend, ForgotPassword, Login,
|
||||
PasswordChange, PasswordReset, ProfileUpdate, Register, SignupCode, SignupResend)
|
||||
from .. import mail
|
||||
from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
||||
from ..scanning import require_clean
|
||||
@@ -47,11 +47,45 @@ def signup_code(c, signup_id, email, exists):
|
||||
'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
|
||||
return send_code(c, signup_id, email, 'criar a conta no DTF Dropstar')
|
||||
|
||||
|
||||
def send_code(c, key, email, purpose):
|
||||
"""A fresh 6-digit code by e-mail for `purpose`; returns its hash."""
|
||||
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'Olá!\n\nO seu código para {purpose} é:\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)
|
||||
return code_digest(key, code)
|
||||
|
||||
|
||||
def checked_code(c, table, key, code, request, extra=''):
|
||||
"""The pending row a code confirms, locked, or the refusal to raise. A wrong
|
||||
code counts against the row; the caller raises after its block commits."""
|
||||
row = c.execute(f'SELECT * FROM dtf_local.{table} WHERE id=%s AND done_at IS NULL {extra} FOR UPDATE',
|
||||
key).fetchone()
|
||||
if not row or row['expires_at'] <= datetime.now(timezone.utc):
|
||||
return None, HTTPException(410, 'Este código venceu. Clique em “Reenviar código”.')
|
||||
if row['attempts'] >= CODE_ATTEMPTS:
|
||||
return None, HTTPException(429, 'Muitas tentativas com este código. Clique em “Reenviar código”.')
|
||||
if row['code_hash'] and secrets.compare_digest(row['code_hash'], code_digest(row['id'], code)):
|
||||
c.execute(f'UPDATE dtf_local.{table} SET done_at=now() WHERE id=%s', (row['id'],))
|
||||
return row, None
|
||||
c.execute(f'UPDATE dtf_local.{table} SET attempts=attempts+1 WHERE id=%s', (row['id'],))
|
||||
left = CODE_ATTEMPTS - row['attempts'] - 1
|
||||
audit('code_wrong', kind=table, ip=client_ip(request))
|
||||
return None, 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”.'))
|
||||
|
||||
|
||||
def resend_wait(row):
|
||||
"""Why another code cannot go yet, or None."""
|
||||
wait = RESEND_SECONDS - (datetime.now(timezone.utc) - row['sent_at']).total_seconds()
|
||||
if wait > 0:
|
||||
return HTTPException(429, f'Aguarde {int(wait) + 1} s para pedir outro código.')
|
||||
if row['sends'] >= CODE_SENDS:
|
||||
return HTTPException(429, 'Limite de códigos atingido. Comece de novo em alguns minutos.')
|
||||
return None
|
||||
|
||||
|
||||
def code_digest(signup_id, code):
|
||||
@@ -101,27 +135,12 @@ def create_account(profile, password, previous, response):
|
||||
|
||||
@router.post('/api/account/register/verify')
|
||||
def register_verify(body: SignupCode, request: Request, response: Response):
|
||||
rate_limit('signup-verify', client_ip(request), 30)
|
||||
rate_limit('code-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
|
||||
signup, refusal = checked_code(c, 'account_signups', (body.signup,), body.code, request)
|
||||
# Raised outside the block, so a wrong attempt is counted, not rolled back.
|
||||
if refusal:
|
||||
raise refusal
|
||||
return create_account(profile=signup['profile'], password=signup['password_hash'],
|
||||
previous=current(request), response=response)
|
||||
|
||||
@@ -143,17 +162,14 @@ def register_dev_code(signup: UUID):
|
||||
|
||||
@router.post('/api/account/register/resend')
|
||||
def register_resend(body: SignupResend, request: Request):
|
||||
rate_limit('signup-verify', client_ip(request), 30)
|
||||
rate_limit('code-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.')
|
||||
if refusal := resend_wait(signup):
|
||||
raise refusal
|
||||
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(),
|
||||
@@ -228,15 +244,66 @@ def change_email(body: EmailChange, request: Request, identity=Depends(owner)):
|
||||
if not password_matches(body.password, row['password_hash']):
|
||||
login_failed(row['email'])
|
||||
raise HTTPException(401, 'Senha incorreta.')
|
||||
profile = {**row['profile'], 'mail': body.email}
|
||||
if body.email == row['email']:
|
||||
raise HTTPException(422, 'Este já é o e-mail da sua conta.')
|
||||
if not mail.configured():
|
||||
return apply_email(identity, row, body.email)
|
||||
# With e-mail on, the change waits for the code sent to the new address.
|
||||
rate_limit('email-change', str(identity), CODE_SENDS, 3600)
|
||||
change = uuid4()
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (body.email,)).fetchone():
|
||||
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
||||
digest = send_code(c, change, body.email, 'trocar o e-mail da sua conta no DTF Dropstar')
|
||||
c.execute('''INSERT INTO dtf_local.email_changes(id,account_id,new_email,code_hash,expires_at)
|
||||
VALUES(%s,%s,%s,%s,now() + %s * interval '1 minute')''', (change, identity, body.email, digest, mail.CODE_MINUTES))
|
||||
audit('account_email_change_started', account=str(identity))
|
||||
return {'verify': str(change), 'email': body.email, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||
|
||||
|
||||
def apply_email(identity, row, email):
|
||||
"""Switch the account to the new e-mail and tell the old address."""
|
||||
profile = {**row['profile'], 'mail': email}
|
||||
try:
|
||||
with db.connect() as c:
|
||||
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (body.email, Jsonb(profile), identity))
|
||||
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s WHERE id=%s', (email, Jsonb(profile), identity))
|
||||
mail.queue(c, 'notice', row['email'], 'O e-mail da sua conta foi trocado · DTF Dropstar',
|
||||
f'Olá!\n\nO e-mail da sua conta no DTF Dropstar foi trocado para {email}. '
|
||||
'A partir de agora, entre com ele.\n\n'
|
||||
'Se não foi você, fale com a Dropstar pelo WhatsApp 16 99428-0056.')
|
||||
except UniqueViolation:
|
||||
raise HTTPException(409, 'Este e-mail já é de outra conta.')
|
||||
audit('account_email_changed', account=str(identity))
|
||||
return {'customer': profile}
|
||||
|
||||
|
||||
@router.post('/api/account/email/verify')
|
||||
def change_email_verify(body: EmailCode, request: Request, identity=Depends(owner)):
|
||||
rate_limit('code-verify', client_ip(request), 30)
|
||||
with db.connect() as c:
|
||||
change, refusal = checked_code(c, 'email_changes', (body.change, identity), body.code, request,
|
||||
extra='AND account_id=%s')
|
||||
row = account_row(c, identity) if change else None
|
||||
if refusal:
|
||||
raise refusal
|
||||
return apply_email(identity, row, change['new_email'])
|
||||
|
||||
|
||||
@router.post('/api/account/email/resend')
|
||||
def change_email_resend(body: EmailResend, request: Request, identity=Depends(owner)):
|
||||
rate_limit('code-verify', client_ip(request), 30)
|
||||
with db.connect() as c:
|
||||
change = c.execute('''SELECT * FROM dtf_local.email_changes WHERE id=%s AND account_id=%s AND done_at IS NULL
|
||||
FOR UPDATE''', (body.change, identity)).fetchone()
|
||||
if not change:
|
||||
raise HTTPException(410, 'Esta troca venceu. Comece de novo.')
|
||||
if refusal := resend_wait(change):
|
||||
raise refusal
|
||||
digest = send_code(c, change['id'], change['new_email'], 'trocar o e-mail da sua conta no DTF Dropstar')
|
||||
c.execute('''UPDATE dtf_local.email_changes 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, change['id']))
|
||||
return {'ok': True, 'minutes': mail.CODE_MINUTES, 'resend_seconds': RESEND_SECONDS}
|
||||
|
||||
@router.post('/api/account/password')
|
||||
def change_password(body: PasswordChange, request: Request, identity=Depends(owner)):
|
||||
with db.connect() as c:
|
||||
|
||||
Reference in New Issue
Block a user