From 95be624cca6d7123709794d9fe96f89efc4577b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Wed, 14 Oct 2026 15:18:37 -0300 Subject: [PATCH] feat: a new account is confirmed with a code sent to its e-mail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Anyone could open an account on someone else's e-mail. Now "Criar conta" e-mails a 6-digit code, and the account exists only once it is entered: one big field that takes a paste or the phone's autofill and confirms by itself, "Reenviar código" after 60 s, "Trocar e-mail", and the sign-in box hidden meanwhile. Security: 15 minutes per code, 5 wrong attempts, at most 5 codes, limits per address and per source; the password is hashed at the first step and the code stored only as a hash, its e-mail erased once sent. An address that already has an account gets the same answer on screen and a "você já tem conta" e-mail instead of a code, so the form does not reveal who is registered. Without e-mail (MAIL_ADAPTER=off) the account is created at once, as before. The browser test reads the code from a local-only endpoint that exists only where e-mail stays in the log. Tested: mail_test (wrong, locked, resent, expired codes, existing address, erasure after SMTP), the full suite and the browser test in a CI-style stack, and the screens in Brave on desktop and phone. Co-Authored-By: Claude Opus 5.5 --- app/api/customer.py | 124 ++++++++++++++++++++++++++++++++++++++--- app/core/models.py | 7 +++ app/mail.py | 19 ++++--- app/schema.sql | 17 +++++- app/worker.py | 2 + docs/CONTEXT.md | 7 +++ ops/demo_customer.py | 2 +- tests/browser_test.mjs | 5 ++ tests/mail_test.py | 92 +++++++++++++++++++++++++++--- tests/smoke_test.py | 13 +++++ tests/workflow_test.py | 4 +- web/portal.css | 4 ++ web/portal.html | 15 ++++- web/portal.js | 55 +++++++++++++++++- 14 files changed, 337 insertions(+), 29 deletions(-) diff --git a/app/api/customer.py b/app/api/customer.py index bd8b21e..4518236 100644 --- a/app/api/customer.py +++ b/app/api/customer.py @@ -15,9 +15,9 @@ 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) + ProfileUpdate, Register, SignupCode, SignupResend) from .. import mail -from ..runtime import PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage +from ..runtime import ENVIRONMENT, PUBLIC_ORIGIN, STATES, file_rows, order_code, owned_order, storage from ..scanning import require_clean router = APIRouter() @@ -28,6 +28,36 @@ def current(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() @@ -35,15 +65,32 @@ def register(body: Register, request: Request, response: Response): # Registration attempts keep counting against the email, as before. login_failed(email) previous = current(request) - encoded = password_hash(body.password) - identity = uuid4() 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: - 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.') - c.execute('INSERT INTO dtf_local.accounts(id,email,password_hash,profile) VALUES(%s,%s,%s,%s)', (identity,email,encoded,Jsonb(profile))) + 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: @@ -51,6 +98,69 @@ def register(body: Register, request: Request, response: Response): 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() diff --git a/app/core/models.py b/app/core/models.py index cf8029b..169506e 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -254,6 +254,13 @@ class PasswordChange(StrictModel): current: str = Field(min_length=1, max_length=128) new: str = Field(min_length=12, max_length=128) +class SignupCode(StrictModel): + signup: UUID + code: str = Field(pattern=r'^[0-9]{6}$') + +class SignupResend(StrictModel): + signup: UUID + class ForgotPassword(StrictModel): email: str = Field(min_length=3, max_length=254) diff --git a/app/mail.py b/app/mail.py index db38d9b..2b24728 100644 --- a/app/mail.py +++ b/app/mail.py @@ -11,8 +11,8 @@ retried. MAIL_ADAPTER chooses where they go: stack, where there is no mail server; smtp sent through SMTP_HOST as MAIL_FROM. -A recovery message carries a link that signs in, so its text is erased once it -is sent (or once the link expired unsent); only its subject stays as a record. +A recovery link or a signup code lets someone in, so its text is erased once +it is sent (or once it expired unsent); only its subject stays as a record. """ import logging import os @@ -25,6 +25,10 @@ ADAPTER = os.environ.get('MAIL_ADAPTER', 'off') # Every Kanban link in an alert points here. KANBAN_ORIGIN = os.environ.get('KANBAN_ORIGIN', '').rstrip('/') RESET_MINUTES = 60 +CODE_MINUTES = 15 +# Messages that let someone in: their text is erased once sent, or once they +# expired unsent (minutes). +SECRET_KINDS = {'reset': RESET_MINUTES, 'code': CODE_MINUTES} MAX_ATTEMPTS = 12 log = logging.getLogger('dtf.mail') @@ -131,10 +135,11 @@ def send_pending(connect, limit=5, ids=None): if not configured(): return with connect() as c: - # A recovery link that expired before it could be sent is useless. - c.execute(f"""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now() - WHERE kind='reset' AND sent_at IS NULL AND failed_at IS NULL - AND created_at < now() - interval '{RESET_MINUTES} minutes'""") + # A link or a code that expired before it could be sent is useless. + for kind, minutes in SECRET_KINDS.items(): + c.execute("""UPDATE dtf_local.mail_queue SET body='', last_error='expirou sem ser enviado', failed_at=now() + WHERE kind=%s AND sent_at IS NULL AND failed_at IS NULL + AND created_at < now() - %s * interval '1 minute'""", (kind, minutes)) rows = c.execute('''SELECT * FROM dtf_local.mail_queue WHERE sent_at IS NULL AND failed_at IS NULL AND (id = ANY(%s) OR (%s::bigint[] IS NULL AND available_at <= now())) ORDER BY id FOR UPDATE SKIP LOCKED LIMIT %s''', (ids or [], ids, limit)).fetchall() @@ -151,7 +156,7 @@ def send_pending(connect, limit=5, ids=None): log.warning('mail to %s failed (attempt %s): %s', row['to_addr'], attempts, exc) continue # The local log keeps the text so the link can be followed by hand. - erase = row['kind'] == 'reset' and ADAPTER != 'log' + erase = row['kind'] in SECRET_KINDS and ADAPTER != 'log' c.execute('''UPDATE dtf_local.mail_queue SET sent_at=now(), attempts=attempts+1, last_error=NULL, body=CASE WHEN %s THEN '' ELSE body END WHERE id=%s''', (erase, row['id'])) diff --git a/app/schema.sql b/app/schema.sql index d87f3a2..6583d85 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -260,7 +260,7 @@ CREATE TABLE IF NOT EXISTS dtf_local.operator_machines ( -- E-mail (app/mail.py): queued in the transaction that caused it, sent by the -- worker. A recovery message's text is erased once sent; the subject stays. CREATE TABLE IF NOT EXISTS dtf_local.mail_queue ( - id bigserial PRIMARY KEY, kind text NOT NULL CHECK(kind IN ('reset','alert','test')), + id bigserial PRIMARY KEY, kind text NOT NULL, to_addr text NOT NULL, subject text NOT NULL, body text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), available_at timestamptz NOT NULL DEFAULT now(), attempts int NOT NULL DEFAULT 0, last_error text, sent_at timestamptz, failed_at timestamptz @@ -282,3 +282,18 @@ ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS alerts boolean NOT NULL ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_since timestamptz; ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_by text; ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_note text; + +-- E-mail kinds: a password-recovery link, a signup code, the notice that an +-- account already exists, the team's alerts and a test. +ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check; +ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check + CHECK(kind IN ('reset','code','account','alert','test')); +-- A signup waiting for its e-mail code. The account is created only when the +-- code is entered; the password is already hashed and the code only hashed. +CREATE TABLE IF NOT EXISTS dtf_local.account_signups ( + id uuid PRIMARY KEY, email text NOT NULL, profile jsonb NOT NULL, password_hash text NOT NULL, + code_hash text, created_at timestamptz NOT NULL DEFAULT now(), 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 +); +CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at); diff --git a/app/worker.py b/app/worker.py index 458cf6d..3694d9d 100644 --- a/app/worker.py +++ b/app/worker.py @@ -42,6 +42,8 @@ def cleanup(): c.execute('UPDATE dtf_local.uploads SET purged_at=now() WHERE id=%s', (row['id'],)) c.execute('DELETE FROM dtf_local.upload_thumbnails WHERE upload_id=%s', (row['id'],)) c.execute('DELETE FROM dtf_local.sessions WHERE expires_at<=now()') + c.execute("DELETE FROM dtf_local.account_signups WHERE created_atportal.eval('!document.getElementById("fCodigo").hidden'),'signup code step'); + await portal.eval(`fetch('/api/account/register/dev-code?signup='+signup).then(r=>r.json()).then(({code})=>{ + const field=document.getElementById('codigo');field.value=code;field.dispatchEvent(new Event('input'));})`); await waitFor(()=>portal.eval('document.getElementById("auth").hidden && location.pathname==="/conta"'),'customer registration'); await waitFor(async()=> (await portal.text()).includes('Finalizado'),'overview shows the last order'); await portal.click('[data-view="dados"]'); diff --git a/tests/mail_test.py b/tests/mail_test.py index 8573e08..2c80e18 100644 --- a/tests/mail_test.py +++ b/tests/mail_test.py @@ -16,7 +16,7 @@ from uuid import uuid4 from app import mail from app.core import db -from tests.smoke_test import Client, approved_quote, item_spec, upload_bytes +from tests.smoke_test import Client, approved_quote, item_spec, register, upload_bytes CNPJ = '11222333000181' PASSWORD = 'senha-antiga-12345' @@ -70,8 +70,7 @@ def recovery(tag): address = f'cliente-{tag}@example.test' customer = Client() assert customer.call('/session')['password_recovery'] is True - customer.call('/account/register', {'customer': {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address}, - 'password': PASSWORD}) + register(customer, {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address}, PASSWORD) # Signed in elsewhere with the old password: the reset signs that out. elsewhere = Client() elsewhere.call('/session') @@ -119,6 +118,78 @@ def recovery(tag): return address +def code_of(c, address): + body = c.execute("SELECT body FROM dtf_local.mail_queue WHERE kind='code' AND to_addr=%s ORDER BY id DESC LIMIT 1", + (address,)).fetchone()['body'] + return re.search(r'\b(\d{6})\b', body).group(1) + + +def signup(tag): + """The account exists only once the code sent to the address is entered.""" + address = f'novo-{tag}@example.test' + customer = {'cnpj': CNPJ, 'zap': '16999990000', 'mail': address} + browser = Client() + browser.call('/session') + started = browser.call('/account/register', {'customer': customer, 'password': PASSWORD}) + assert started['email'] == address and started['minutes'] == 15 and started['verify'], started + assert browser.call('/account/me')['customer'] is None + with db.connect() as c: + assert not c.execute('SELECT 1 FROM dtf_local.accounts WHERE email=%s', (address,)).fetchone() + first = code_of(c, address) + # The password is stored hashed from the first step. + assert c.execute('SELECT password_hash FROM dtf_local.account_signups WHERE id=%s', + (started['verify'],)).fetchone()['password_hash'].startswith('scrypt-v2$') + wrong = '000000' if first != '000000' else '111111' + attempt = lambda code, expected: browser.call('/account/register/verify', {'signup': started['verify'], 'code': code}, + expected=expected) + assert 'Restam 4' in attempt(wrong, 400)['detail'] + attempt('12a456', 422) + # Another code only after a minute; the old one stops working. + browser.call('/account/register/resend', {'signup': started['verify']}, expected=429) + with db.connect() as c: + c.execute("UPDATE dtf_local.account_signups SET sent_at=now()-interval '2 minutes' WHERE id=%s", (started['verify'],)) + browser.call('/account/register/resend', {'signup': started['verify']}) + with db.connect() as c: + second = code_of(c, address) + if second != first: + attempt(first, 400) + # Five wrong codes lock it until a new code is asked for. + with db.connect() as c: + c.execute('UPDATE dtf_local.account_signups SET attempts=5 WHERE id=%s', (started['verify'],)) + attempt(second, 429) + with db.connect() as c: + c.execute('UPDATE dtf_local.account_signups SET attempts=0 WHERE id=%s', (started['verify'],)) + assert attempt(second, 200)['customer']['mail'] == address + assert browser.call('/account/me')['customer']['mail'] == address + attempt(second, 410) + Client().call('/account/login', {'email': address, 'password': PASSWORD}) + + # An address that already has an account: the same answer, a notice instead + # of a code, and no code opens anything. + again = Client() + again.call('/session') + other = again.call('/account/register', {'customer': customer, 'password': NEW_PASSWORD}) + assert set(other) == set(started) and other['email'] == address + with db.connect() as c: + notices = c.execute("SELECT subject FROM dtf_local.mail_queue WHERE kind='account' AND to_addr=%s", + (address,)).fetchall() + assert len(notices) == 1 and 'já tem conta' in notices[0]['subject'] + assert code_of(c, address) == second + again.call('/account/register/verify', {'signup': other['verify'], 'code': second}, expected=400) + Client().call('/account/login', {'email': address, 'password': NEW_PASSWORD}, expected=401) + + # An expired code. + late = Client() + late.call('/session') + expiring = late.call('/account/register', {'customer': {**customer, 'mail': f'tarde-{tag}@example.test'}, + 'password': PASSWORD}) + with db.connect() as c: + code = code_of(c, f'tarde-{tag}@example.test') + c.execute("UPDATE dtf_local.account_signups SET expires_at=now()-interval '1 second' WHERE id=%s", + (expiring['verify'],)) + late.call('/account/register/verify', {'signup': expiring['verify'], 'code': code}, expected=410) + + def smtp_delivery(tag): """The worker's SMTP path, against a server of our own.""" sink = Sink() @@ -135,17 +206,19 @@ def smtp_delivery(tag): VALUES(%s,%s,%s,%s,now()+interval '1 hour') RETURNING id''', (kind, to, subject, body)).fetchone()['id'] for kind, subject, body in (('reset', 'Crie uma nova senha · DTF Dropstar', 'link secreto ção'), - ('alert', 'Pedido pago', 'olá equipe'))] + ('alert', 'Pedido pago', 'olá equipe'), + ('code', '123456 é o seu código', 'código 123456'))] mail.send_pending(db.connect, ids=ids) - assert len(sink.messages) == 2, sink.messages + assert len(sink.messages) == 3, sink.messages rcpt, first = sink.messages[0] assert to in rcpt[0] and first['Subject'] == 'Crie uma nova senha · DTF Dropstar' assert first['From'] == 'DTF Dropstar ' assert first.get_content().strip() == 'link secreto ção' with db.connect() as c: - sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'alert')} - # The recovery's text is erased once sent; an alert keeps its own. + sent = {r['kind']: r for r in queued(c, to, 'reset') + queued(c, to, 'alert') + queued(c, to, 'code')} + # A recovery link or a signup code is erased once sent; an alert keeps its text. assert sent['reset']['sent_at'] and sent['reset']['body'] == '' + assert sent['code']['sent_at'] and sent['code']['body'] == '' assert sent['alert']['sent_at'] and sent['alert']['body'] == 'olá equipe' # A server that does not answer: retried later, with the error kept. @@ -211,9 +284,11 @@ def run(): c.execute('DELETE FROM dtf_local.login_attempts') try: recovery(tag) + signup(tag) smtp_delivery(tag) order, quote = alerts(tag) - print('PASS: password recovery by a one-time link, SMTP delivery and retry, alerts to who asked for them') + print('PASS: password recovery by a one-time link, signup confirmed by an e-mailed code, ' + 'SMTP delivery and retry, alerts to who asked for them') finally: with db.connect() as c: if order: @@ -225,6 +300,7 @@ def run(): 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',)) + c.execute('DELETE FROM dtf_local.account_signups WHERE email LIKE %s', (f'%-{tag}@example.test',)) c.execute('DELETE FROM dtf_local.accounts WHERE email LIKE %s', (f'%-{tag}@example.test',)) c.execute('DELETE FROM dtf_local.operators WHERE email LIKE %s', (f'%-{tag}@example.test',)) c.execute('DELETE FROM dtf_local.login_attempts') diff --git a/tests/smoke_test.py b/tests/smoke_test.py index 2f16042..8e1d818 100644 --- a/tests/smoke_test.py +++ b/tests/smoke_test.py @@ -54,6 +54,19 @@ class Client: if exc.code!=expected:raise AssertionError((path,exc.code,exc.read().decode())) from exc return json.load(exc) +def register(client, customer, password): + """Create an account as the Site does: with e-mail on, the code sent to the + address (kept readable on the local stack) confirms it.""" + started=client.call('/account/register',{'customer':customer,'password':password}) + if 'verify' not in started: + return started + from app.core import db + with db.connect() as c: + body=c.execute("SELECT body FROM dtf_local.mail_queue WHERE kind='code' AND to_addr=%s ORDER BY id DESC LIMIT 1", + (customer['mail'].strip().lower(),)).fetchone()['body'] + code=next(word for word in body.split() if word.isdigit() and len(word)==6) + return client.call('/account/register/verify',{'signup':started['verify'],'code':code}) + def wait_scan(client, uid, operator=False, expected='clean'): prefix='/operator/uploads' if operator else '/uploads' deadline=time.monotonic()+150 diff --git a/tests/workflow_test.py b/tests/workflow_test.py index 0c44267..6293ad4 100644 --- a/tests/workflow_test.py +++ b/tests/workflow_test.py @@ -1,7 +1,7 @@ """Customer identity, correction and final-file trust boundaries against local stack.""" from uuid import uuid4 from urllib.request import urlopen -from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec +from tests.smoke_test import Client, approved_quote, upload_bytes, item_spec, register def run(): customer=Client();other=Client();customer.call('/session');other.call('/session') @@ -13,7 +13,7 @@ def run(): order=customer.call('/orders/dev-paid',{'quote_id':q['id']});oid=order['id'] before=list(customer.jar)[0].value password='local-test-password-'+uuid4().hex - customer.call('/account/register',{'customer':profile,'password':password}) + register(customer,profile,password) assert customer.call('/account/me')['customer']['mail']==profile['mail'] assert [e['id'] for e in customer.call('/customer/orders')['items'] if e['kind']=='order'][0]==oid # The list filters, pages and counts by group. diff --git a/web/portal.css b/web/portal.css index 2fa1cd5..168cf4e 100644 --- a/web/portal.css +++ b/web/portal.css @@ -27,6 +27,10 @@ button:disabled{opacity:.6;cursor:default} .bloco{display:flex;flex-direction:column;margin-bottom:16px;padding:22px;border:1px solid var(--linha);border-radius:var(--raio);background:#fff} .bloco h2{font-size:20px;font-weight:800} .nota2{margin:4px 0 8px;font-size:14.5px;color:var(--fraco)} +/* The signup code: one field, big and spaced, so it reads as six digits. */ +.bloco input.codigo{height:60px;font-size:30px;font-weight:700;letter-spacing:.45em;text-align:center;font-variant-numeric:tabular-nums;padding-left:.45em} +.codigoAcoes{display:flex;flex-wrap:wrap;gap:4px 22px} +#fCodigo{max-width:520px} .nota2 a{color:var(--laranja-escuro)} .bloco label{margin:10px 0 5px;font-size:14px;font-weight:600;color:var(--texto2)} .bloco label .obs{font-weight:400;color:var(--fraco)} diff --git a/web/portal.html b/web/portal.html index a9298ce..a3ec991 100644 --- a/web/portal.html +++ b/web/portal.html @@ -66,7 +66,20 @@ - + + + + diff --git a/web/portal.js b/web/portal.js index 8ae4d52..655b483 100644 --- a/web/portal.js +++ b/web/portal.js @@ -333,7 +333,10 @@ async function migrateGuestCart(previous,next){ } async function authenticate(path,body,destino){ const previous=scope,guest=!conta; - const r=await api(path,body);forgetCheckout(); + const r=await api(path,body); + // With e-mail on, a new account waits for the code sent to the address. + if(r.verify){pedeCodigo(r);return;} + forgetCheckout(); const next=(await api('/session')).cart_scope;scope=next; if(guest)try{await migrateGuestCart(previous,next);}catch{aviso('Não foi possível transferir o carrinho salvo neste navegador.',true);} conta=r.customer;$('quem').textContent=conta.mail; @@ -342,7 +345,55 @@ async function authenticate(path,body,destino){ await mostra(); } $('login').onsubmit=async event=>{event.preventDefault();try{await authenticate('/account/login',{email:$('email').value,password:$('password').value});}catch(e){aviso(e.message,true);}}; -$('register').onsubmit=async event=>{event.preventDefault();try{await authenticate('/account/register',{customer:{cnpj:$('cnpj').value,zap:$('phone').value,mail:$('register-email').value},password:$('register-password').value});}catch(e){aviso(e.status===422?'Confira o CNPJ, o WhatsApp e o e-mail. A senha precisa ter 12 caracteres ou mais.':e.message,true);}}; +$('register').onsubmit=async event=>{event.preventDefault();$('criarConta').disabled=true; + try{await authenticate('/account/register',{customer:{cnpj:$('cnpj').value,zap:$('phone').value,mail:$('register-email').value},password:$('register-password').value});} + catch(e){aviso(e.status===422?'Confira o CNPJ, o WhatsApp e o e-mail. A senha precisa ter 12 caracteres ou mais.':e.message,true);} + finally{$('criarConta').disabled=false;}}; + +// Signup code: the account is created only once the code e-mailed to the +// address is entered. Six digits confirm by themselves. +let signup=null, reenvioTimer=null; +function pedeCodigo(r){ + signup=r.verify; + $('codigoMail').textContent=r.email;$('codigoMin').textContent=r.minutes; + // Only the code on screen while it is awaited: "Entrar" comes back with "Trocar e-mail". + $('register').hidden=true;$('login').hidden=true;$('fEsqueci').hidden=true;$('fCodigo').hidden=false;$('codigo').value=''; + aviso('');contagem(r.resend_seconds);$('codigo').focus(); +} +function contagem(segundos){ + clearInterval(reenvioTimer); + const b=$('reenviar');let falta=segundos; + const pinta=()=>{b.disabled=falta>0;b.textContent=falta>0?'Reenviar código ('+falta+' s)':'Reenviar código';}; + pinta();reenvioTimer=setInterval(()=>{falta--;pinta();if(falta<=0)clearInterval(reenvioTimer);},1000); +} +function voltaCadastro(){ + clearInterval(reenvioTimer);signup=null; + $('fCodigo').hidden=true;$('register').hidden=false;$('login').hidden=false;$('register-email').focus(); +} +$('codigo').addEventListener('input',e=>{ + e.target.value=e.target.value.replace(/\D/g,'').slice(0,6); + if(e.target.value.length===6&&!$('codigoOk').disabled)$('fCodigo').requestSubmit(); +}); +$('fCodigo').onsubmit=async event=>{ + event.preventDefault();$('codigoOk').disabled=true; + try{ + await authenticate('/account/register/verify',{signup,code:$('codigo').value},'/conta'); + clearInterval(reenvioTimer);signup=null;$('fCodigo').hidden=true;$('register').hidden=false;$('login').hidden=false; + $('register-password').value='';aviso('Conta criada. Bem-vindo!'); + }catch(e){ + aviso(e.status===422?'O código tem 6 números.':e.message,true); + $('codigo').select(); + // Expired or used: the field stays, and "Reenviar código" is the way on. + if(e.status===410||e.status===429){$('reenviar').disabled=false;$('reenviar').textContent='Reenviar código';clearInterval(reenvioTimer);} + }finally{$('codigoOk').disabled=false;} +}; +$('reenviar').onclick=async()=>{ + $('reenviar').disabled=true; + try{const r=await api('/account/register/resend',{signup});aviso('Enviamos um código novo para '+$('codigoMail').textContent+'.'); + contagem(r.resend_seconds);$('codigo').value='';$('codigo').focus();} + catch(e){aviso(e.message,true);if(e.status===410)voltaCadastro();else $('reenviar').disabled=false;} +}; +$('trocarMail').onclick=()=>{aviso('');voltaCadastro();}; // Password recovery: a link by e-mail when the server sends e-mail, // otherwise the WhatsApp. The link arrives in the address's fragment. let recovery=false, resetToken='';