fix(auth): B-2.2 review fixes — Tailwind path + WCAG + race + flash + tests

C-1: Add templates/register.html (and templates/auth/**) to tailwind.config.js
content array so utility classes used by the signup template don't get purged
on next build. Rebuilt static/css/marketing.css; verified text-brand-navy/90
and min-h-[calc(100vh-62px)] are now compiled.

I-1: Replace flash() calls for missing required consents with WTForms
field-level errors (form.consent_cgu.errors.append / form.consent_confidentialite
.errors.append). Errors render inline next to each consent checkbox via
{% if form.consent_cgu.errors %}<p role="alert">…</p>{% endif %}. Prevents
session-backed flash messages from leaking across unrelated navigations.

I-2: Wrap user creation + flush in IntegrityError retry loop (max 5 attempts);
import IntegrityError from sqlalchemy.exc. Absorbs the inherent race between
_generate_unique_username's lookup and the subsequent flush under concurrent
signups. Added docstring note to _generate_unique_username explaining the
wrapper.

I-3: Move db.create_all() inside the try/finally in
test_signup_route_csrf_enforced so WTF_CSRF_ENABLED is restored even if
table creation fails.

I-4: Pin test_signup_rejects_duplicate_email assertion to status_code == 200
(WTForms validate_email raises ValidationError → form fails validation →
fall-through to default 200 render_template).

I-5: Add id="password-help" to the password help paragraph and
aria-describedby="password-help" to the password input so screen readers
announce the password requirements when the field is focused.

I-6: Bump flash banner text colors from -700/-800 to -900 variants
(text-amber-900, text-blue-900, text-red-900, text-green-900) for safer
WCAG 2.2 AA contrast against the -50 backgrounds. Same bump applied to the
new consent and password inline error renders.
This commit is contained in:
Allison
2026-04-27 22:43:00 -04:00
parent d2fc1f03ed
commit 3b324ad0b9
5 changed files with 75 additions and 27 deletions

View File

@@ -15,6 +15,7 @@ from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, SelectField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from werkzeug.security import generate_password_hash, check_password_hash
from sqlalchemy.exc import IntegrityError
from urllib.parse import urlparse, urljoin
import markdown
@@ -202,6 +203,11 @@ def _generate_unique_username(email: str) -> str:
Append a numeric suffix on collision. User.username is required, unique,
and capped at 20 chars by the schema.
Note: this lookup-then-pick is inherently racy under concurrent signups
(two requests can both read no-collision and both pick `jane`, then one
flush wins and the other raises IntegrityError). The signup() view wraps
the call site in an IntegrityError retry loop to absorb that race.
"""
local = re.sub(r'[^a-z0-9]', '', email.split('@', 1)[0].lower())[:20] or 'user'
candidate = local
@@ -240,18 +246,21 @@ def signup():
if form.validate_on_submit():
# Hard-stop: required Loi 25 consents (CGU + politique de confidentialité).
missing_required = []
# Errors are attached to the field directly (not flashed) so that the
# message stays scoped to this form-render and never leaks to other
# navigations via the session-backed flash queue.
consent_errors_present = False
if not form.consent_cgu.data:
missing_required.append(
form.consent_cgu.errors.append(
"Vous devez accepter les conditions d'utilisation pour créer un compte."
)
consent_errors_present = True
if not form.consent_confidentialite.data:
missing_required.append(
form.consent_confidentialite.errors.append(
"Vous devez accepter la politique de confidentialité pour créer un compte."
)
if missing_required:
for msg in missing_required:
flash(msg, 'danger')
consent_errors_present = True
if consent_errors_present:
return render_template(
'register.html', title='Créer un compte', form=form
), 400
@@ -270,17 +279,29 @@ def signup():
form.password.data
).decode('utf-8')
user = User(
username=_generate_unique_username(email_normalized),
email=email_normalized,
password=hashed_password,
name=full_name,
cabinet=(form.cabinet.data.strip() or None) if form.cabinet.data else None,
ordre_pro=(form.ordre_pro.data or None),
email_verified=not is_email_verification_enabled(),
)
db.session.add(user)
db.session.flush() # need user.id for ConsentLog FK
# Username generation can race under concurrent signups (two requests
# can both pick `jane` before either flushes). Retry up to 5 times on
# unique-constraint conflict; cap iterations to prevent an infinite
# loop on pathological username churn.
max_username_attempts = 5
for attempt in range(max_username_attempts):
user = User(
username=_generate_unique_username(email_normalized),
email=email_normalized,
password=hashed_password,
name=full_name,
cabinet=(form.cabinet.data.strip() or None) if form.cabinet.data else None,
ordre_pro=(form.ordre_pro.data or None),
email_verified=not is_email_verification_enabled(),
)
db.session.add(user)
try:
db.session.flush() # need user.id for ConsentLog FK
break
except IntegrityError:
db.session.rollback()
if attempt == max_username_attempts - 1:
raise
ip = _client_ip()
ua = (request.headers.get('User-Agent') or '')[:500]