feat(auth): migra login/sessão/roles para o auth partilhado (auditoria 1.3)
config/db.php liga-se com 'auth' => 'shared' em vez de 'own': login, sessão, papéis e guardas passam a correr sobre shared/platform-tools/functions_auth.php (auth_attempt/auth_login/ auth_at_least/auth_is/auth_session_start/auth_remember_*) em vez da lógica local duplicada. Os ~30 ficheiros em views/ que chamam require_login()/require_admin()/require_staff()/require_sysadmin()/ is_admin()/etc. não mudam — só o que está por baixo dessas funções. - roles: staff=40, client=10 registados para preservar a hierarquia sysadmin>admin>staff>client que os antigos in_array() garantiam. `users` já tinha exactamente as colunas por omissão do auth_schema(), não foi preciso mapear nada. - sessão: o bloco manual de ini_set()/session_start() em config/db.php foi substituído pela opção 'session' do platform_connect() — mesmo nome de cookie (FIT_SESS), mesmo SameSite=Lax, secure/httponly passam a ser geridos por auth_session_start(). - «Manter sessão iniciada»: config/functions_remember.php (a reimplementação local do selector/validator) foi eliminado a favor do módulo partilhado (auth_remember_issue/resume/clear via 'remember' => true), que já cobria o mesmo desenho. - auth_attempts: tinha (ip, scope) do throttle próprio da app (config/functions_throttle.php), não o `identifier` que o throttle partilhado exige. Migração aditiva (migration_20260925_shared_auth_attempts.sql) torna a tabela conforme sem tocar no throttle da app, que continua a ser o único usado para login/registo/recuperação — o throttle partilhado não é chamado, para não duplicar a mesma defesa com duas contagens. - last_login_ua (sem equivalente partilhado) passa a ser gravado por fit_stamp_login_ua(), chamado a seguir a auth_login(). Testado ponta-a-ponta num contentor scratch na VPS (site-fitme:8.4, cópia da BD de produção + migração aplicada): visitante anónimo é redirigido, password errada dá o mesmo erro genérico e conta para o throttle (bloqueia à 5ª tentativa, 429), login correcto regenera a sessão, grava last_login_at/ip/ua, audita "auth.login" e (com "lembrar-me") emite o cookie am_remember; esse cookie sozinho, numa sessão nova, repõe a sessão certa com rotação do validator; logout limpa sessão+cookie+token e audita "auth.logout"; platform.php (guard=require_sysadmin) e views/admin/dashboard.php respondem 302 sem sessão e 200 com sessão de sysadmin. php -l limpo em todos os ficheiros alterados. Migração já aplicada em produção (aditiva). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ccc644ac0d
commit
fa87aabb87
9 files changed
+196
-274
No files matched your search
+18
-5
@@ -1,6 +1,16 @@
|
||||
<?php
|
||||
// Local login form. This install owns its passwords (users.password_hash);
|
||||
// there is no identity provider in front of it.
|
||||
// there is no identity provider in front of it. Credential check and session
|
||||
// establishment go through shared/platform-tools/functions_auth.php
|
||||
// (auth_attempt()/auth_login()) since auditoria 2026-09-24 ponto 1.3 — see
|
||||
// config/db.php for the connection and the reasoning on auth_attempts.
|
||||
//
|
||||
// The throttle below is still fitme's own (config/functions_throttle.php),
|
||||
// not the shared auth_throttle_check()/auth_throttle_hit(): it already covers
|
||||
// login (two tiers: per-IP and per-account) plus register/forgot_password,
|
||||
// which the shared throttle doesn't touch at all, so switching only the login
|
||||
// scope over would mean running two different throttles for the same form
|
||||
// with no reduction in code. Kept as one system.
|
||||
//
|
||||
// Carries through ?return_to=/path, set by require_login(), so the visitor
|
||||
// lands back on the page they originally asked for.
|
||||
@@ -54,13 +64,16 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
throttle_record($pdo, 'login');
|
||||
throttle_record($pdo, 'login_acct', $acct);
|
||||
|
||||
$user = auth_login($pdo, $_POST['email'] ?? '', $_POST['password'] ?? '');
|
||||
$user = auth_attempt($pdo, $_POST['email'] ?? '', $_POST['password'] ?? '');
|
||||
if ($user) {
|
||||
auth_set_session($user);
|
||||
// auth_login() (shared) regenerates the session, stamps
|
||||
// last_login_at/ip and audits "auth.login" itself — no need to also
|
||||
// call the old auth_set_session()/audit() pair here.
|
||||
auth_login($pdo, $user);
|
||||
fit_stamp_login_ua($pdo, (int) $user['id']);
|
||||
if (!empty($_POST['remember'])) {
|
||||
remember_issue($pdo, (int) $user['id']);
|
||||
auth_remember_issue($pdo, (int) $user['id']);
|
||||
}
|
||||
audit('auth.login', ['target_type' => 'user', 'target_id' => (int) $user['id'], 'target_label' => (string) $user['name']]);
|
||||
header('Location: ' . base_url($destination($user['role'])));
|
||||
exit;
|
||||
}
|
||||
|
||||
+6
-13
@@ -1,25 +1,18 @@
|
||||
<?php
|
||||
// Ends the local session. Nothing to coordinate with an identity provider —
|
||||
// this install owns its own sessions.
|
||||
// this install owns its own sessions. auth_logout() (shared) audits
|
||||
// "auth.logout" (before it wipes $_SESSION), clears the session and its
|
||||
// cookie — same steps this file used to do by hand.
|
||||
|
||||
require __DIR__ . '/../../config/db.php';
|
||||
require __DIR__ . '/../../config/functions.php';
|
||||
|
||||
if (!empty($_SESSION['user_id'])) {
|
||||
audit('auth.logout', ['target_type' => 'user', 'target_id' => (int) $_SESSION['user_id']]);
|
||||
if (auth_check()) {
|
||||
// Só o token deste browser, não toda a conta: sair aqui não deve expulsar
|
||||
// a pessoa de outro dispositivo onde pediu para ficar.
|
||||
$cookie = remember_parse_cookie();
|
||||
if ($cookie !== null) remember_delete($pdo, $cookie['selector']);
|
||||
auth_remember_clear($pdo);
|
||||
}
|
||||
remember_forget_cookie();
|
||||
$_SESSION = [];
|
||||
// Drop the cookie too, so the browser doesn't keep presenting a dead id.
|
||||
if (ini_get('session.use_cookies')) {
|
||||
$p = session_get_cookie_params();
|
||||
setcookie(session_name(), '', time() - 42000, $p['path'], $p['domain'], $p['secure'], $p['httponly']);
|
||||
}
|
||||
session_destroy();
|
||||
auth_logout();
|
||||
|
||||
header('Location: ' . base_url('views/auth/login.php?loggedout=1'));
|
||||
exit;
|
||||
@@ -51,7 +51,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
// login form with credentials they just typed.
|
||||
$user = db_get_user($pdo, (int) $res['id']);
|
||||
if ($user) {
|
||||
auth_set_session($user);
|
||||
// auth_login() (shared) — same primitive views/auth/login.php
|
||||
// uses, so a fresh registration and a normal login leave the
|
||||
// session/audit trail in the same shape.
|
||||
auth_login($pdo, $user);
|
||||
header('Location: ' . base_url(post_login_destination($user['role'])));
|
||||
exit;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user