Files
fitme3070.pt/views/auth/login.php
T
andreandClaude Sonnet 5 300655b92a feat(auth): «Manter sessão iniciada» (auditoria: item Médio)
config/functions_remember.php reimplementa o desenho selector/validator
do platform-tools (functions_remember.php) localmente, porque esta app
tem autenticação própria e não passa por functions_auth.php partilhado:
selector em claro e UNIQUE indexa a linha, só o SHA-256 do validator
fica na BD, hash_equals() na comparação, rotação a cada uso, e um
validator que não bate certo revoga TODOS os tokens da conta (sinal de
cookie em circulação).

- Checkbox no login; remember_issue() só quando marcada.
- require_login() tenta remember_resume() antes de mandar para o login.
- logout.php apaga só o token deste browser (não a conta toda).
- auth_set_password() revoga todos os tokens da conta — uma password
  nova não pode deixar um cookie antigo continuar a entrar.

Migração: database/migration_20260925_remember_me.sql (remember_tokens).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-25 13:01:18 +01:00

141 lines
6.6 KiB
PHP

<?php
// Local login form. This install owns its passwords (users.password_hash);
// there is no identity provider in front of it.
//
// 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_login($pdo, $_POST['email'] ?? '', $_POST['password'] ?? '');
if ($user) {
auth_set_session($user);
if (!empty($_POST['remember'])) {
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;
}
$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'; ?>