feat: password recovery by e-mail, team alerts, and a price for files opened by hand
Pilot customers had no way to reset a forgotten password, and the 7 October meeting asked for two things that only needed the client's inputs to go live. Password recovery: "Esqueci minha senha" in Minha conta sends a link that works once, for an hour (/conta/redefinir#token, in the fragment so it never reaches a server or a Referer). Only the token's hash is stored, the e-mail's text is erased once sent, the answer never says whether an account exists, and a reset signs out every other session. Limited per address and source. Team alerts: Kanban users who tick "Receber alertas por e-mail" in Usuários get one when an order is paid, a cart waits for review, or a payment needs attention. Messages are queued in the transaction that caused them and sent by the worker with retries (app/mail.py). Integrações shows an E-mail row with "Enviar teste". E-mail is off in production (MAIL_ADAPTER=off; recovery keeps offering WhatsApp) until the client's SMTP account exists; then it is only settings (docs/PORTAINER.md). The local stack keeps messages in the database and log. Files opened by hand: a finished sheet in CDR, AI, PSD or TIFF (or with a length the customer typed) pays the full price plus MANUAL_FILE_EXTRA_CENTS per metre, to steer customers to PNG as the meeting asked. It is 0 until Marcus gives the amount. The Site shows it before checkout, the server charges it, Tiny gets it in the unit price, and the Kanban says it. Tested: new tests/mail_test (reset flow, SMTP delivery against a local SMTP server, retry, who gets alerts), pricing unit tests, and the browser test now checks the Site total equals the server's, run with the charge at 0 and at R$ 5,00. The full CI suite passes in a CI-style stack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
"""Customer accounts, their orders, and the corrections they submit."""
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
@@ -10,10 +12,12 @@ from psycopg.types.json import Jsonb
|
||||
|
||||
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, session_row, throttle, transfer_guest)
|
||||
from ..core.models import ArtworkSubmission, EmailChange, Login, PasswordChange, ProfileUpdate, Register
|
||||
from ..runtime import STATES, file_rows, order_code, owned_order, storage
|
||||
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)
|
||||
from .. import mail
|
||||
from ..runtime import PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage
|
||||
from ..scanning import require_clean
|
||||
|
||||
router = APIRouter()
|
||||
@@ -139,6 +143,62 @@ def change_password(body: PasswordChange, request: Request, identity=Depends(own
|
||||
audit('account_password_changed', account=str(identity))
|
||||
return {'ok': True}
|
||||
|
||||
# Password recovery: a link by e-mail that works once, for an hour. The answer
|
||||
# never says whether the e-mail has an account.
|
||||
RESET_SENT = 'Se houver uma conta com este e-mail, enviamos um link para criar uma nova senha. Ele vale por 1 hora.'
|
||||
|
||||
@router.post('/api/account/forgot')
|
||||
def forgot_password(body: ForgotPassword, request: Request):
|
||||
if not mail.configured():
|
||||
raise HTTPException(503, 'A recuperação por e-mail ainda não está disponível. Fale com a Dropstar pelo WhatsApp.')
|
||||
email = body.email.strip().lower()
|
||||
rate_limit('reset-source', client_ip(request), 10)
|
||||
# Per address: a few links an hour, so nobody fills someone's inbox.
|
||||
rate_limit('reset-account', email, 3, 3600)
|
||||
token = secrets.token_urlsafe(32)
|
||||
with db.connect() as c:
|
||||
account = c.execute('SELECT id FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone()
|
||||
if account:
|
||||
c.execute('''INSERT INTO dtf_local.password_resets(token_hash,account_id,expires_at)
|
||||
VALUES(%s,%s,now() + %s * interval '1 minute')''',
|
||||
(hashlib.sha256(token.encode()).hexdigest(), account['id'], mail.RESET_MINUTES))
|
||||
# In the fragment, not the query: it is never sent to a server,
|
||||
# nor in the Referer of the fonts and the logo the page loads.
|
||||
link = f'{PUBLIC_ORIGIN}/conta/redefinir#{token}'
|
||||
mail.queue(c, 'reset', email, 'Crie uma nova senha · DTF Dropstar',
|
||||
'Olá!\n\nAlguém pediu para criar uma nova senha na sua conta do DTF Dropstar. '
|
||||
f'Para criar, abra o link abaixo. Ele vale por 1 hora e funciona uma vez só.\n\n{link}\n\n'
|
||||
'Se não foi você, ignore este e-mail: a sua senha continua a mesma.')
|
||||
audit('password_reset_requested', account=str(account['id']) if account else None, ip=client_ip(request))
|
||||
return {'ok': True, 'message': RESET_SENT}
|
||||
|
||||
@router.post('/api/account/reset')
|
||||
def reset_password(body: PasswordReset, request: Request, response: Response):
|
||||
rate_limit('reset-source', client_ip(request), 10)
|
||||
digest = hashlib.sha256(body.token.encode()).hexdigest()
|
||||
previous = current(request)
|
||||
with db.connect() as c:
|
||||
reset = c.execute('''SELECT * FROM dtf_local.password_resets WHERE token_hash=%s
|
||||
AND used_at IS NULL AND expires_at>now() FOR UPDATE''', (digest,)).fetchone()
|
||||
if not reset:
|
||||
audit('password_reset_refused', ip=client_ip(request))
|
||||
raise HTTPException(400, 'Este link venceu ou já foi usado. Peça outro em “Esqueci minha senha”.')
|
||||
identity = reset['account_id']
|
||||
account = account_row(c, identity, lock=True)
|
||||
c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.password), identity))
|
||||
c.execute('UPDATE dtf_local.password_resets SET used_at=now() WHERE token_hash=%s', (digest,))
|
||||
# Every other link to this account stops working, and so does every
|
||||
# session signed in with the old password.
|
||||
c.execute('DELETE FROM dtf_local.password_resets WHERE account_id=%s AND used_at IS NULL', (identity,))
|
||||
if previous:
|
||||
transfer_guest(c, previous, identity)
|
||||
c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s', (identity,))
|
||||
if previous:
|
||||
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
|
||||
new_session(c, response, identity)
|
||||
audit('password_reset', account=str(identity))
|
||||
return {'customer': account['profile']}
|
||||
|
||||
# The order list's groups, as the customer filters them.
|
||||
GROUPS = {'pay': 'Aguardando pagamento', 'prod': 'Em produção', 'cor': 'Correção', 'fin': 'Finalizados'}
|
||||
ENTRIES = '''WITH live_quote AS (
|
||||
|
||||
Reference in New Issue
Block a user