Files
fitme3070.pt/views/auth/login.php
T
andreandClaude Opus 5.5 0e8b53f620 feat(audit): platform-tools atualizado (12f26fd) e registo de auditoria ligado
- shared/platform-tools: ea3616a → 12f26fd (27 commits). Traz o módulo de
  audit (f761d99, o pin da frota), «manter sessão iniciada», o registo de
  segurança da frota (o gancho que o login já tinha passa a funcionar) e a
  correção do IP do cliente encontrada nesta auditoria (último X-Forwarded-For
  / X-Real-IP), promovida ao partilhado. client_ip() da app delega nele.
- config/functions_audit.php: audit() sobre platform_audit(); tabela
  audit_log criada no primeiro uso, segredos ocultados, nunca parte a ação.
- Registado: login, falha de login, bloqueio por excesso de tentativas,
  logout, pedidos de recuperação, mudança/definição de palavra-passe,
  registo e criação de utilizadores, convites, perfil (antes/depois), todas
  as definições (db_update_setting, com valor anterior), cada passo da
  lixeira (apagar, restaurar, eliminar de vez) e ações nas mensagens.
- Sistema → Auditoria (views/sysadmin/audit.php), só sysadmin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 07:28:13 +01:00

129 lines
5.9 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). A cópia
// vendorizada ainda não traz esse ficheiro (ver VENDORED.md); até ao próximo
// refresh isto não faz nada.
$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]);
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);
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>
<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'; ?>