Files
fitme3070.pt/views/user/set_password.php
T
andreandClaude Opus 5 aec7b47820 Replace Andmore ID SSO with local login
fitme3070.pt delegated all authentication to hub.andmore.pt: views/auth/*
were bounce stubs, and because this domain is outside the .andmore.pt cookie
scope the real handoff was a one-time HTTPS ticket redeem. Bring identity back
in-house — passwords live in users.password_hash, which the SSO migration
never dropped.

Removed: config/sso.php, IDENTITY_MODE, every SSO_* constant and env key,
identity_is_federated() and the cookie/ticket paths in the auth views and the
public-site bootstrap. ANDMORE_ID_URL stays — it is still the hub /notify
endpoint for outbound email/SMS, which the reset mails ride on, and has
nothing to do with authentication now.

Added, ported from the fotografia.andmore.pt sibling rather than invented:

  - auth_login() with transparent password_needs_rehash upgrades and the
    last_login trail; auth_register_client(); auth_set_password(); the
    single-use 2h reset tokens.
  - Real login / register / forgot_password / reset_password pages on a new
    anonymous shell (includes/auth_header.php). includes/header.php renders
    the backoffice sidebar and a logout button, which is wrong for a visitor
    who is not signed in yet.
  - safe_return_path(), so a crafted ?return_to= cannot bounce a freshly
    authenticated user off-site.
  - Per-IP throttling on login, register and reset-request. Successes count
    too, so a guessed password cannot be parlayed into stuffing the rest of
    the user list from the same IP.
  - views/user/set_password.php: admin override for anyone whose email is
    undeliverable. Prefers mailing an invite link so the backoffice never
    handles the password. A plain admin cannot act on a sysadmin, and nobody
    can use it on themselves — self-service goes through profile.php, which
    demands the current password so a hijacked session cannot lock the owner
    out.

Accounts provisioned during the SSO era have password_hash NULL. They get in
via the reset email, or by registering again with the same address:
auth_register_client() claims a passwordless row, but only a plain `client`
one, so knowing a staff address does not let anyone self-assign the role.

users.andmore_id is deliberately left in place. No code reads it any more, but
it records which central identity each row was linked to.

Deployment: apply database/migration_20260913_local_auth.sql (password_resets
+ auth_attempts) in the SAME sysadmin session that pulls this commit — the
forgot-password flow needs that table, and after the pull a login requires a
local password.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-13 21:00:57 +01:00

122 lines
5.7 KiB
PHP

<?php
// Admin override for a user's password — the way in for anyone whose email is
// wrong or undeliverable, and for the accounts carried over from the Andmore ID
// era that have no local password yet.
//
// Two actions:
// set — write a password the admin chose, and read it out once.
// invite — mail a single-use "define a sua palavra-passe" link instead, so
// the admin never handles the password at all. Preferred.
require __DIR__ . '/../../config/db.php';
require __DIR__ . '/../../config/functions.php';
$user = require_admin();
$target = db_get_user($pdo, (int) ($_GET['id'] ?? $_POST['id'] ?? 0));
if (!$target) {
header('Location: ' . base_url('views/user/index.php'));
exit;
}
// Guards. Self-service goes through profile.php, which demands the current
// password — routing it through here would let a hijacked admin session change
// the password without knowing the old one. And a plain admin must not be able
// to take over a sysadmin account; only a sysadmin can act on a sysadmin.
$is_self = ((int) $target['id'] === (int) $user['id']);
$blocked = '';
if ($is_self) {
$blocked = 'Para alterar a sua própria palavra-passe use O meu perfil.';
} elseif ($target['role'] === 'sysadmin' && !is_sysadmin()) {
$blocked = 'Apenas um administrador de sistema pode alterar a palavra-passe de outro administrador de sistema.';
}
$error = '';
$success = '';
$plain = ''; // shown once, only for the `set` action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $blocked === '') {
csrf_check();
$action = $_POST['action'] ?? '';
if ($action === 'invite') {
if (send_password_invite_email($pdo, $target)) {
$success = 'Email enviado para ' . $target['email'] . '. O link é válido durante 2 horas.';
} else {
$error = 'Não foi possível enviar o email. Verifique as definições de notificações e tente novamente.';
}
} elseif ($action === 'set') {
$password = $_POST['password'] ?? '';
$confirm = $_POST['confirm'] ?? '';
if (strlen($password) < 8) {
$error = 'A palavra-passe deve ter pelo menos 8 caracteres.';
} elseif ($password !== $confirm) {
$error = 'As palavras-passe não coincidem.';
} else {
auth_set_password($pdo, (int) $target['id'], $password);
$plain = $password;
$success = 'Palavra-passe definida.';
}
}
$target = db_get_user($pdo, (int) $target['id']) ?? $target;
}
$page_title = 'Palavra-passe';
include __DIR__ . '/../../includes/header.php';
?>
<div class="container" style="max-width:640px;">
<h1 class="h3 mb-1">Palavra-passe</h1>
<p class="text-muted mb-4">
<?= htmlspecialchars($target['name']) ?>
· <?= htmlspecialchars($target['email']) ?>
· <span class="badge text-bg-secondary"><?= htmlspecialchars(role_label($target['role'])) ?></span>
</p>
<?php if ($blocked): ?>
<div class="alert alert-warning"><?= htmlspecialchars($blocked) ?></div>
<a class="btn btn-outline-secondary" href="<?= base_url('views/user/index.php') ?>">Voltar</a>
<?php else: ?>
<?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= htmlspecialchars($success) ?></div><?php endif; ?>
<?php if ($plain !== ''): ?>
<div class="alert alert-warning">
Comunique-a por um canal seguro e peça que a altere no primeiro acesso.
Esta é a única vez que aparece:
<code class="d-block mt-2 fs-6"><?= htmlspecialchars($plain) ?></code>
</div>
<?php endif; ?>
<div class="card shadow-sm mb-3"><div class="card-body">
<h2 class="h6">Enviar link por email</h2>
<p class="text-muted small">
A pessoa define a própria palavra-passe. Ninguém no backoffice chega a conhecê-la.
<?php if (empty($target['password_hash'])): ?>
<br><strong>Esta conta ainda não tem palavra-passe definida.</strong>
<?php endif; ?>
</p>
<form method="POST">
<?= csrf_field() ?>
<input type="hidden" name="id" value="<?= (int) $target['id'] ?>">
<input type="hidden" name="action" value="invite">
<button class="btn btn-primary"><i class="bi bi-envelope me-1"></i>Enviar link</button>
</form>
</div></div>
<form method="POST" class="card shadow-sm"><div class="card-body">
<?= csrf_field() ?>
<input type="hidden" name="id" value="<?= (int) $target['id'] ?>">
<input type="hidden" name="action" value="set">
<h2 class="h6">Definir manualmente</h2>
<p class="text-muted small">Use apenas quando o email não for uma opção.</p>
<div class="mb-3"><label class="form-label" for="sp-password">Nova palavra-passe <span class="text-muted small">(mín. 8 caracteres)</span></label>
<input type="password" class="form-control" id="sp-password" name="password" required minlength="8" autocomplete="new-password"></div>
<div class="mb-3"><label class="form-label" for="sp-confirm">Confirmar</label>
<input type="password" class="form-control" id="sp-confirm" name="confirm" required autocomplete="new-password"></div>
<button class="btn btn-outline-primary">Definir palavra-passe</button>
<a class="btn btn-link" href="<?= base_url('views/user/index.php') ?>">Voltar</a>
</div></form>
<?php endif; ?>
</div>
<?php include __DIR__ . '/../../includes/footer.php'; ?>