Add stage 1: authentication REST API

Slim 4 + SQLite todo-list API providing email/password registration,
login, and an authenticated GET /me endpoint. Stateless HS256 JWTs,
bcrypt password hashing, uniform JSON error envelope, and a SQL
migration runner. Includes PHPUnit feature tests and stage-1 docs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-03 17:35:10 +01:00
co-authored by Claude Sonnet 5
commit 7faef6fbff
23 changed files with 4054 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
# Copy to .env and adjust as needed. All values are optional and have sane
# development defaults (see src/Support/Config.php).
# Show full exception details in API error responses. Never enable in production.
APP_DEBUG=false
# Path to the SQLite database file (absolute, or relative to the project root).
DATABASE_PATH=storage/database.sqlite
# Secret used to sign JWTs. Leave blank to auto-generate one into storage/secret.key.
JWT_SECRET=
# How long an issued token stays valid, in seconds (default: 86400 = 24h).
JWT_TTL=86400
+6
View File
@@ -0,0 +1,6 @@
/vendor/
/storage/
/.env
composer.phar
.phpunit.cache/
.phpunit.result.cache
+157
View File
@@ -0,0 +1,157 @@
# PHP Todo List
A small todo-list application: a REST API written in PHP (Slim 4) backed by an
SQLite file, plus a single-page frontend (added in a later stage).
## Status
| Stage | Scope | State |
|-------|-------|-------|
| 1 | Auth API — register, login, `GET /me` | ✅ done |
| 2 | Todo CRUD API | planned |
| 3 | Single-page frontend | planned |
## Requirements
- PHP 8.1+ with the `pdo_sqlite` and `mbstring` extensions
- [Composer](https://getcomposer.org/)
On Fedora:
```bash
sudo dnf install php-cli php-pdo php-mbstring composer
```
## Setup
```bash
composer install
cp .env.example .env # optional; sane defaults are used without it
composer migrate # creates storage/database.sqlite and its tables
```
## Running
```bash
composer serve # http://localhost:8080 (php -S localhost:8080 -t public)
```
Any web server can serve the app as long as the document root is `public/` and
unknown paths fall through to `public/index.php`.
## Configuration
All settings are optional environment variables (read from `.env` or the real
environment). See [.env.example](.env.example).
| Variable | Default | Purpose |
|----------|---------|---------|
| `APP_DEBUG` | `false` | Include exception details in error responses |
| `DATABASE_PATH` | `storage/database.sqlite` | SQLite file location |
| `JWT_SECRET` | auto-generated into `storage/secret.key` | Token signing key |
| `JWT_TTL` | `86400` | Token lifetime in seconds |
## API
Base path: `/api`. All request and response bodies are JSON; send
`Content-Type: application/json`.
### `GET /api/health`
```json
{ "status": "ok" }
```
### `POST /api/auth/register`
Request:
```json
{ "email": "ada@example.com", "password": "correct horse battery staple" }
```
`201 Created`:
```json
{
"user": { "id": 1, "email": "ada@example.com", "created_at": "2026-09-03T12:00:00Z" },
"token": "<jwt>",
"expires_at": "2026-09-04T12:00:00+00:00"
}
```
Errors: `422` invalid input, `409` email already registered.
Validation: `email` must be a valid address (≤ 255 chars); `password` must be
872 characters.
### `POST /api/auth/login`
Request:
```json
{ "email": "ada@example.com", "password": "correct horse battery staple" }
```
`200 OK`: same shape as register. `401` on bad credentials (the message does not
say whether it was the email or the password that was wrong).
### `GET /api/me`
Requires `Authorization: Bearer <jwt>`.
`200 OK`:
```json
{ "user": { "id": 1, "email": "ada@example.com", "created_at": "2026-09-03T12:00:00Z" } }
```
`401` if the header is missing, malformed, or the token is invalid/expired.
### Error shape
Every error response looks like:
```json
{ "error": { "message": "The submitted data was invalid.", "details": { "email": ["Email must be a valid address."] } } }
```
`details` is present only when relevant (e.g. validation).
## Try it
```bash
BASE=http://localhost:8080
curl -s -X POST $BASE/api/auth/register \
-H 'Content-Type: application/json' \
-d '{"email":"ada@example.com","password":"password123"}'
TOKEN=$(curl -s -X POST $BASE/api/auth/login \
-H 'Content-Type: application/json' \
-d '{"email":"ada@example.com","password":"password123"}' | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
curl -s $BASE/api/me -H "Authorization: Bearer $TOKEN"
```
## Tests
```bash
composer install # installs phpunit (require-dev)
vendor/bin/phpunit
```
## Layout
```
public/index.php Front controller
src/bootstrap.php App wiring and route definitions
src/Support/Config.php Environment-driven configuration
src/Support/Database.php PDO/SQLite connection
src/Auth/JwtService.php Issue/verify JWTs
src/Auth/AuthMiddleware.php Bearer-token authentication
src/Http/JsonErrorHandler.php Uniform JSON error envelope
src/Http/Controllers/ Request handlers
src/Repository/ Database access
migrations/*.sql Schema, applied by bin/migrate.php
```
+64
View File
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
/**
* Applies any pending SQL migrations from migrations/*.sql, in filename order.
* Each applied file is recorded in the schema_migrations table so re-running is
* safe. Usage: php bin/migrate.php (or: composer migrate)
*/
use App\Support\Config;
use App\Support\Database;
require __DIR__ . '/../vendor/autoload.php';
$config = Config::load(dirname(__DIR__));
$pdo = (new Database($config->databasePath))->pdo();
$pdo->exec(
'CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TEXT NOT NULL DEFAULT (strftime(\'%Y-%m-%dT%H:%M:%SZ\', \'now\'))
)'
);
$applied = $pdo->query('SELECT filename FROM schema_migrations')
->fetchAll(PDO::FETCH_COLUMN);
$files = glob(dirname(__DIR__) . '/migrations/*.sql') ?: [];
sort($files);
$count = 0;
foreach ($files as $file) {
$name = basename($file);
if (in_array($name, $applied, true)) {
continue;
}
$sql = (string) file_get_contents($file);
$pdo->beginTransaction();
try {
$pdo->exec($sql);
$record = $pdo->prepare('INSERT INTO schema_migrations (filename) VALUES (?)');
$record->execute([$name]);
$pdo->commit();
} catch (Throwable $e) {
$pdo->rollBack();
fwrite(STDERR, "Failed to apply {$name}: {$e->getMessage()}\n");
exit(1);
}
echo "Applied {$name}\n";
$count++;
}
echo $count === 0
? "Database is up to date; nothing to apply.\n"
: "Done. Applied {$count} migration(s).\n";
+37
View File
@@ -0,0 +1,37 @@
{
"name": "aneurin/php-todo-list",
"description": "Simple todo list REST API + SPA (PHP, SQLite)",
"type": "project",
"license": "MIT",
"require": {
"php": ">=8.1",
"ext-json": "*",
"ext-mbstring": "*",
"ext-pdo": "*",
"ext-pdo_sqlite": "*",
"slim/slim": "^4.12",
"slim/psr7": "^1.6",
"firebase/php-jwt": "^7.0",
"vlucas/phpdotenv": "^5.6"
},
"require-dev": {
"phpunit/phpunit": "^10.5"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"config": {
"sort-packages": true
},
"scripts": {
"migrate": "php bin/migrate.php",
"serve": "php -S localhost:8080 -t public"
}
}
Generated
+2886
View File
File diff suppressed because it is too large Load Diff
+60
View File
@@ -0,0 +1,60 @@
# Stage 1 — Authentication API
Status: **done** and verified end-to-end (PHPUnit feature tests + a live `curl`
run against the built-in server).
## What's there
A Slim 4 REST API on SQLite with JWT bearer authentication.
| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/health` | liveness check |
| POST | `/api/auth/register` | create account, returns user + token |
| POST | `/api/auth/login` | exchange email/password for a token |
| GET | `/api/me` | current user (requires `Authorization: Bearer <jwt>`) |
- **Passwords** are hashed with `password_hash()` (bcrypt). Validation is
email-format plus an 872 character password. Login returns a single generic
"Invalid email or password" message so it does not leak which emails exist.
- **Emails** are stored lower-cased in a `UNIQUE COLLATE NOCASE` column;
duplicate registration returns `409`.
- **Errors** always come back as
`{ "error": { "message": ..., "details"?: ... } }` via
[../src/Http/JsonErrorHandler.php](../src/Http/JsonErrorHandler.php).
- **Tokens** are stateless HS256 JWTs. The signing secret comes from
`JWT_SECRET`, or is auto-generated into `storage/secret.key` on first run.
- **Migrations** are plain SQL files in [../migrations/](../migrations/), applied
idempotently by [../bin/migrate.php](../bin/migrate.php) and tracked in a
`schema_migrations` table.
## Dependency note
`firebase/php-jwt` is pinned to `^7.0` — Composer blocks `6.10``6.11` for a
published security advisory (`PKSA-y2cr-5h3j-g3ys`).
## Key files
- [../src/bootstrap.php](../src/bootstrap.php) — app wiring + routes
- [../src/Http/Controllers/AuthController.php](../src/Http/Controllers/AuthController.php) — register / login / me
- [../src/Auth/JwtService.php](../src/Auth/JwtService.php), [../src/Auth/AuthMiddleware.php](../src/Auth/AuthMiddleware.php)
- [../src/Repository/UserRepository.php](../src/Repository/UserRepository.php)
- [../src/Support/Config.php](../src/Support/Config.php), [../src/Support/Database.php](../src/Support/Database.php)
- [../tests/AuthTest.php](../tests/AuthTest.php) — 6 passing feature tests
## Run it
```bash
composer install && composer migrate && composer serve # http://localhost:8080
```
## Local toolchain
This machine has no `php`/`composer` binary. Tooling was run through the official
Composer container image, which bundles PHP + Composer + `pdo_sqlite` +
`mbstring`:
```bash
podman run --rm -v "$PWD":/app:Z -w /app docker.io/library/composer:2 install
podman run --rm -v "$PWD":/app:Z -w /app docker.io/library/composer:2 vendor/bin/phpunit
```
+7
View File
@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
password_hash TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
cacheDirectory=".phpunit.cache">
<testsuites>
<testsuite name="Feature">
<directory>tests</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_DEBUG" value="true"/>
<env name="JWT_SECRET" value="test-secret-do-not-use-in-production"/>
</php>
</phpunit>
+4
View File
@@ -0,0 +1,4 @@
# Route every request that isn't a real file through the front controller.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
/** @var \Slim\App $app */
$app = require __DIR__ . '/../src/bootstrap.php';
$app->run();
+49
View File
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace App\Auth;
use App\Exception\ApiException;
use App\Repository\UserRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Throwable;
/**
* Requires a valid `Authorization: Bearer <jwt>` header. On success the resolved
* user row is attached to the request as the `user` attribute.
*/
final class AuthMiddleware implements MiddlewareInterface
{
public function __construct(
private readonly JwtService $jwt,
private readonly UserRepository $users,
) {
}
public function process(Request $request, RequestHandler $handler): Response
{
$header = $request->getHeaderLine('Authorization');
if (preg_match('/^Bearer\s+(\S+)$/i', $header, $matches) !== 1) {
throw new ApiException('Missing or malformed Authorization header.', 401);
}
try {
$claims = $this->jwt->verify($matches[1]);
} catch (Throwable) {
throw new ApiException('The access token is invalid or has expired.', 401);
}
$user = $this->users->findById((int) ($claims['sub'] ?? 0));
if ($user === null) {
throw new ApiException('The account for this token no longer exists.', 401);
}
return $handler->handle($request->withAttribute('user', $user));
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace App\Auth;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
/**
* Issues and verifies stateless HS256 JSON Web Tokens for authenticated users.
*/
final class JwtService
{
private const ALGORITHM = 'HS256';
public function __construct(
private readonly string $secret,
private readonly int $ttl,
) {
}
/**
* @param array{id: int, email: string, ...} $user
* @return array{token: string, expires_at: string}
*/
public function issue(array $user): array
{
$issuedAt = time();
$expiresAt = $issuedAt + $this->ttl;
$token = JWT::encode([
'sub' => (int) $user['id'],
'email' => $user['email'],
'iat' => $issuedAt,
'exp' => $expiresAt,
], $this->secret, self::ALGORITHM);
return [
'token' => $token,
'expires_at' => gmdate('c', $expiresAt),
];
}
/**
* @return array<string, mixed> The decoded claims.
*
* @throws \Firebase\JWT\ExpiredException
* @throws \Firebase\JWT\SignatureInvalidException
* @throws \UnexpectedValueException
*/
public function verify(string $token): array
{
return (array) JWT::decode($token, new Key($this->secret, self::ALGORITHM));
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Exception;
use RuntimeException;
/**
* An error that should be reported to the client with a specific HTTP status and
* a JSON body. Thrown by controllers and middleware, rendered by JsonErrorHandler.
*/
class ApiException extends RuntimeException
{
/**
* @param array<string, mixed> $details Optional machine-readable context.
*/
public function __construct(
string $message,
private readonly int $statusCode = 400,
private readonly array $details = [],
) {
parent::__construct($message);
}
public function getStatusCode(): int
{
return $this->statusCode;
}
/**
* @return array<string, mixed>
*/
public function getDetails(): array
{
return $this->details;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Exception;
/**
* Raised when request input fails validation. Carries a field => messages map.
*/
final class ValidationException extends ApiException
{
/**
* @param array<string, string[]> $errors
*/
public function __construct(array $errors)
{
parent::__construct('The submitted data was invalid.', 422, $errors);
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Auth\JwtService;
use App\Exception\ApiException;
use App\Exception\ValidationException;
use App\Repository\UserRepository;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
final class AuthController extends Controller
{
private const PASSWORD_MIN = 8;
// bcrypt (password_hash's current default) only considers the first 72 bytes.
private const PASSWORD_MAX = 72;
private const EMAIL_MAX = 255;
public function __construct(
private readonly UserRepository $users,
private readonly JwtService $jwt,
) {
}
/**
* POST /api/auth/register
*/
public function register(Request $request, Response $response): Response
{
[$email, $password] = $this->credentials($request);
if ($this->users->findByEmail($email) !== null) {
throw new ApiException('That email address is already registered.', 409);
}
$user = $this->users->create($email, password_hash($password, PASSWORD_DEFAULT));
return $this->json($response, $this->session($user), 201);
}
/**
* POST /api/auth/login
*/
public function login(Request $request, Response $response): Response
{
[$email, $password] = $this->credentials($request);
$user = $this->users->findByEmail($email);
if ($user === null || !password_verify($password, $user['password_hash'])) {
// Same message either way so we don't reveal which emails are registered.
throw new ApiException('Invalid email or password.', 401);
}
return $this->json($response, $this->session($user));
}
/**
* GET /api/me (requires AuthMiddleware)
*/
public function me(Request $request, Response $response): Response
{
/** @var array{id: int, email: string, created_at: string} $user */
$user = $request->getAttribute('user');
return $this->json($response, ['user' => $this->presentUser($user)]);
}
/**
* Extract and validate the email/password pair from the request body.
*
* @return array{0: string, 1: string} Normalised email and raw password.
*/
private function credentials(Request $request): array
{
$body = (array) ($request->getParsedBody() ?? []);
$email = is_string($body['email'] ?? null) ? trim($body['email']) : '';
$password = is_string($body['password'] ?? null) ? $body['password'] : '';
$errors = [];
if ($email === '') {
$errors['email'][] = 'Email is required.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'][] = 'Email must be a valid address.';
} elseif (strlen($email) > self::EMAIL_MAX) {
$errors['email'][] = sprintf('Email must be at most %d characters.', self::EMAIL_MAX);
}
if ($password === '') {
$errors['password'][] = 'Password is required.';
} elseif (strlen($password) < self::PASSWORD_MIN) {
$errors['password'][] = sprintf('Password must be at least %d characters.', self::PASSWORD_MIN);
} elseif (strlen($password) > self::PASSWORD_MAX) {
$errors['password'][] = sprintf('Password must be at most %d characters.', self::PASSWORD_MAX);
}
if ($errors !== []) {
throw new ValidationException($errors);
}
return [mb_strtolower($email), $password];
}
/**
* Build the standard authentication payload returned by register and login.
*
* @param array{id: int, email: string, created_at: string} $user
* @return array<string, mixed>
*/
private function session(array $user): array
{
$token = $this->jwt->issue($user);
return [
'user' => $this->presentUser($user),
'token' => $token['token'],
'expires_at' => $token['expires_at'],
];
}
/**
* @param array{id: int, email: string, created_at?: string} $user
* @return array<string, mixed>
*/
private function presentUser(array $user): array
{
return [
'id' => (int) $user['id'],
'email' => $user['email'],
'created_at' => $user['created_at'] ?? null,
];
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
/**
* Shared helpers for HTTP controllers.
*/
abstract class Controller
{
/**
* Write a JSON body and return the response with the appropriate headers.
*
* @param array<string, mixed> $data
*/
protected function json(Response $response, array $data, int $status = 200): Response
{
$response->getBody()->write(
(string) json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
);
return $response
->withHeader('Content-Type', 'application/json')
->withStatus($status);
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Http;
use App\Exception\ApiException;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Exception\HttpMethodNotAllowedException;
use Slim\Exception\HttpNotFoundException;
use Throwable;
/**
* Renders every uncaught error as a consistent JSON envelope:
*
* { "error": { "message": string, "details"?: object } }
*/
final class JsonErrorHandler
{
public function __construct(
private readonly ResponseFactoryInterface $responseFactory,
private readonly bool $displayErrorDetails,
) {
}
public function __invoke(
Request $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails,
): Response {
[$status, $payload] = $this->describe($exception);
$response = $this->responseFactory->createResponse($status);
$response->getBody()->write(
(string) json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
);
return $response->withHeader('Content-Type', 'application/json');
}
/**
* @return array{0: int, 1: array<string, mixed>}
*/
private function describe(Throwable $exception): array
{
if ($exception instanceof ApiException) {
$error = ['message' => $exception->getMessage()];
if ($exception->getDetails() !== []) {
$error['details'] = $exception->getDetails();
}
return [$exception->getStatusCode(), ['error' => $error]];
}
if ($exception instanceof HttpNotFoundException) {
return [404, ['error' => ['message' => 'The requested resource was not found.']]];
}
if ($exception instanceof HttpMethodNotAllowedException) {
return [405, ['error' => ['message' => 'Method not allowed for this resource.']]];
}
$error = ['message' => 'An unexpected error occurred.'];
if ($this->displayErrorDetails) {
$error['message'] = $exception->getMessage();
$error['exception'] = $exception::class;
$error['file'] = $exception->getFile() . ':' . $exception->getLine();
}
return [500, ['error' => $error]];
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Repository;
use PDO;
/**
* Data access for the `users` table. Rows are returned as associative arrays.
*
* @phpstan-type UserRow array{id: int, email: string, password_hash: string, created_at: string, updated_at: string}
*/
final class UserRepository
{
public function __construct(private readonly PDO $pdo)
{
}
/**
* @return UserRow|null
*/
public function findByEmail(string $email): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
$row = $stmt->fetch();
return $row === false ? null : $this->cast($row);
}
/**
* @return UserRow|null
*/
public function findById(int $id): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
return $row === false ? null : $this->cast($row);
}
/**
* @return UserRow
*/
public function create(string $email, string $passwordHash): array
{
$stmt = $this->pdo->prepare(
'INSERT INTO users (email, password_hash) VALUES (:email, :password_hash)'
);
$stmt->execute([
'email' => $email,
'password_hash' => $passwordHash,
]);
/** @var UserRow $user */
$user = $this->findById((int) $this->pdo->lastInsertId());
return $user;
}
/**
* @param array<string, mixed> $row
* @return UserRow
*/
private function cast(array $row): array
{
$row['id'] = (int) $row['id'];
/** @var UserRow $row */
return $row;
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Support;
/**
* Immutable application configuration, resolved from environment variables with
* development-friendly defaults.
*/
final class Config
{
public function __construct(
public readonly string $databasePath,
public readonly string $jwtSecret,
public readonly int $jwtTtl,
public readonly bool $displayErrors,
) {
}
public static function load(string $basePath): self
{
if (is_file($basePath . '/.env')) {
\Dotenv\Dotenv::createImmutable($basePath)->safeLoad();
}
$storagePath = $basePath . '/storage';
if (!is_dir($storagePath)) {
mkdir($storagePath, 0775, true);
}
$databasePath = self::env('DATABASE_PATH', $storagePath . '/database.sqlite');
if (!self::isAbsolutePath($databasePath)) {
$databasePath = $basePath . '/' . ltrim($databasePath, '/');
}
$jwtSecret = self::env('JWT_SECRET') ?? self::resolveSecret($storagePath . '/secret.key');
$jwtTtl = (int) (self::env('JWT_TTL') ?? '86400');
$displayErrors = filter_var(self::env('APP_DEBUG', 'false'), FILTER_VALIDATE_BOOL);
return new self($databasePath, $jwtSecret, $jwtTtl, $displayErrors);
}
private static function env(string $key, ?string $default = null): ?string
{
$value = $_ENV[$key] ?? $_SERVER[$key] ?? getenv($key);
if ($value === false || $value === null || $value === '') {
return $default;
}
return (string) $value;
}
private static function isAbsolutePath(string $path): bool
{
return str_starts_with($path, '/') || preg_match('#^[A-Za-z]:[\\\\/]#', $path) === 1;
}
/**
* Return the persisted signing secret, generating and storing one on first run
* so local development works with zero configuration.
*/
private static function resolveSecret(string $path): string
{
if (is_file($path)) {
return trim((string) file_get_contents($path));
}
$secret = bin2hex(random_bytes(32));
file_put_contents($path, $secret);
@chmod($path, 0600);
return $secret;
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Support;
use PDO;
/**
* Thin wrapper around a PDO connection to the SQLite database.
*/
final class Database
{
private PDO $pdo;
public function __construct(string $path)
{
$this->pdo = new PDO('sqlite:' . $path, null, null, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
$this->pdo->exec('PRAGMA foreign_keys = ON');
$this->pdo->exec('PRAGMA journal_mode = WAL');
}
public function pdo(): PDO
{
return $this->pdo;
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
use App\Auth\AuthMiddleware;
use App\Auth\JwtService;
use App\Http\Controllers\AuthController;
use App\Http\JsonErrorHandler;
use App\Repository\UserRepository;
use App\Support\Config;
use App\Support\Database;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Slim\Routing\RouteCollectorProxy;
$config = Config::load(dirname(__DIR__));
$database = new Database($config->databasePath);
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
$errorMiddleware = $app->addErrorMiddleware($config->displayErrors, true, true);
$errorMiddleware->setDefaultErrorHandler(
new JsonErrorHandler($app->getResponseFactory(), $config->displayErrors)
);
// --- Wiring -----------------------------------------------------------------
$users = new UserRepository($database->pdo());
$jwt = new JwtService($config->jwtSecret, $config->jwtTtl);
$authController = new AuthController($users, $jwt);
$authMiddleware = new AuthMiddleware($jwt, $users);
// --- Routes ---------------------------------------------------------------
$app->group('/api', function (RouteCollectorProxy $group) use ($authController, $authMiddleware) {
$group->get('/health', function (Request $request, Response $response): Response {
$response->getBody()->write((string) json_encode(['status' => 'ok']));
return $response->withHeader('Content-Type', 'application/json');
});
$group->post('/auth/register', [$authController, 'register']);
$group->post('/auth/login', [$authController, 'login']);
$group->get('/me', [$authController, 'me'])->add($authMiddleware);
});
return $app;
+151
View File
@@ -0,0 +1,151 @@
<?php
declare(strict_types=1);
namespace Tests;
use PDO;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\ResponseInterface;
use Slim\App;
use Slim\Psr7\Factory\ServerRequestFactory;
final class AuthTest extends TestCase
{
private App $app;
private string $databasePath;
protected function setUp(): void
{
$this->databasePath = sys_get_temp_dir() . '/todo-test-' . uniqid() . '.sqlite';
putenv('DATABASE_PATH=' . $this->databasePath);
$_ENV['DATABASE_PATH'] = $this->databasePath;
$pdo = new PDO('sqlite:' . $this->databasePath);
foreach (glob(dirname(__DIR__) . '/migrations/*.sql') ?: [] as $migration) {
$pdo->exec((string) file_get_contents($migration));
}
$this->app = require dirname(__DIR__) . '/src/bootstrap.php';
}
protected function tearDown(): void
{
@unlink($this->databasePath);
putenv('DATABASE_PATH');
unset($_ENV['DATABASE_PATH']);
}
public function test_registration_returns_a_user_and_token(): void
{
$response = $this->request('POST', '/api/auth/register', [
'email' => 'Ada@example.com',
'password' => 'correct horse battery',
]);
self::assertSame(201, $response->getStatusCode());
$body = $this->decode($response);
self::assertSame('ada@example.com', $body['user']['email']);
self::assertArrayNotHasKey('password_hash', $body['user']);
self::assertNotEmpty($body['token']);
}
public function test_registration_rejects_a_duplicate_email(): void
{
$payload = ['email' => 'dupe@example.com', 'password' => 'password123'];
$this->request('POST', '/api/auth/register', $payload);
$response = $this->request('POST', '/api/auth/register', $payload);
self::assertSame(409, $response->getStatusCode());
}
public function test_registration_validates_input(): void
{
$response = $this->request('POST', '/api/auth/register', [
'email' => 'not-an-email',
'password' => 'short',
]);
self::assertSame(422, $response->getStatusCode());
$body = $this->decode($response);
self::assertArrayHasKey('email', $body['error']['details']);
self::assertArrayHasKey('password', $body['error']['details']);
}
public function test_login_succeeds_with_correct_password(): void
{
$this->request('POST', '/api/auth/register', [
'email' => 'grace@example.com',
'password' => 'password123',
]);
$response = $this->request('POST', '/api/auth/login', [
'email' => 'grace@example.com',
'password' => 'password123',
]);
self::assertSame(200, $response->getStatusCode());
self::assertNotEmpty($this->decode($response)['token']);
}
public function test_login_fails_with_wrong_password(): void
{
$this->request('POST', '/api/auth/register', [
'email' => 'grace@example.com',
'password' => 'password123',
]);
$response = $this->request('POST', '/api/auth/login', [
'email' => 'grace@example.com',
'password' => 'wrong-password',
]);
self::assertSame(401, $response->getStatusCode());
}
public function test_me_requires_a_valid_token(): void
{
$unauthorised = $this->request('GET', '/api/me');
self::assertSame(401, $unauthorised->getStatusCode());
$token = $this->decode($this->request('POST', '/api/auth/register', [
'email' => 'linus@example.com',
'password' => 'password123',
]))['token'];
$response = $this->request('GET', '/api/me', null, ['Authorization' => 'Bearer ' . $token]);
self::assertSame(200, $response->getStatusCode());
self::assertSame('linus@example.com', $this->decode($response)['user']['email']);
}
/**
* @param array<string, mixed>|null $body
* @param array<string, string> $headers
*/
private function request(string $method, string $path, ?array $body = null, array $headers = []): ResponseInterface
{
$request = (new ServerRequestFactory())->createServerRequest($method, $path);
foreach ($headers as $name => $value) {
$request = $request->withHeader($name, $value);
}
if ($body !== null) {
$request = $request->withParsedBody($body)->withHeader('Content-Type', 'application/json');
}
return $this->app->handle($request);
}
/**
* @return array<string, mixed>
*/
private function decode(ResponseInterface $response): array
{
return (array) json_decode((string) $response->getBody(), true, 512, JSON_THROW_ON_ERROR);
}
}