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 (
|
||||
|
||||
@@ -6,8 +6,10 @@ import httpx
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
|
||||
from ..core import db
|
||||
from .. import mail
|
||||
from ..core.auth import client_ip, owner, new_session, rate_limit
|
||||
from ..core.limits import upload_limit_bytes
|
||||
from ..core.pricing import manual_extra_cents
|
||||
from ..core.models import FreightEstimate
|
||||
from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, freight, payment,
|
||||
require_delivery_available, storage)
|
||||
@@ -38,6 +40,9 @@ def session(request: Request, response: Response):
|
||||
session_id = new_session(c, response)
|
||||
return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES,
|
||||
'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name,
|
||||
'password_recovery': mail.configured(),
|
||||
# Per metre on a finished sheet someone opens by hand (app/core/pricing.py).
|
||||
'manual_extra_cents': manual_extra_cents(),
|
||||
# Public by design: Mercado Pago's card form needs it in the browser.
|
||||
'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '',
|
||||
# The delivery service the cart quotes, or none: pickup only.
|
||||
|
||||
@@ -15,7 +15,7 @@ from ..core.auth import (COOKIE_SECURE, DUMMY_PASSWORD_HASH, audit, can, client_
|
||||
login_failed, password_matches, throttle)
|
||||
from ..core.models import Move, OperatorLogin, Resolution, Review, StrictModel
|
||||
from ..printjobs import queue as queue_print_files
|
||||
from .. import cnpj, payments, quote_review
|
||||
from .. import cnpj, mail, payments, quote_review
|
||||
from .. import tiny
|
||||
from ..runtime import (BACK, BOARD_FINISHED_LIMIT, BOARD_QUOTE_LIMIT, ENVIRONMENT, PUBLIC_ORIGIN, STATES,
|
||||
TRANSITIONS, payment, enqueue, freight, quote_view, storage)
|
||||
@@ -122,7 +122,8 @@ def board(request: Request, user=Depends(operator)):
|
||||
quotes = [quote_view(c, q) for q in pending + approved]
|
||||
return {'states': STATES, 'transitions': TRANSITIONS, 'back': BACK,
|
||||
'orders': orders, 'payment_issues_total': issues_total, 'tiny': tiny_status(), 'operator': user,
|
||||
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup},
|
||||
'providers': {'payment': payment.name, 'freight': freight_status(), 'backup': backup,
|
||||
'mail': mail.status(c)},
|
||||
'environment': ENVIRONMENT, 'site_origin': PUBLIC_ORIGIN,
|
||||
'finished_shown': len(finished), 'finished_total': finished_total,
|
||||
'machines': [{**m, 'id': str(m['id'])} for m in c.execute(
|
||||
|
||||
@@ -7,7 +7,7 @@ from uuid import UUID, uuid4
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from .. import payments
|
||||
from .. import mail, payments
|
||||
from ..core import db
|
||||
from ..core.auth import owner
|
||||
from ..core.models import QuoteRequest
|
||||
@@ -61,6 +61,9 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)):
|
||||
if row['id'] == uid:
|
||||
# An operator reviews it first; the files wait for that review.
|
||||
payments.hold_uploads(c, payments.quote_uploads(draft), payments.REVIEW_HOLD)
|
||||
mail.alert(c, 'Cotação esperando revisão',
|
||||
['Um cliente montou um carrinho que precisa de revisão antes do pagamento.',
|
||||
f'Motivo: {reason}', '', *mail.summary(draft)], '/')
|
||||
return {'id': row['id'], 'status': 'approved' if row['approved'] else 'pending_review'}
|
||||
|
||||
@router.get('/api/quotes/{uid}')
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""Kanban users and print machines, managed by the administrators.
|
||||
|
||||
There is no e-mail yet, so an administrator creates each account with a
|
||||
first password and the person changes it in "Minha senha". The superadmin is
|
||||
An administrator creates each account with a first password and the person
|
||||
changes it in "Minha senha". Whoever wants the team's alerts by e-mail has
|
||||
them switched on here. The superadmin is
|
||||
the system's own account, set from the console (python -m app.operators);
|
||||
administrators manage everyone else. Nobody can remove, disable or demote
|
||||
themselves, so the last administrator cannot lock the team out by accident.
|
||||
@@ -13,6 +14,7 @@ from uuid import UUID, uuid4
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from pydantic import Field, field_validator
|
||||
|
||||
from .. import mail
|
||||
from ..core import db
|
||||
from ..core.auth import CAPABILITIES, audit, can, password_hash, password_matches, signed_in
|
||||
from ..core.models import StrictModel
|
||||
@@ -27,6 +29,8 @@ class UserIn(StrictModel):
|
||||
password: str | None = Field(default=None, min_length=12, max_length=128)
|
||||
active: bool = True
|
||||
machines: list[UUID] = Field(default_factory=list, max_length=50)
|
||||
# The team's alerts by e-mail: orders paid, carts waiting for review, payments to look at.
|
||||
alerts: bool = False
|
||||
|
||||
@field_validator('email')
|
||||
@classmethod
|
||||
@@ -70,7 +74,7 @@ def change_password(body: PasswordChange, request: Request):
|
||||
|
||||
|
||||
def user_rows(c):
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.last_login_at,o.created_at,
|
||||
rows = c.execute('''SELECT o.id,o.email,o.name,o.role,o.active,o.alerts,o.last_login_at,o.created_at,
|
||||
COALESCE(array_agg(m.machine_id) FILTER (WHERE m.machine_id IS NOT NULL), '{}') AS machines
|
||||
FROM dtf_local.operators o LEFT JOIN dtf_local.operator_machines m ON m.operator_id=o.id
|
||||
GROUP BY o.id ORDER BY o.active DESC, o.name, o.email''').fetchall()
|
||||
@@ -113,9 +117,9 @@ def create_user(body: UserIn, request: Request, user=Depends(can('users'))):
|
||||
with db.connect() as c:
|
||||
if c.execute('SELECT 1 FROM dtf_local.operators WHERE email=%s', (body.email,)).fetchone():
|
||||
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active)
|
||||
VALUES(%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.active))
|
||||
c.execute('''INSERT INTO dtf_local.operators(id,email,name,password_hash,role,active,alerts)
|
||||
VALUES(%s,%s,%s,%s,%s,%s,%s)''', (uid, body.email, body.name.strip(), password_hash(body.password),
|
||||
body.role, body.active, body.alerts))
|
||||
set_machines(c, uid, body.machines)
|
||||
audit('operator_created', operator=user, account=body.email, role=body.role)
|
||||
return {'id': str(uid)}
|
||||
@@ -133,8 +137,8 @@ def update_user(uid: UUID, body: UserIn, request: Request, user=Depends(can('use
|
||||
if body.email != row['email'] and c.execute(
|
||||
'SELECT 1 FROM dtf_local.operators WHERE email=%s AND id<>%s', (body.email, uid)).fetchone():
|
||||
raise HTTPException(409, 'Já existe um usuário com este e-mail.')
|
||||
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s WHERE id=%s',
|
||||
(body.name.strip(), body.email, role, body.active, uid))
|
||||
c.execute('UPDATE dtf_local.operators SET name=%s,email=%s,role=%s,active=%s,alerts=%s WHERE id=%s',
|
||||
(body.name.strip(), body.email, role, body.active, body.alerts, uid))
|
||||
if body.password:
|
||||
c.execute('UPDATE dtf_local.operators SET password_hash=%s WHERE id=%s', (password_hash(body.password), uid))
|
||||
if body.email != row['email']:
|
||||
@@ -208,3 +212,15 @@ def delete_machine(mid: UUID, user=Depends(can('users'))):
|
||||
raise HTTPException(404, 'Máquina não encontrada.')
|
||||
audit('machine_deleted', operator=user, machine=row['name'])
|
||||
return {'ok': True}
|
||||
|
||||
|
||||
@router.post('/api/operator/mail/test')
|
||||
def test_mail(request: Request, user=Depends(can('manage'))):
|
||||
"""A message to whoever asked, to prove the mail server works."""
|
||||
with db.connect() as c:
|
||||
if not mail.queue(c, 'test', user, 'Teste de e-mail · Kanban DTF',
|
||||
'Este é um teste do Kanban DTF. Se chegou, o envio de e-mails está funcionando: '
|
||||
'recuperação de senha dos clientes e alertas da equipe.'):
|
||||
raise HTTPException(409, 'O envio de e-mails não está configurado no servidor.')
|
||||
audit('mail_test_queued', operator=user)
|
||||
return {'ok': True, 'to': user}
|
||||
|
||||
Reference in New Issue
Block a user