feat: an account brings the orders bought without it with its CPF/CNPJ and e-mail
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 4m44s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m22s
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 4m44s
Build and deploy / Secret scan and release gate (push) Successful in 10s
Build and deploy / Publish images (push) Successful in 1m22s
At signup (once the e-mailed code confirms the address), on an e-mail change and at every sign-in, a confirmed account takes over the guest orders placed with the same CPF/CNPJ and the same e-mail, from any browser, with their carts and files. A CPF or CNPJ alone, which others may know, brings nothing; neither does an account whose e-mail was never confirmed. Accounts already confirmed by a code are marked as such. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -119,13 +119,40 @@ def register(body: Register, request: Request, response: Response):
|
||||
return create_account(profile=profile, password=password_hash(body.password), previous=previous, response=response)
|
||||
|
||||
|
||||
def create_account(profile, password, previous, response):
|
||||
def claim_orders(c, identity, profile):
|
||||
"""Orders bought without an account with this account's CPF/CNPJ and
|
||||
e-mail, from any browser. Only for an e-mail confirmed with a code: a
|
||||
CPF or CNPJ alone, which others may know, never brings anyone's orders.
|
||||
Each order comes with its cart and the customer's files."""
|
||||
document = ''.join(ch for ch in str(profile.get('cnpj') or '') if ch.isdigit())
|
||||
if not document:
|
||||
return 0
|
||||
orders = c.execute('''SELECT o.id,o.owner,o.quote_id,o.snapshot FROM dtf_local.orders o
|
||||
WHERE o.owner<>%s AND NOT EXISTS (SELECT 1 FROM dtf_local.accounts a WHERE a.id=o.owner)
|
||||
AND regexp_replace(coalesce(o.snapshot->'customer'->>'cnpj',''),'\\D','','g')=%s
|
||||
AND lower(trim(o.snapshot->'customer'->>'mail'))=%s
|
||||
FOR UPDATE''', (identity, document, profile['mail'].strip().lower())).fetchall()
|
||||
for order in orders:
|
||||
uploads = [uid for item in order['snapshot'].get('items') or [] for uid in item.get('uploads') or []]
|
||||
uploads += [row['upload_id'] for row in c.execute(
|
||||
'SELECT upload_id FROM dtf_local.order_files WHERE order_id=%s', (order['id'],)).fetchall()]
|
||||
c.execute('UPDATE dtf_local.orders SET owner=%s WHERE id=%s', (identity, order['id']))
|
||||
c.execute('UPDATE dtf_local.quotes SET owner=%s WHERE id=%s AND owner=%s', (identity, order['quote_id'], order['owner']))
|
||||
c.execute('UPDATE dtf_local.uploads SET owner=%s WHERE id=ANY(%s::uuid[]) AND owner=%s',
|
||||
(identity, [str(uid) for uid in uploads], order['owner']))
|
||||
if orders:
|
||||
audit('account_orders_claimed', account=str(identity), orders=len(orders))
|
||||
return len(orders)
|
||||
|
||||
|
||||
def create_account(profile, password, previous, response, verified=False):
|
||||
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)))
|
||||
c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile,email_verified) VALUES(%s,%s,%s,%s,%s)',
|
||||
(identity, profile['mail'], password, Jsonb(profile), verified))
|
||||
if previous: transfer_guest(c, previous, identity)
|
||||
if verified: claim_orders(c, identity, profile)
|
||||
new_session(c, response, identity)
|
||||
except UniqueViolation:
|
||||
raise HTTPException(409, 'Já existe uma conta com este e-mail. Entre com a sua senha.')
|
||||
@@ -142,7 +169,7 @@ def register_verify(body: SignupCode, request: Request, response: Response):
|
||||
if refusal:
|
||||
raise refusal
|
||||
return create_account(profile=signup['profile'], password=signup['password_hash'],
|
||||
previous=current(request), response=response)
|
||||
previous=current(request), response=response, verified=True)
|
||||
|
||||
|
||||
@router.get('/api/account/register/dev-code')
|
||||
@@ -197,6 +224,9 @@ def login(body: Login, request: Request, response: Response):
|
||||
if previous:
|
||||
transfer_guest(c, previous, account['id'])
|
||||
c.execute('DELETE FROM dtf_local.sessions WHERE id=%s', (previous['id'],))
|
||||
# Orders bought without the account since, on any device.
|
||||
if account['email_verified']:
|
||||
claim_orders(c, account['id'], account['profile'])
|
||||
new_session(c, response, account['id'])
|
||||
audit('customer_login_success', account=str(account['id']))
|
||||
return {'customer': account['profile']}
|
||||
@@ -266,7 +296,9 @@ def apply_email(identity, row, email):
|
||||
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', (email, Jsonb(profile), identity))
|
||||
c.execute('UPDATE dtf_local.accounts SET email=%s, profile=%s, email_verified=true WHERE id=%s',
|
||||
(email, Jsonb(profile), identity))
|
||||
claim_orders(c, identity, profile)
|
||||
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'
|
||||
|
||||
@@ -35,6 +35,9 @@ CREATE TABLE IF NOT EXISTS dtf_local.accounts (
|
||||
id uuid PRIMARY KEY, email text UNIQUE NOT NULL, password_hash text NOT NULL,
|
||||
profile jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
-- Confirmed with an e-mailed code (at signup or on a change): only then does
|
||||
-- the account bring guest orders placed with its CPF/CNPJ and e-mail.
|
||||
ALTER TABLE dtf_local.accounts ADD COLUMN IF NOT EXISTS email_verified boolean NOT NULL DEFAULT false;
|
||||
CREATE TABLE IF NOT EXISTS dtf_local.sessions (
|
||||
id uuid PRIMARY KEY, owner uuid NOT NULL,
|
||||
expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days'
|
||||
@@ -301,6 +304,10 @@ CREATE TABLE IF NOT EXISTS dtf_local.email_changes (
|
||||
sent_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL,
|
||||
sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0, done_at timestamptz
|
||||
);
|
||||
-- Accounts confirmed by a code before email_verified existed.
|
||||
UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified AND (
|
||||
EXISTS (SELECT 1 FROM dtf_local.account_signups s WHERE s.email=a.email AND s.done_at IS NOT NULL)
|
||||
OR EXISTS (SELECT 1 FROM dtf_local.email_changes e WHERE e.account_id=a.id AND e.new_email=a.email AND e.done_at IS NOT NULL));
|
||||
-- E-mail kinds: a password-recovery link, a code, the notice that an account
|
||||
-- already exists, the notice of a changed e-mail, the team's alerts and a test.
|
||||
-- Defined once, here: the schema runs on every start, and an earlier, narrower
|
||||
|
||||
@@ -336,9 +336,11 @@ as references and are not imported or started by Compose.
|
||||
- The customer portal at `/portal.html` supports local registration/login,
|
||||
stronger scrypt password hashing with legacy-hash upgrade, revocable HttpOnly
|
||||
sessions, owned order history/status, secure active
|
||||
file downloads, and correction uploads. Registration/login can claim only the
|
||||
current guest session's records, never orders found by email or CPF/CNPJ. Email
|
||||
verification and password recovery are not implemented.
|
||||
file downloads, and correction uploads. Registration/login claims the current
|
||||
guest session's records and, once the account's e-mail is confirmed with a
|
||||
code, every guest order placed with the account's CPF/CNPJ and e-mail
|
||||
together, from any browser; never by CPF/CNPJ alone. Signup and e-mail
|
||||
changes are confirmed by an e-mailed code; password recovery by a link.
|
||||
- Unfinished carts (including File blobs) recover from IndexedDB for 24 hours in
|
||||
the same browser, scoped to the guest/account identity. Recovered items can be
|
||||
removed/replaced or joined by new items; in-place reconstruction of the artwork
|
||||
|
||||
@@ -310,9 +310,64 @@ def alerts(tag):
|
||||
return order['id'], quote['id']
|
||||
|
||||
|
||||
def guest_order(document, address, made):
|
||||
"""An order bought without an account, in a browser of its own."""
|
||||
browser = Client()
|
||||
browser.call('/session')
|
||||
uid = upload_bytes(browser, b'GUEST ORDER ARTWORK')
|
||||
item = item_spec('file', '1.2', 0, uid)
|
||||
quote = browser.call('/quotes', {'request_key': str(uuid4()), 'items': [item],
|
||||
'customer': {'cnpj': document, 'zap': '16999990000', 'mail': address},
|
||||
'freight': {'service': 'pickup'}})
|
||||
approved_quote(browser, quote, [item])
|
||||
order = browser.call('/orders/dev-paid', {'quote_id': quote['id']})
|
||||
made.append((order['id'], quote['id']))
|
||||
return order['id'], uid
|
||||
|
||||
|
||||
def claimed_orders(tag, made):
|
||||
"""A confirmed account brings the orders bought without it with its CPF or
|
||||
CNPJ and e-mail, from any browser; a CPF alone or an unconfirmed e-mail
|
||||
brings nothing."""
|
||||
cpf, address = '52998224725', f'comprador-{tag}@example.test'
|
||||
mine, art = guest_order('529.982.247-25', address.upper(), made)
|
||||
other_mail, _ = guest_order(cpf, f'outro-{tag}@example.test', made)
|
||||
other_document, _ = guest_order(CNPJ, address, made)
|
||||
# Someone who knows the CPF, with an e-mail of their own: nothing.
|
||||
stranger = Client()
|
||||
stranger.call('/session')
|
||||
register(stranger, {'cnpj': cpf, 'zap': '16999990000', 'mail': f'curioso-{tag}@example.test'}, PASSWORD)
|
||||
assert stranger.call('/customer/orders?page=1&size=10')['items'] == []
|
||||
# The customer, on another computer: the order comes with its cart and files.
|
||||
customer = Client()
|
||||
customer.call('/session')
|
||||
register(customer, {'cnpj': cpf, 'zap': '16999990000', 'mail': address}, PASSWORD)
|
||||
listed = lambda client: {e['id'] for e in client.call('/customer/orders?page=1&size=10')['items'] if e['kind'] == 'order'}
|
||||
assert listed(customer) == {mine}, listed(customer)
|
||||
customer.call('/customer/orders/' + mine)
|
||||
with db.connect() as c:
|
||||
account = c.execute('SELECT id,email_verified FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone()
|
||||
assert account['email_verified']
|
||||
assert c.execute('SELECT owner FROM dtf_local.uploads WHERE id=%s', (art,)).fetchone()['owner'] == account['id']
|
||||
owners = {r['id']: r['owner'] for r in c.execute('SELECT id,owner FROM dtf_local.orders WHERE id=ANY(%s)',
|
||||
([other_mail, other_document],)).fetchall()}
|
||||
assert account['id'] not in owners.values()
|
||||
# Bought later without signing in, elsewhere: it comes at the next sign-in.
|
||||
later, _ = guest_order(cpf, address, made)
|
||||
Client().call('/account/login', {'email': address, 'password': PASSWORD})
|
||||
assert listed(customer) == {mine, later}
|
||||
# An account whose e-mail was never confirmed brings nothing.
|
||||
with db.connect() as c:
|
||||
c.execute('UPDATE dtf_local.accounts SET email_verified=false WHERE id=%s', (account['id'],))
|
||||
unconfirmed, _ = guest_order(cpf, address, made)
|
||||
Client().call('/account/login', {'email': address, 'password': PASSWORD})
|
||||
assert unconfirmed not in listed(customer)
|
||||
|
||||
|
||||
def run():
|
||||
tag = secrets.token_hex(3)
|
||||
order = quote = None
|
||||
made = []
|
||||
with db.connect() as c:
|
||||
# The recovery's per-source limit would make a second run within 15 minutes fail.
|
||||
c.execute('DELETE FROM dtf_local.login_attempts')
|
||||
@@ -322,16 +377,17 @@ def run():
|
||||
email_change(tag)
|
||||
smtp_delivery(tag)
|
||||
order, quote = alerts(tag)
|
||||
made.append((order, quote))
|
||||
claimed_orders(tag, made)
|
||||
print('PASS: password recovery by a one-time link, signup and e-mail changes confirmed by an e-mailed code, '
|
||||
'SMTP delivery and retry, alerts to who asked for them')
|
||||
'SMTP delivery and retry, alerts to who asked for them, guest orders brought by CPF/CNPJ and e-mail')
|
||||
finally:
|
||||
with db.connect() as c:
|
||||
if order:
|
||||
for table in ('movements', 'print_files'):
|
||||
for order, quote in made:
|
||||
for table in ('movements', 'print_files', 'order_files'):
|
||||
c.execute(f'DELETE FROM dtf_local.{table} WHERE order_id=%s', (order,))
|
||||
c.execute('DELETE FROM dtf_local.outbox WHERE event_key LIKE %s', (f'{order}:%',))
|
||||
c.execute('DELETE FROM dtf_local.orders WHERE id=%s', (order,))
|
||||
if quote:
|
||||
c.execute('DELETE FROM dtf_local.payment_intents WHERE quote_id=%s', (quote,))
|
||||
c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,))
|
||||
c.execute("DELETE FROM dtf_local.mail_queue WHERE to_addr LIKE %s OR kind='test'", (f'%-{tag}@example.test',))
|
||||
|
||||
Reference in New Issue
Block a user