diff --git a/app/security.py b/app/security.py index f09014a..c97b05d 100644 --- a/app/security.py +++ b/app/security.py @@ -8,9 +8,14 @@ import secrets ITERATIONS = 310_000 +MIN_PASSWORD_LENGTH = 4 + + def hash_password(password: str) -> str: - if len(password) < 8: - raise ValueError("A palavra-passe tem de ter pelo menos 8 caracteres") + if len(password.strip()) < MIN_PASSWORD_LENGTH: + raise ValueError( + f"A palavra-passe tem de ter pelo menos {MIN_PASSWORD_LENGTH} caracteres" + ) salt = os.urandom(16) digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, ITERATIONS) return f"pbkdf2_sha256${ITERATIONS}${salt.hex()}${digest.hex()}" diff --git a/app/static/app.css b/app/static/app.css index 1c3d35c..5d5162a 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -55,6 +55,9 @@ a{color:var(--brand-dark)} .small{padding:5px 9px;font-size:.88rem} .compact{gap:4px} .link-button{padding:0;font-weight:400} +.account-link{display:flex;flex-direction:column;line-height:1.15;padding:5px 11px;border:1px solid var(--line);border-radius:999px;font-weight:600;text-decoration:none;color:var(--text)} +.account-link .muted{font-size:.78rem;font-weight:500} +.account-link:hover{border-color:var(--brand);color:var(--brand-deep)} .form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px} .form-col{display:flex;flex-direction:column;gap:14px} .form-grid fieldset{margin:0;border:1px solid var(--line);border-radius:10px;padding:12px 14px 14px;min-width:0} @@ -123,5 +126,5 @@ th{font-size:.8rem;text-transform:uppercase;color:var(--muted);background:#fff7f } @media(max-width:430px){ .brand-name{font-size:1rem} - .account span{display:none} + .account-link .name-text{display:none} } diff --git a/app/templates/account.html b/app/templates/account.html new file mode 100644 index 0000000..987b211 --- /dev/null +++ b/app/templates/account.html @@ -0,0 +1,32 @@ +{% extends "base.html" %} +{% block title %}A minha conta · {{ settings.app_name }}{% endblock %} +{% block content %} +
+
+

Rota

+

A minha conta

+

{{ current_user.name }}{% if current_user.username %} · @{{ current_user.username }}{% endif %}

+
+
+ +
+

Alterar palavra-passe

+ {% if current_user.can_login %} +
+ + + + +
+
+ {% else %} +

A sua conta ainda não tem palavra-passe. Peça a um administrador que a defina para poder entrar.

+ {% endif %} +
+{% endblock %} diff --git a/app/templates/admin_users.html b/app/templates/admin_users.html index 1f1d8bf..0ce8848 100644 --- a/app/templates/admin_users.html +++ b/app/templates/admin_users.html @@ -16,7 +16,7 @@
Acesso (opcional) - +
@@ -35,7 +35,7 @@
Acesso - +
diff --git a/app/templates/base.html b/app/templates/base.html index 37f5279..84df975 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -28,7 +28,14 @@ {% if current_user %}
+ {% if current_user.can_login %} + + {{ current_user.name }} + @{{ current_user.username }} + + {% else %} {{ current_user.name }} + {% endif %}
diff --git a/app/web.py b/app/web.py index d95df2f..3be514e 100644 --- a/app/web.py +++ b/app/web.py @@ -231,6 +231,51 @@ def calendar_feed( ) +@router.get("/account", response_class=HTMLResponse) +def account_page(request: Request, db: Session = Depends(get_db)): + """The password editor lives on its own page, reached by clicking the username.""" + _require_user(request, db) + return request.app.state.templates.TemplateResponse( + request=request, + name="account.html", + context=_context(request, db), + ) + + +@router.post("/account") +def account_password( + request: Request, + current_password: str = Form(""), + new_password: str = Form(""), + confirm_password: str = Form(""), + csrf_token: str = Form(...), + db: Session = Depends(get_db), +): + """A person changes their own password from `/account`.""" + _check_csrf(request, csrf_token) + user = _require_user(request, db) + if not user.can_login: + _flash(request, "A sua conta ainda não tem palavra-passe.", "error") + return _redirect(_safe_back(request, "/")) + if not verify_password(current_password, user.password_hash): + _flash(request, "A palavra-passe atual não está correta.", "error") + return _redirect(_safe_back(request, "/")) + if new_password != confirm_password: + _flash(request, "As duas palavras-passe não são iguais.", "error") + return _redirect(_safe_back(request, "/")) + if new_password == current_password: + _flash(request, "A nova palavra-passe é igual à atual.", "error") + return _redirect(_safe_back(request, "/")) + try: + user.password_hash = hash_password(new_password) + except ValueError as exc: + _flash(request, str(exc), "error") + return _redirect(_safe_back(request, "/")) + db.commit() + _flash(request, "Palavra-passe alterada.") + return _redirect(_safe_back(request, "/")) + + @router.get("/calendar", response_class=HTMLResponse) def calendar_page(request: Request, db: Session = Depends(get_db)): """The links to subscribe, kept off the rota so that page stays about the shifts.""" diff --git a/docs/DOMAIN.md b/docs/DOMAIN.md index 99108e0..b2972b4 100644 --- a/docs/DOMAIN.md +++ b/docs/DOMAIN.md @@ -69,6 +69,8 @@ Every assignment on a lunch schedule page has a **Regenerate** button. An admini - A username and password are optional, but they are all-or-nothing: a person can either sign in or be rota-only. A username without a password (or the reverse) is not allowed, and a person without credentials can never sign in. - A username, when set, is unique. - Rota-only people can be assigned by an administrator, appear in rotations, and can be named as the target of a change request, but cannot accept it; an administrator completes the transfer on the schedule's own configuration page. +- Any password of at least four characters is accepted; there is no complexity rule. +- A signed-in person reaches their account through their username in the top bar, which opens `/account`: it asks for the current password and the new one twice. Accounts without a password have no username and no link, and need an administrator to set one. - A person cannot remove their own login. - An administrator can remove a person permanently from `/admin/users`, after a confirmation page that lists the impact. A person who still holds any assignment, past ones included, cannot be removed: those shifts must first be handed over, so the record of who worked each date stays intact. SQLite cascades are not enforced by the application, so the removal clears the remaining references explicitly: night-pattern days lose their person, rotation positions are deleted, that person's own change requests are deleted and the ones that merely targeted or accepted by them lose those references, and notification logs keep their history without the person. - Nobody may remove their own account or the last remaining administrator. The people page only shows the remove button for the people who pass these checks; the endpoints enforce them again. Deactivating is the non-destructive alternative. diff --git a/tests/test_users.py b/tests/test_users.py index 6a40b86..165c71a 100644 --- a/tests/test_users.py +++ b/tests/test_users.py @@ -10,7 +10,7 @@ from sqlalchemy.pool import StaticPool from app.database import Base, get_db from app.main import app from app.models import User -from app.security import hash_password +from app.security import hash_password, verify_password CSRF_RE = re.compile(r'name="csrf_token" value="([^"]+)"') @@ -136,12 +136,12 @@ def test_admin_can_give_and_remove_a_login(client, db, admin): person.id, name="Rota Only", username="rotarota", - new_password="a-secure-password", + new_password="abcd", ) assert db.get(User, person.id).can_login is True client.post("/logout", data={"csrf_token": csrf(client, "/")}) - assert "Bem-vindo(a), Rota Only." in login(client, "rotarota", "a-secure-password") + assert "Bem-vindo(a), Rota Only." in login(client, "rotarota", "abcd") login(client, "admin", "admin-password") page = update_person(client, person.id, name="Rota Only") @@ -155,7 +155,7 @@ def test_username_must_stay_unique(client, db, admin): person = db.scalar(select(User).where(User.name == "Rota Only")) page = update_person( - client, person.id, name="Rota Only", username="admin", new_password="a-secure-password" + client, person.id, name="Rota Only", username="admin", new_password="abcd" ) assert "Esse nome de utilizador já está a ser usado." in page assert db.get(User, person.id).can_login is False @@ -343,3 +343,82 @@ def test_admins_cannot_remove_themselves_or_the_last_admin(client, db, admin): client.post(f"/admin/users/{second.id}/delete", data={"csrf_token": token}) assert db.get(User, second.id) is None assert db.get(User, admin.id) is not None + + +def test_a_person_changes_their_own_password(client, db, admin): + login(client, "admin", "admin-password") + add_person(client, name="Member") + person = db.scalar(select(User).where(User.name == "Member")) + update_person(client, person.id, name="Member", username="member", new_password="abcd") + + # the username in the bar is the button that opens the password editor + assert '