Until now every account could do the same, and managing accounts meant running make-user.php on the server. Accounts now carry a role, and admins get a tab in the editor to create, rename, re-role, reset and delete accounts. Both issues share the same server files, so they land in one commit. #180 Roles: - Every account is admin or user. A missing or unknown role counts as user, on the server and in the client. - auth/session and auth/login return {user, role}. - Auth::requireAdmin() answers everyone else with 403. - make-user.php takes the role as a third argument. Without it an existing account keeps its role, so a password reset from the CLI never demotes an admin. - Admins see and save other users' projects like their own. Saving keeps the original owner. #179 User management: - The account menu gets "User management" (admins only) and "Plugins" (everyone). Both open the same closable tab, accounts on top and plugins below. The fixed Plugins tab is gone. - Per account: Rename, Role, Password (no old password needed) and Delete with a confirmation. "New user..." creates one. - Each account lists its projects with an Open button. - Delete is refused while the account still owns projects. - Renaming moves the projects along and ends every session of the account. transfer takes the same lock as save. - On their own row an admin can only set the password. The last admin cannot be demoted or deleted. The server enforces both. - The account rules live in AccountRules.php and accountRules.ts as pure functions, so they are testable without a server. Findings: - At 1280 px the Delete button reached past the column edge and was not clickable. The name column is flexible now, and module 49 checks the layout. - The server lets an admin delete other users' projects, but the editor has no button for it yet. Left open in the issue. Tests: - ./check.sh: 148 files, 2214 tests, exit 0 (was 147 / 2204). - New tests/php/accounts.test.php, 51 checks, plain PHP. CI runs it as its own step in the gate job, the host has no PHP. - New e2e module 49 with 18 checks. CI creates the e2e-admin account in serve.sh. Modules 14, 38, 46 and the scaffold follow the new tab. - e2e 1-16,37,38,45,46,49: all passed, 581 checks. - Counter-checks: owner on save, admin view, default role and self delete in PHP fail 7, 5, 5 and 1 checks. Unchecked requireAdmin, a wider column and the caller as owner each fail exactly their e2e check. - Check sum 1314 -> 1333 (+1 in 38, +18 in 49), computed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
30fb3a2316
commit
ceaa44e5b8
38 files changed
+1803
-138
No files matched your search
+139
-12
@@ -7,15 +7,25 @@ declare(strict_types=1);
|
||||
* Routing uses the `r` query parameter (e.g. `index.php?r=projects/abc123`) because the
|
||||
* site's nginx configuration does not pass PATH_INFO to PHP.
|
||||
*
|
||||
* GET ?r=auth/session → {user} (null while nobody is signed in)
|
||||
* POST ?r=auth/login {username,password} → {user} | 401
|
||||
* GET ?r=auth/session → {user, role} (both null while nobody is signed in)
|
||||
* POST ?r=auth/login {username,password} → {user, role} | 401
|
||||
* POST ?r=auth/logout → 204
|
||||
* POST ?r=auth/password {currentPassword,newPassword} → 204 | 401 | 422
|
||||
* (the only auth route that needs a session; ends the account's
|
||||
* other logins, keeps the one asking)
|
||||
*
|
||||
* Everything below needs a signed-in user (401 otherwise), and projects belong to one: a project
|
||||
* of somebody else answers like one that is not there.
|
||||
* of somebody else answers like one that is not there – unless the one asking is an administrator
|
||||
* (#179), who reads, saves and deletes it like their own; a save keeps its owner.
|
||||
*
|
||||
* Administrators only (403 for everybody else, #180):
|
||||
*
|
||||
* GET ?r=users → [{username,role,createdAt,projects:[{id,name,revision,updatedAt}]}]
|
||||
* POST ?r=users {username,password,role} → 201 {username,role,createdAt} | 409 | 422
|
||||
* PATCH ?r=users/{name} {username?,role?,password?} → {username,role,createdAt} | 404 | 409 | 422
|
||||
* DELETE ?r=users/{name} → 204 | 404 | 409 (still owns projects) | 422
|
||||
* (renaming or deleting signs the account out everywhere; a new
|
||||
* password ends its other sessions)
|
||||
*
|
||||
* GET ?r=projects → [{id,name,revision,updatedAt}]
|
||||
* POST ?r=projects {name} → {id,name,revision,updatedAt,project}
|
||||
@@ -47,6 +57,7 @@ declare(strict_types=1);
|
||||
* `data/sounds/` and `data/pixels/` as static files; the API only writes them.
|
||||
*/
|
||||
|
||||
require __DIR__ . '/lib/AccountRules.php';
|
||||
require __DIR__ . '/lib/Auth.php';
|
||||
require __DIR__ . '/lib/FontStore.php';
|
||||
require __DIR__ . '/lib/OriginalName.php';
|
||||
@@ -86,7 +97,8 @@ function routeAuth(array $parts, string $method, Auth $auth): never
|
||||
}
|
||||
// Always 200, never 401: "nobody is signed in" is an answer, not a failure, and the
|
||||
// login screen asks this before it can know either way.
|
||||
Response::json(['user' => $auth->user()]);
|
||||
$user = $auth->user();
|
||||
Response::json(['user' => $user, 'role' => $user === null ? null : $auth->role($user)]);
|
||||
}
|
||||
|
||||
if ($what === 'login') {
|
||||
@@ -99,7 +111,7 @@ function routeAuth(array $parts, string $method, Auth $auth): never
|
||||
// One message for both halves: which of the two was wrong is the attacker's question.
|
||||
Response::error('Wrong user name or password', 401);
|
||||
}
|
||||
Response::json(['user' => $user]);
|
||||
Response::json(['user' => $user, 'role' => $auth->role($user)]);
|
||||
}
|
||||
|
||||
if ($what === 'password') {
|
||||
@@ -132,9 +144,9 @@ function routeAuth(array $parts, string $method, Auth $auth): never
|
||||
}
|
||||
|
||||
/** @param list<string> $parts */
|
||||
function routeProjects(array $parts, string $method, string $owner): never
|
||||
function routeProjects(array $parts, string $method, string $owner, bool $seesAll): never
|
||||
{
|
||||
$store = new Store(dirname(__DIR__) . '/data/projects', $owner);
|
||||
$store = new Store(dirname(__DIR__) . '/data/projects', $owner, $seesAll);
|
||||
|
||||
if (count($parts) === 1) {
|
||||
if ($method === 'GET') {
|
||||
@@ -190,6 +202,120 @@ function routeProjects(array $parts, string $method, string $owner): never
|
||||
Response::error('Method not allowed', 405);
|
||||
}
|
||||
|
||||
/** @param list<string> $parts */
|
||||
function routeUsers(array $parts, string $method, Auth $auth, UserStore $users): never
|
||||
{
|
||||
$actor = $auth->requireAdmin();
|
||||
$projects = new Store(dirname(__DIR__) . '/data/projects', $actor, true);
|
||||
$shown = static function (string $name) use ($users): array {
|
||||
foreach ($users->accounts() as $account) {
|
||||
if (strcasecmp($account['username'], $name) === 0) {
|
||||
return $account;
|
||||
}
|
||||
}
|
||||
throw new RuntimeException("Account {$name} vanished");
|
||||
};
|
||||
|
||||
if (count($parts) === 1) {
|
||||
if ($method === 'GET') {
|
||||
Response::json(array_map(
|
||||
static fn(array $a): array => $a + ['projects' => $projects->listOf($a['username'])],
|
||||
$users->accounts(),
|
||||
));
|
||||
}
|
||||
if ($method === 'POST') {
|
||||
$body = Response::body();
|
||||
$name = (string) ($body['username'] ?? '');
|
||||
$password = (string) ($body['password'] ?? '');
|
||||
$role = (string) ($body['role'] ?? 'user');
|
||||
if (!UserStore::isValidName($name)) {
|
||||
Response::error('A user name is 2–32 letters, digits, dots, dashes or underscores', 422);
|
||||
}
|
||||
if (!UserStore::isValidPassword($password)) {
|
||||
Response::error('The password needs at least ' . UserStore::MIN_PASSWORD_LENGTH . ' characters', 422);
|
||||
}
|
||||
if (!UserStore::isValidRole($role)) {
|
||||
Response::error('Unknown role', 422);
|
||||
}
|
||||
if ($users->exists($name)) {
|
||||
Response::error("The name {$name} is taken", 409);
|
||||
}
|
||||
$users->put($name, $password, $role);
|
||||
Response::json($shown($name), 201);
|
||||
}
|
||||
Response::error('Method not allowed', 405);
|
||||
}
|
||||
|
||||
$target = $parts[1];
|
||||
if (!$users->exists($target)) {
|
||||
Response::error('User not found', 404);
|
||||
}
|
||||
$role = $users->role($target);
|
||||
|
||||
if ($method === 'PATCH') {
|
||||
$body = Response::body();
|
||||
$newName = array_key_exists('username', $body) ? (string) $body['username'] : null;
|
||||
$newRole = array_key_exists('role', $body) ? (string) $body['role'] : null;
|
||||
$password = array_key_exists('password', $body) ? (string) $body['password'] : null;
|
||||
// Everything is checked before anything is written: half an edit is worse than none.
|
||||
if ($newName !== null && $newName !== $target) {
|
||||
$refusal = AccountRules::renameRefusal($actor, $target);
|
||||
if ($refusal !== null) {
|
||||
Response::error($refusal, 422);
|
||||
}
|
||||
if (!UserStore::isValidName($newName)) {
|
||||
Response::error('A user name is 2–32 letters, digits, dots, dashes or underscores', 422);
|
||||
}
|
||||
if (strcasecmp($newName, $target) !== 0 && $users->exists($newName)) {
|
||||
Response::error("The name {$newName} is taken", 409);
|
||||
}
|
||||
}
|
||||
if ($newRole !== null) {
|
||||
if (!UserStore::isValidRole($newRole)) {
|
||||
Response::error('Unknown role', 422);
|
||||
}
|
||||
$refusal = AccountRules::roleRefusal($actor, $target, $role, $newRole, $users->adminCount());
|
||||
if ($refusal !== null) {
|
||||
Response::error($refusal, 422);
|
||||
}
|
||||
}
|
||||
if ($password !== null && !UserStore::isValidPassword($password)) {
|
||||
Response::error('The password needs at least ' . UserStore::MIN_PASSWORD_LENGTH . ' characters', 422);
|
||||
}
|
||||
|
||||
if ($password !== null) {
|
||||
$auth->resetPassword($target, $password);
|
||||
}
|
||||
if ($newRole !== null && $newRole !== $role) {
|
||||
$users->setRole($target, $newRole);
|
||||
}
|
||||
$name = $shown($target)['username'];
|
||||
if ($newName !== null && $newName !== $name) {
|
||||
$users->rename($name, $newName);
|
||||
$projects->transfer($name, $newName);
|
||||
$auth->endSessionsOf($name);
|
||||
$name = $newName;
|
||||
}
|
||||
Response::json($shown($name));
|
||||
}
|
||||
|
||||
if ($method === 'DELETE') {
|
||||
$refusal = AccountRules::deleteRefusal($actor, $target, $role, $users->adminCount());
|
||||
if ($refusal !== null) {
|
||||
Response::error($refusal, 422);
|
||||
}
|
||||
$refusal = AccountRules::ownerRefusal($target, count($projects->listOf($shown($target)['username'])));
|
||||
if ($refusal !== null) {
|
||||
Response::error($refusal, 409);
|
||||
}
|
||||
$users->remove($target);
|
||||
$auth->endSessionsOf($target);
|
||||
Response::noContent();
|
||||
}
|
||||
|
||||
Response::error('Method not allowed', 405);
|
||||
}
|
||||
|
||||
/** @param list<string> $parts */
|
||||
function routeTextures(array $parts, string $method): never
|
||||
{
|
||||
@@ -350,19 +476,20 @@ try {
|
||||
Response::error('Not found', 404);
|
||||
}
|
||||
|
||||
$auth = new Auth(
|
||||
new UserStore(dirname(__DIR__) . '/data/users.json'),
|
||||
new SessionStore(dirname(__DIR__) . '/data/sessions'),
|
||||
);
|
||||
$users = new UserStore(dirname(__DIR__) . '/data/users.json');
|
||||
$auth = new Auth($users, new SessionStore(dirname(__DIR__) . '/data/sessions'));
|
||||
if ($parts[0] === 'auth') {
|
||||
routeAuth($parts, $method, $auth);
|
||||
}
|
||||
if ($parts[0] === 'users') {
|
||||
routeUsers($parts, $method, $auth, $users);
|
||||
}
|
||||
// Images, fonts, sounds, cels and plugins are shared between accounts; being signed in is still the
|
||||
// price of admission, so an uploaded file cannot be dropped in by a stranger.
|
||||
$user = $auth->require();
|
||||
|
||||
match ($parts[0]) {
|
||||
'projects' => routeProjects($parts, $method, $user),
|
||||
'projects' => routeProjects($parts, $method, $user, $auth->role($user) === 'admin'),
|
||||
'textures' => routeTextures($parts, $method),
|
||||
'fonts' => routeFonts($parts, $method),
|
||||
'sounds' => routeSounds($parts, $method),
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* What an administrator may not do to an account (#179), as plain functions of the facts: each
|
||||
* answers the refusal to send back, or null when the change may go ahead.
|
||||
*
|
||||
* An administrator's own name and role are off limits here – renaming yourself would end the
|
||||
* session you are using, and demoting yourself would lock you out of the page you are on. Their
|
||||
* own password may be set like anyone's.
|
||||
*/
|
||||
final class AccountRules
|
||||
{
|
||||
public static function renameRefusal(string $actor, string $target): ?string
|
||||
{
|
||||
return strcasecmp($actor, $target) === 0 ? 'You cannot rename your own account' : null;
|
||||
}
|
||||
|
||||
public static function roleRefusal(string $actor, string $target, string $currentRole, string $newRole, int $admins): ?string
|
||||
{
|
||||
if (strcasecmp($actor, $target) === 0 && $newRole !== $currentRole) {
|
||||
return 'You cannot change your own role';
|
||||
}
|
||||
if ($currentRole === 'admin' && $newRole !== 'admin' && $admins <= 1) {
|
||||
return 'The last administrator cannot be demoted';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function deleteRefusal(string $actor, string $target, string $role, int $admins): ?string
|
||||
{
|
||||
if (strcasecmp($actor, $target) === 0) {
|
||||
return 'You cannot delete your own account';
|
||||
}
|
||||
if ($role === 'admin' && $admins <= 1) {
|
||||
return 'The last administrator cannot be deleted';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* An account with projects is not deleted: they would belong to nobody and vanish from every
|
||||
* list. The administrator deletes them first – there is no way to hand them on yet.
|
||||
*/
|
||||
public static function ownerRefusal(string $target, int $projects): ?string
|
||||
{
|
||||
if ($projects === 0) {
|
||||
return null;
|
||||
}
|
||||
return "{$target} still owns {$projects} " . ($projects === 1 ? 'project' : 'projects');
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,26 @@ final class Auth
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* The signed-in user if they are an administrator (#180), else 401 or 403. Every route that
|
||||
* may do more than a user goes through here: the editor only hides what it may not offer, the
|
||||
* decision is made on this side.
|
||||
*/
|
||||
public function requireAdmin(): string
|
||||
{
|
||||
$user = $this->require();
|
||||
if ($this->users->role($user) !== 'admin') {
|
||||
Response::error('Administrators only', 403);
|
||||
}
|
||||
return $user;
|
||||
}
|
||||
|
||||
/** `admin` or `user`; the session answer carries it so the editor knows what to offer. */
|
||||
public function role(string $user): string
|
||||
{
|
||||
return $this->users->role($user);
|
||||
}
|
||||
|
||||
/** Checks the pair, starts a session and sets the cookie. Null when the pair is wrong. */
|
||||
public function logIn(string $username, string $password): ?string
|
||||
{
|
||||
@@ -68,6 +88,22 @@ final class Auth
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* An administrator sets somebody's password without knowing the old one (#179). That account's
|
||||
* sessions end with it, except the one asking when it is their own.
|
||||
*/
|
||||
public function resetPassword(string $user, string $new): void
|
||||
{
|
||||
$this->users->put($user, $new);
|
||||
$this->sessions->destroyAllFor($user, $this->token());
|
||||
}
|
||||
|
||||
/** Signs an account out everywhere – it was renamed or deleted, and its sessions carry the old name. */
|
||||
public function endSessionsOf(string $user): void
|
||||
{
|
||||
$this->sessions->destroyAllFor($user);
|
||||
}
|
||||
|
||||
private function token(): string
|
||||
{
|
||||
return (string) ($_COOKIE[SessionStore::COOKIE] ?? '');
|
||||
|
||||
+63
-17
@@ -19,12 +19,17 @@ final class StaleRevisionException extends RuntimeException
|
||||
* A store belongs to one signed-in user: it lists, reads and writes only the projects whose
|
||||
* `owner` is that user. Someone else's project is answered as missing rather than as forbidden,
|
||||
* because "this id exists" is already more than a stranger should learn.
|
||||
*
|
||||
* An administrator's store (`$seesAll`, #179) reads, writes and deletes every project as if it
|
||||
* were their own, and a save keeps the owner it found. The list stays their own: the others are
|
||||
* reached through the user management, one account at a time.
|
||||
*/
|
||||
final class Store
|
||||
{
|
||||
public function __construct(
|
||||
private readonly string $dir,
|
||||
private readonly string $owner,
|
||||
private readonly bool $seesAll = false,
|
||||
) {
|
||||
if (!is_dir($this->dir) && !mkdir($this->dir, 0775, true) && !is_dir($this->dir)) {
|
||||
throw new RuntimeException("Cannot create data directory {$this->dir}");
|
||||
@@ -43,11 +48,17 @@ final class Store
|
||||
|
||||
/** @return list<array{id:string,name:string,revision:int,updatedAt:string}> */
|
||||
public function list(): array
|
||||
{
|
||||
return $this->listOf($this->owner);
|
||||
}
|
||||
|
||||
/** @return list<array{id:string,name:string,revision:int,updatedAt:string}> */
|
||||
public function listOf(string $owner): array
|
||||
{
|
||||
$items = [];
|
||||
foreach (glob($this->dir . '/*.json') ?: [] as $file) {
|
||||
$doc = $this->readFile($file);
|
||||
if ($doc === null || $doc['owner'] !== $this->owner) {
|
||||
if ($doc === null || $doc['owner'] !== $owner) {
|
||||
continue;
|
||||
}
|
||||
$items[] = [
|
||||
@@ -81,7 +92,7 @@ final class Store
|
||||
'assets' => [],
|
||||
'activeSceneId' => '',
|
||||
];
|
||||
$doc = $this->document($id, $name, 1, $project);
|
||||
$doc = $this->document($id, $name, $this->owner, 1, $project);
|
||||
$this->writeFile($this->path($id), $doc);
|
||||
return $doc;
|
||||
}
|
||||
@@ -94,11 +105,7 @@ final class Store
|
||||
public function save(string $id, int $expectedRevision, array $project): ?array
|
||||
{
|
||||
$path = $this->path($id);
|
||||
$lock = fopen($path . '.lock', 'c');
|
||||
if ($lock === false || !flock($lock, LOCK_EX)) {
|
||||
throw new RuntimeException('Cannot acquire project lock');
|
||||
}
|
||||
try {
|
||||
return $this->locked($path, function () use ($path, $id, $expectedRevision, $project): ?array {
|
||||
$current = $this->own($this->readFile($path));
|
||||
if ($current === null) {
|
||||
return null;
|
||||
@@ -108,14 +115,10 @@ final class Store
|
||||
}
|
||||
$name = is_string($project['name'] ?? null) && $project['name'] !== '' ? $project['name'] : $current['name'];
|
||||
$project['id'] = $id;
|
||||
$doc = $this->document($id, $name, $expectedRevision + 1, $project);
|
||||
$doc = $this->document($id, $name, $current['owner'], $expectedRevision + 1, $project);
|
||||
$this->writeFile($path, $doc);
|
||||
return $doc;
|
||||
} finally {
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
@unlink($path . '.lock');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function delete(string $id): bool
|
||||
@@ -127,10 +130,53 @@ final class Store
|
||||
return file_exists($path) && unlink($path);
|
||||
}
|
||||
|
||||
/** The document, or null when it belongs to someone else. */
|
||||
/**
|
||||
* Hands every project of `$from` to `$to` – what renaming an account does, since the name is
|
||||
* the owner. Revision and date stay: nothing in the project changed, and a tab that has one of
|
||||
* them open must not be told it was modified elsewhere. Returns how many moved.
|
||||
*/
|
||||
public function transfer(string $from, string $to): int
|
||||
{
|
||||
$moved = 0;
|
||||
foreach (glob($this->dir . '/*.json') ?: [] as $file) {
|
||||
// Under the save lock, or a save running at the same time writes the old owner back.
|
||||
$moved += $this->locked($file, function () use ($file, $from, $to): int {
|
||||
$doc = $this->readFile($file);
|
||||
if ($doc === null || $doc['owner'] !== $from) {
|
||||
return 0;
|
||||
}
|
||||
$doc['owner'] = $to;
|
||||
$this->writeFile($file, $doc);
|
||||
return 1;
|
||||
});
|
||||
}
|
||||
return $moved;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param callable():T $work
|
||||
* @return T
|
||||
*/
|
||||
private function locked(string $path, callable $work): mixed
|
||||
{
|
||||
$lock = fopen($path . '.lock', 'c');
|
||||
if ($lock === false || !flock($lock, LOCK_EX)) {
|
||||
throw new RuntimeException('Cannot acquire project lock');
|
||||
}
|
||||
try {
|
||||
return $work();
|
||||
} finally {
|
||||
flock($lock, LOCK_UN);
|
||||
fclose($lock);
|
||||
@unlink($path . '.lock');
|
||||
}
|
||||
}
|
||||
|
||||
/** The document, or null when it belongs to someone else and this store does not see everything. */
|
||||
private function own(?array $doc): ?array
|
||||
{
|
||||
return $doc !== null && $doc['owner'] === $this->owner ? $doc : null;
|
||||
return $doc !== null && ($this->seesAll || $doc['owner'] === $this->owner) ? $doc : null;
|
||||
}
|
||||
|
||||
private function path(string $id): string
|
||||
@@ -138,12 +184,12 @@ final class Store
|
||||
return $this->dir . '/' . $id . '.json';
|
||||
}
|
||||
|
||||
private function document(string $id, string $name, int $revision, array $project): array
|
||||
private function document(string $id, string $name, string $owner, int $revision, array $project): array
|
||||
{
|
||||
return [
|
||||
'id' => $id,
|
||||
'name' => $name,
|
||||
'owner' => $this->owner,
|
||||
'owner' => $owner,
|
||||
'revision' => $revision,
|
||||
'updatedAt' => gmdate('c'),
|
||||
'project' => $project,
|
||||
|
||||
+128
-21
@@ -2,11 +2,15 @@
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* The accounts, as one JSON file: `data/users.json` holding `{username, password}` per user,
|
||||
* where `password` is a hash from `password_hash` – the plain one is never stored.
|
||||
* The accounts, as one JSON file: `data/users.json` holding `{username, password, role, createdAt}`
|
||||
* per user, where `password` is a hash from `password_hash` – the plain one is never stored.
|
||||
*
|
||||
* Accounts are made from the command line (`tools/make-user.php`), not through the API: signing
|
||||
* up is a follow-up of its own, and until it exists nobody may create an account over the wire.
|
||||
* An entry without `role` is a `user` (#180): the weaker of the two is what a missing field means,
|
||||
* so a hand-written file never hands out rights by accident. `createdAt` is missing on the accounts
|
||||
* from before #179 and stays empty for them.
|
||||
*
|
||||
* Accounts are made from the command line (`tools/make-user.php`) or by an administrator through
|
||||
* the `users` routes (#179); nobody can sign up over the wire.
|
||||
*/
|
||||
final class UserStore
|
||||
{
|
||||
@@ -17,6 +21,8 @@ final class UserStore
|
||||
*/
|
||||
public const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
public const ROLES = ['admin', 'user'];
|
||||
|
||||
public function __construct(private readonly string $file) {}
|
||||
|
||||
public static function isValidName(string $name): bool
|
||||
@@ -29,6 +35,11 @@ final class UserStore
|
||||
return strlen($password) >= self::MIN_PASSWORD_LENGTH;
|
||||
}
|
||||
|
||||
public static function isValidRole(string $role): bool
|
||||
{
|
||||
return in_array($role, self::ROLES, true);
|
||||
}
|
||||
|
||||
/** The name as stored, or null when the pair does not match an account. */
|
||||
public function verify(string $username, string $password): ?string
|
||||
{
|
||||
@@ -44,30 +55,119 @@ final class UserStore
|
||||
return $this->find($username) !== null;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function names(): array
|
||||
/** `user` for an account that does not exist, the same as for one without a role. */
|
||||
public function role(string $username): string
|
||||
{
|
||||
return array_map(static fn(array $u): string => $u['username'], $this->all());
|
||||
return $this->find($username)['role'] ?? 'user';
|
||||
}
|
||||
|
||||
/** Adds the account or replaces the password of one that is already there. */
|
||||
public function put(string $username, string $password): void
|
||||
/**
|
||||
* Every account as the API may show it – never the hash.
|
||||
*
|
||||
* @return list<array{username:string,role:string,createdAt:string}>
|
||||
*/
|
||||
public function accounts(): array
|
||||
{
|
||||
return array_map(
|
||||
static fn(array $u): array => [
|
||||
'username' => $u['username'],
|
||||
'role' => $u['role'],
|
||||
'createdAt' => $u['createdAt'],
|
||||
],
|
||||
$this->all(),
|
||||
);
|
||||
}
|
||||
|
||||
public function adminCount(): int
|
||||
{
|
||||
return count(array_filter($this->all(), static fn(array $u): bool => $u['role'] === 'admin'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the account or replaces the password of one that is already there. Without `$role` a new
|
||||
* account is a `user` and an existing one keeps what it has, so resetting a password from the
|
||||
* command line never demotes an administrator.
|
||||
*/
|
||||
public function put(string $username, string $password, ?string $role = null): void
|
||||
{
|
||||
if (!self::isValidName($username)) {
|
||||
throw new InvalidArgumentException("Invalid user name: {$username}");
|
||||
}
|
||||
$users = array_values(
|
||||
array_filter(
|
||||
$this->all(),
|
||||
static fn(array $u): bool => strcasecmp($u['username'], $username) !== 0,
|
||||
),
|
||||
);
|
||||
$users[] = ['username' => $username, 'password' => password_hash($password, PASSWORD_DEFAULT)];
|
||||
usort($users, static fn(array $a, array $b): int => strcmp($a['username'], $b['username']));
|
||||
if ($role !== null && !self::isValidRole($role)) {
|
||||
throw new InvalidArgumentException("Invalid role: {$role}");
|
||||
}
|
||||
$existing = $this->find($username);
|
||||
$users = $this->without($username);
|
||||
$users[] = [
|
||||
'username' => $existing['username'] ?? $username,
|
||||
'password' => password_hash($password, PASSWORD_DEFAULT),
|
||||
'role' => $role ?? $existing['role'] ?? 'user',
|
||||
'createdAt' => $existing !== null ? $existing['createdAt'] : gmdate('c'),
|
||||
];
|
||||
$this->write($users);
|
||||
}
|
||||
|
||||
/** @return array{username:string,password:string}|null */
|
||||
/** @return bool False when there is no such account. */
|
||||
public function setRole(string $username, string $role): bool
|
||||
{
|
||||
if (!self::isValidRole($role)) {
|
||||
throw new InvalidArgumentException("Invalid role: {$role}");
|
||||
}
|
||||
return $this->change($username, static fn(array $u): array => ['role' => $role] + $u);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives an account a new name. Only the name: the projects that carry the old one as `owner`
|
||||
* and the sessions that do are the caller's to move (see `Store::transfer`).
|
||||
*
|
||||
* @return bool False when there is no such account.
|
||||
* @throws InvalidArgumentException when the new name is invalid or taken by another account.
|
||||
*/
|
||||
public function rename(string $from, string $to): bool
|
||||
{
|
||||
if (!self::isValidName($to)) {
|
||||
throw new InvalidArgumentException("Invalid user name: {$to}");
|
||||
}
|
||||
$other = $this->find($to);
|
||||
// Only a change of case is the same account; any other match is somebody else's name.
|
||||
if ($other !== null && strcasecmp($other['username'], $from) !== 0) {
|
||||
throw new InvalidArgumentException("The name {$to} is taken");
|
||||
}
|
||||
return $this->change($from, static fn(array $u): array => ['username' => $to] + $u);
|
||||
}
|
||||
|
||||
/** @return bool False when there is no such account. */
|
||||
public function remove(string $username): bool
|
||||
{
|
||||
if ($this->find($username) === null) {
|
||||
return false;
|
||||
}
|
||||
$this->write($this->without($username));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @param callable(array):array $edit */
|
||||
private function change(string $username, callable $edit): bool
|
||||
{
|
||||
$user = $this->find($username);
|
||||
if ($user === null) {
|
||||
return false;
|
||||
}
|
||||
$users = $this->without($username);
|
||||
$users[] = $edit($user);
|
||||
$this->write($users);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** @return list<array{username:string,password:string,role:string,createdAt:string}> */
|
||||
private function without(string $username): array
|
||||
{
|
||||
return array_values(
|
||||
array_filter($this->all(), static fn(array $u): bool => strcasecmp($u['username'], $username) !== 0),
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array{username:string,password:string,role:string,createdAt:string}|null */
|
||||
private function find(string $username): ?array
|
||||
{
|
||||
foreach ($this->all() as $user) {
|
||||
@@ -78,7 +178,7 @@ final class UserStore
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @return list<array{username:string,password:string}> */
|
||||
/** @return list<array{username:string,password:string,role:string,createdAt:string}> */
|
||||
private function all(): array
|
||||
{
|
||||
if (!is_file($this->file)) {
|
||||
@@ -92,15 +192,22 @@ final class UserStore
|
||||
$users = [];
|
||||
foreach ($data['users'] as $user) {
|
||||
if (is_array($user) && is_string($user['username'] ?? null) && is_string($user['password'] ?? null)) {
|
||||
$users[] = ['username' => $user['username'], 'password' => $user['password']];
|
||||
$role = $user['role'] ?? null;
|
||||
$users[] = [
|
||||
'username' => $user['username'],
|
||||
'password' => $user['password'],
|
||||
'role' => is_string($role) && self::isValidRole($role) ? $role : 'user',
|
||||
'createdAt' => is_string($user['createdAt'] ?? null) ? $user['createdAt'] : '',
|
||||
];
|
||||
}
|
||||
}
|
||||
return $users;
|
||||
}
|
||||
|
||||
/** @param list<array{username:string,password:string}> $users */
|
||||
/** @param list<array{username:string,password:string,role:string,createdAt:string}> $users */
|
||||
private function write(array $users): void
|
||||
{
|
||||
usort($users, static fn(array $a, array $b): int => strcmp($a['username'], $b['username']));
|
||||
$dir = dirname($this->file);
|
||||
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
|
||||
throw new RuntimeException("Cannot create data directory {$dir}");
|
||||
|
||||
Reference in new issue
Block a user