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>
154 lines
7.4 KiB
PHP
154 lines
7.4 KiB
PHP
<?php
|
|
// Local login form. This install owns its passwords (users.password_hash);
|
|
// 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.
|
|
|
|
require __DIR__ . '/../../config/db.php';
|
|
require_once __DIR__ . '/../../config/functions.php';
|
|
|
|
$return_to = safe_return_path($_GET['return_to'] ?? '');
|
|
|
|
$destination = function (string $role) use ($return_to): string {
|
|
return $return_to !== '' ? $return_to : post_login_destination($role);
|
|
};
|
|
|
|
if (!empty($_SESSION['user_id'])) {
|
|
header('Location: ' . base_url($destination($_SESSION['user']['role'] ?? '')));
|
|
exit;
|
|
}
|
|
|
|
// O login é deste site, não o partilhado, por isso é daqui que a frota fica a
|
|
// saber das falhas (platform-tools/functions_security_events.php).
|
|
$report_login = function (string $kind) use ($pdo): void {
|
|
$f = dirname(__DIR__, 2) . '/shared/platform-tools/functions_security_events.php';
|
|
if (!is_file($f)) return;
|
|
require_once $f;
|
|
platform_security_event($pdo, $kind, hub_security_mask_identifier((string) ($_POST['email'] ?? '')));
|
|
hub_security_maybe_sync($pdo);
|
|
};
|
|
|
|
$error = '';
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
csrf_check();
|
|
|
|
// Counts successes too, so a guessed password can't be parlayed into
|
|
// stuffing the rest of the user list from the same IP.
|
|
// Dois limites: por IP (5/min, 30/h) e por conta (10/min, 50/h). O da conta
|
|
// apanha um ataque distribuído a um só email; é mais largo para que um
|
|
// estranho não consiga trancar o dono com meia dúzia de tentativas.
|
|
$acct = throttle_account_key((string) ($_POST['email'] ?? ''));
|
|
if (!throttle_check($pdo, 'login') || !throttle_check($pdo, 'login_acct', 10, 50, $acct)) {
|
|
$report_login('login_throttled');
|
|
audit('auth.login_throttled', ['target_type' => 'user', 'target_label' => audit_mask_email((string) ($_POST['email'] ?? '')), 'actor' => null]);
|
|
// O throttle por si só esquece em uma hora; isto é a memória que falta —
|
|
// um IP que esgota o throttle repetidamente ao longo de dias acaba banido
|
|
// pela frota (functions_ip_ban.php, o mesmo ip_bans que já bloqueia à
|
|
// porta desde 25/09). 3 vezes em 24h = 1h de ban; 12 = permanente.
|
|
if (function_exists('platform_ip_record_offence')) {
|
|
platform_ip_record_offence($pdo, 'login_throttled');
|
|
}
|
|
throttle_block('login form');
|
|
}
|
|
throttle_record($pdo, 'login');
|
|
throttle_record($pdo, 'login_acct', $acct);
|
|
|
|
$user = auth_attempt($pdo, $_POST['email'] ?? '', $_POST['password'] ?? '');
|
|
if ($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'])) {
|
|
auth_remember_issue($pdo, (int) $user['id']);
|
|
}
|
|
header('Location: ' . base_url($destination($user['role'])));
|
|
exit;
|
|
}
|
|
$report_login('login_failed');
|
|
audit('auth.login_failed', ['target_type' => 'user', 'target_label' => audit_mask_email((string) ($_POST['email'] ?? '')), 'actor' => null]);
|
|
// Deliberately vague — doesn't reveal whether the address exists.
|
|
$error = 'Email ou palavra-passe incorretos.';
|
|
}
|
|
|
|
// Preserve the redirect intent across the POST.
|
|
$form_qs = $return_to !== '' ? ('?' . http_build_query(['return_to' => $_GET['return_to'] ?? ''])) : '';
|
|
|
|
$page_title = 'Entrar';
|
|
include __DIR__ . '/../../includes/auth_header.php';
|
|
?>
|
|
<p class="auth-sub">Entre na sua conta para continuar.</p>
|
|
|
|
<?php if ($error): ?>
|
|
<div class="alert alert-danger py-2 small mb-2"><?= htmlspecialchars($error) ?></div>
|
|
<?php // Shown on any failure — an account created by an admin (or carried
|
|
// over from the Andmore ID era) has no password yet and would
|
|
// otherwise be stuck here. Phrased so it never confirms the address
|
|
// exists. ?>
|
|
<p class="small auth-foot">
|
|
Se a sua conta foi criada por nós, ainda não tem palavra-passe definida —
|
|
use <a href="<?= htmlspecialchars(base_url('views/auth/forgot_password.php')) ?>">Esqueceu a palavra-passe?</a>
|
|
para definir uma.
|
|
</p>
|
|
<?php endif; ?>
|
|
<?php if (isset($_GET['registered'])): ?>
|
|
<div class="alert alert-success py-2 small">Conta criada. Já pode entrar.</div>
|
|
<?php endif; ?>
|
|
<?php if (isset($_GET['reset'])): ?>
|
|
<div class="alert alert-success py-2 small">Palavra-passe alterada. Entre com a nova palavra-passe.</div>
|
|
<?php endif; ?>
|
|
<?php if (isset($_GET['loggedout'])): ?>
|
|
<div class="alert alert-success py-2 small">Sessão terminada.</div>
|
|
<?php endif; ?>
|
|
|
|
<form method="POST" action="<?= htmlspecialchars('login.php' . $form_qs) ?>" novalidate>
|
|
<?= csrf_field() ?>
|
|
<div class="mb-3">
|
|
<label class="form-label" for="login-email">Email</label>
|
|
<input type="email" id="login-email" name="email" class="form-control" required autofocus
|
|
autocomplete="username" inputmode="email"
|
|
value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
|
|
</div>
|
|
<div class="mb-4">
|
|
<!-- O link de recuperação vem DEPOIS do input: dentro do <label> ficava
|
|
antes dele no DOM, e o Tab a partir do email saltava para o link
|
|
em vez de ir para a palavra-passe. -->
|
|
<label class="form-label" for="login-password">Palavra-passe</label>
|
|
<div class="input-group">
|
|
<input type="password" id="login-password" name="password" class="form-control" required
|
|
autocomplete="current-password">
|
|
<button class="btn btn-outline-secondary" type="button" tabindex="-1"
|
|
data-toggle-password="login-password" aria-label="Mostrar palavra-passe">
|
|
<i class="bi bi-eye"></i>
|
|
</button>
|
|
</div>
|
|
<div class="text-end mt-1">
|
|
<a href="<?= htmlspecialchars(base_url('views/auth/forgot_password.php')) ?>" class="small">Esqueceu a <span class="text-nowrap">palavra-passe</span>?</a>
|
|
</div>
|
|
</div>
|
|
<div class="mb-3 form-check">
|
|
<input type="checkbox" class="form-check-input" id="login-remember" name="remember" value="1">
|
|
<label class="form-check-label small" for="login-remember">Manter sessão iniciada</label>
|
|
</div>
|
|
<button type="submit" class="btn btn-primary w-100">Entrar</button>
|
|
</form>
|
|
|
|
<hr class="my-3">
|
|
<p class="text-center small mb-0 auth-foot">
|
|
Novo cliente?
|
|
<a href="<?= htmlspecialchars(base_url('views/auth/register.php')) ?>">Criar conta</a>
|
|
</p>
|
|
<?php include __DIR__ . '/../../includes/auth_footer.php'; ?>
|