"""Customer accounts, their orders, and the corrections they submit.""" import hashlib import secrets from datetime import datetime, timedelta, timezone from uuid import UUID, uuid4 from typing import Literal from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response from psycopg.errors import UniqueViolation 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, rate_limit, session_row, throttle, transfer_guest) from ..core.models import (ArtworkSubmission, EmailChange, 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 router = APIRouter() def current(request): try: return session_row(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() throttle(email, request) # Registration attempts keep counting against the email, as before. login_failed(email) previous = current(request) 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: 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: raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.') 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() throttle(email, request) with db.connect() as c: account = c.execute('SELECT * FROM dtf_local.accounts WHERE email=%s', (email,)).fetchone() # Comparable password work even when the email is absent. stored = account['password_hash'] if account else DUMMY_PASSWORD_HASH matches = password_matches(body.password, stored) if not account or not matches: login_failed(email) audit('customer_login_failed', ip=client_ip(request)) raise HTTPException(401, 'E-mail ou senha inválidos.') previous = current(request) with db.connect() as c: if not stored.startswith('scrypt-v2$'): c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.password),account['id'])) if previous: transfer_guest(c, previous, account['id']) c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],)) new_session(c, response, account['id']) audit('customer_login_success', account=str(account['id'])) return {'customer': account['profile']} @router.post('/api/account/logout') def logout(request: Request, response: Response): previous = current(request) if previous: with db.connect() as c: c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],)) response.delete_cookie('dtf_session', httponly=True, samesite='strict') response.headers['Clear-Site-Data'] = '"storage"' audit('customer_logout') return {'ok': True} @router.get('/api/account/me') def me(identity=Depends(owner)): with db.connect() as c: row = c.execute('SELECT profile FROM dtf_local.accounts WHERE id=%s', (identity,)).fetchone() return {'customer': row['profile'] if row else None} def account_row(c, identity, lock=False): row = c.execute('SELECT * FROM dtf_local.accounts WHERE id=%s' + (' FOR UPDATE' if lock else ''), (identity,)).fetchone() if not row: raise HTTPException(401, 'Entre na sua conta.') return row @router.post('/api/account/profile') def update_profile(body: ProfileUpdate, identity=Depends(owner)): """WhatsApp and the saved delivery address. The CNPJ is the account's and does not change; the e-mail is the login and changes on its own route.""" with db.connect() as c: row = account_row(c, identity, lock=True) profile = {**row['profile'], 'zap': body.zap, 'address': body.address.model_dump() if body.address else None} c.execute('UPDATE dtf_local.accounts SET profile=%s WHERE id=%s', (Jsonb(profile), identity)) audit('account_profile_updated', account=str(identity)) return {'customer': profile} @router.post('/api/account/email') def change_email(body: EmailChange, request: Request, identity=Depends(owner)): with db.connect() as c: row = account_row(c, identity) throttle(row['email'], request) if not password_matches(body.password, row['password_hash']): login_failed(row['email']) raise HTTPException(401, 'Senha incorreta.') profile = {**row['profile'], 'mail': body.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)) 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/password') def change_password(body: PasswordChange, request: Request, identity=Depends(owner)): with db.connect() as c: row = account_row(c, identity) throttle(row['email'], request) if not password_matches(body.current, row['password_hash']): login_failed(row['email']) raise HTTPException(401, 'Senha atual incorreta.') session = current(request) with db.connect() as c: c.execute('UPDATE dtf_local.accounts SET password_hash=%s WHERE id=%s', (password_hash(body.new), identity)) # Other devices signed in with the old password are signed out. c.execute('DELETE FROM dtf_local.sessions WHERE owner=%s AND id<>%s', (identity, session['id'])) 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 ( -- The cart waiting for payment: the newest unpaid quote whose files still -- exist. An older one was replaced when the cart changed, and one whose -- files are gone can no longer be paid. SELECT q.id, q.created_at, q.approved FROM dtf_local.quotes q LEFT JOIN dtf_local.orders o ON o.quote_id=q.id WHERE q.owner=%(me)s AND o.id IS NULL AND q.discarded_at IS NULL AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(q.draft->'items') i CROSS JOIN LATERAL jsonb_array_elements_text(i->'uploads') u(uid) JOIN dtf_local.uploads up ON up.id=u.uid::uuid WHERE up.purged_at IS NOT NULL OR up.expires_at<=now()) ORDER BY q.created_at DESC LIMIT 1 ), entries AS ( SELECT 'order' AS kind, o.id, o.number, CASE WHEN o.cancelled_at IS NOT NULL THEN 'cancelled' ELSE o.state END, CASE WHEN o.cancelled_at IS NOT NULL OR o.state='fin' THEN 'fin' WHEN o.state='cor' THEN 'cor' ELSE 'prod' END AS grp, (o.snapshot->>'total_cents')::bigint AS total_cents, o.created_at, o.snapshot->'items' AS items FROM dtf_local.orders o WHERE o.owner=%(me)s UNION ALL SELECT 'quote', q.id, NULL, CASE WHEN q.approved IS NULL THEN 'review' ELSE 'pay' END, 'pay', (q.approved->>'total_cents')::bigint, q.created_at, COALESCE(q.approved->'items','[]'::jsonb) FROM live_quote q )''' @router.get('/api/customer/orders') def orders(identity=Depends(owner), status: Literal['all','pay','prod','cor','fin'] = 'all', number: int | None = Query(None, ge=1), code: str | None = Query(None, max_length=12, pattern=r'^[0-9A-Fa-f]+$'), days: int = Query(0, ge=0, le=3650), page: int = Query(1, ge=1, le=10000), size: int = Query(10, ge=1, le=50)): """The customer's orders and the cart waiting for payment, newest first, filtered and a page at a time, with how many there are in each group.""" params = {'me': identity, 'grp': None if status == 'all' else status, 'number': number, 'code': code.lower() + '%' if code else None, 'since': datetime.now(timezone.utc) - timedelta(days=days) if days else None, 'size': size, 'offset': (page - 1) * size} where = '''WHERE (%(grp)s::text IS NULL OR grp=%(grp)s) AND (%(number)s::int IS NULL OR number=%(number)s) AND (%(code)s::text IS NULL OR (kind='order' AND replace(id::text,'-','') LIKE %(code)s)) AND (%(since)s::timestamptz IS NULL OR created_at>=%(since)s)''' with db.connect() as c: counts = {r['grp']: r['n'] for r in c.execute(ENTRIES + ' SELECT grp, count(*) AS n FROM entries GROUP BY grp', params).fetchall()} total = c.execute(ENTRIES + ' SELECT count(*) AS n FROM entries ' + where, params).fetchone()['n'] rows = c.execute(ENTRIES + ' SELECT * FROM entries ' + where + ' ORDER BY created_at DESC LIMIT %(size)s OFFSET %(offset)s', params).fetchall() items = [] for r in rows: entry = {'kind': r['kind'], 'id': r['id'], 'number': r['number'], 'state': r['state'], 'code': order_code(r['id']) if r['kind'] == 'order' else None, 'group': r['grp'], 'total_cents': r['total_cents'], 'created_at': r['created_at'], 'items': [{'mode': i['mode'], 'billed_metres': i.get('billed_metres')} for i in r['items']]} if r['kind'] == 'quote': # A PIX code still open is paid on its own page. pix = c.execute('''SELECT 1 FROM dtf_local.payment_intents WHERE quote_id=%s AND method='pix' AND status='pending' AND COALESCE((response->>'expires_at')::timestamptz > now(), false)''', (r['id'],)).fetchone() entry['pay_with'] = 'pix' if pix else 'page' items.append(entry) return {'items': items, 'total': total, 'page': page, 'size': size, 'counts': {g: counts.get(g, 0) for g in GROUPS}, 'groups': GROUPS, 'states': STATES} @router.get('/api/customer/orders/{oid}') def detail(oid: UUID, identity=Depends(owner)): with db.connect() as c: row = owned_order(c, oid, identity) # A move back undoes an operator's mistake and its reason is internal; # only a correction's reason is written for the customer. history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason, created_at FROM dtf_local.movements WHERE order_id=%s AND NOT back ORDER BY id''', (oid,)).fetchall() return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']), 'state': row['state'], 'version': row['version'], 'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history, 'files': file_rows(c,oid)} @router.post('/api/customer/orders/{oid}/corrections') def correction(oid: UUID, body: ArtworkSubmission, identity=Depends(owner)): with db.connect() as c: order = owned_order(c, oid, identity, lock=True) return submit_files(c,order,body,identity,'correction','customer') @router.get('/api/customer/orders/{oid}/files/{fid}/download') def customer_download(oid: UUID, fid: UUID, identity=Depends(owner)): with db.connect() as c: owned_order(c,oid,identity) row = c.execute('SELECT u.* FROM dtf_local.order_files f JOIN dtf_local.uploads u ON u.id=f.upload_id WHERE f.id=%s AND f.order_id=%s AND f.active', (fid,oid)).fetchone() if not row: raise HTTPException(404, 'Arquivo não encontrado.') if row['expires_at'] <= datetime.now(timezone.utc): raise HTTPException(410, 'Este arquivo não está mais disponível: os arquivos ficam guardados por 30 dias.') require_clean(row) return {'url':storage.download(row['object_key'],row['name']), 'name':row['name']}