88 lines
2.2 KiB
PHP
88 lines
2.2 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/db.php';
|
|
|
|
const ROLE_HEAD = 'head_of_household';
|
|
const ROLE_ADULT = 'adult';
|
|
const ROLE_CHILD = 'child';
|
|
|
|
const SESSION_ACTIVE_PERSON = 'active_person_id';
|
|
const SESSION_HOH_VERIFIED = 'hoh_verified';
|
|
|
|
function startFamilyHubSession(): void {
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
}
|
|
|
|
function getActivePersonId(): ?string {
|
|
$id = $_SESSION[SESSION_ACTIVE_PERSON] ?? null;
|
|
return is_string($id) && $id !== '' ? $id : null;
|
|
}
|
|
|
|
function setSessionPerson(string $personId, bool $hohVerified): void {
|
|
$_SESSION[SESSION_ACTIVE_PERSON] = $personId;
|
|
$_SESSION[SESSION_HOH_VERIFIED] = $hohVerified;
|
|
}
|
|
|
|
function clearPersonaSession(): void {
|
|
unset($_SESSION[SESSION_ACTIVE_PERSON], $_SESSION[SESSION_HOH_VERIFIED]);
|
|
}
|
|
|
|
function isHohVerified(): bool {
|
|
return !empty($_SESSION[SESSION_HOH_VERIFIED]);
|
|
}
|
|
|
|
function findPersonById(array $people, string $id): ?array {
|
|
foreach ($people as $p) {
|
|
if (($p['id'] ?? '') === $id) {
|
|
return $p;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function getActivePerson(array $people): ?array {
|
|
$id = getActivePersonId();
|
|
if ($id === null) {
|
|
return null;
|
|
}
|
|
return findPersonById($people, $id);
|
|
}
|
|
|
|
function personRequiresPinToActivate(?array $person): bool {
|
|
if ($person === null) {
|
|
return false;
|
|
}
|
|
return ($person['role'] ?? '') === ROLE_HEAD && !empty($person['pin_hash']);
|
|
}
|
|
|
|
function assertHoHCanManagePeople(array $people): void {
|
|
if (count($people) === 0) {
|
|
return;
|
|
}
|
|
$active = getActivePerson($people);
|
|
if ($active === null || ($active['role'] ?? '') !== ROLE_HEAD || !isHohVerified()) {
|
|
http_response_code(403);
|
|
echo json_encode(['success' => false, 'error' => 'Head of household verification required.']);
|
|
exit;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param mixed $raw
|
|
* @return array<int, array<string, mixed>>
|
|
*/
|
|
function normalizePeopleList($raw): array {
|
|
if (!is_array($raw) || !array_is_list($raw)) {
|
|
return [];
|
|
}
|
|
$out = [];
|
|
foreach ($raw as $row) {
|
|
if (is_array($row) && !empty($row['id']) && is_string($row['id'])) {
|
|
$out[] = $row;
|
|
}
|
|
}
|
|
return $out;
|
|
}
|