wire postgres session repo, migrations, seed, and dev serve

This commit is contained in:
Yisroel Baum 2026-05-17 22:01:27 +03:00
parent 02effe761a
commit 89b63cb9e9
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
8 changed files with 235 additions and 2 deletions

View file

@ -0,0 +1,64 @@
<?php
namespace App\Auth;
use App\Database\SessionModel;
use App\Shared\ValueObject\EmailAddress;
use App\User\User;
class PostgresSessionRepository implements SessionRepository
{
public function create(CreateSessionDto $dto): Session
{
$record = SessionModel::create([
'token' => $dto->token,
'user_id' => $dto->user->getId(),
'created_at' => $dto->createdAt->format('Y-m-d H:i:s'),
'expires_at' => $dto->expiresAt->format('Y-m-d H:i:s'),
]);
return new Session(
token: $record->token,
user: $dto->user,
createdAt: $dto->createdAt,
expiresAt: $dto->expiresAt,
);
}
public function findByToken(string $token): ?Session
{
$record = SessionModel::where('token', $token)->first();
if ($record === null) {
return null;
}
$userRecord = $record->user;
if ($userRecord === null) {
return null;
}
$user = new User(
id: $userRecord->id,
email: new EmailAddress($userRecord->email),
passwordHash: $userRecord->password_hash,
);
return new Session(
token: $record->token,
user: $user,
createdAt: $record->created_at instanceof \DateTimeImmutable
? $record->created_at
: new \DateTimeImmutable($record->created_at->format('Y-m-d H:i:s')),
expiresAt: $record->expires_at instanceof \DateTimeImmutable
? $record->expires_at
: new \DateTimeImmutable($record->expires_at->format('Y-m-d H:i:s')),
);
}
public function deleteByToken(string $token): void
{
SessionModel::where('token', $token)->delete();
}
}

40
backend/bin/seed Executable file
View file

@ -0,0 +1,40 @@
#!/usr/bin/env php
<?php
use App\Auth\PasswordHasher;
use App\Shared\ValueObject\EmailAddress;
use App\User\CreateUserDto;
use App\User\UserRepository;
(static function (): void {
$root = dirname(__DIR__);
require $root . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable($root);
$dotenv->safeLoad();
require $root . '/config/database.php';
$container = require $root . '/config/container.php';
$userRepo = $container->get(UserRepository::class);
$hasher = $container->get(PasswordHasher::class);
$seedEmail = 'admin@rabbigerzi.test';
$seedPassword = 'password';
$email = new EmailAddress($seedEmail);
if ($userRepo->findByEmail($email) !== null) {
echo "Seed user {$seedEmail} already exists, skipping.\n";
exit(0);
}
$userRepo->create(new CreateUserDto(
email: $email,
passwordHash: $hasher->hash($seedPassword),
));
echo "Created seed user {$seedEmail} / {$seedPassword}\n";
})();

30
backend/bin/serve Executable file
View file

@ -0,0 +1,30 @@
#!/usr/bin/env bash
set -e
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
export PGDATA="${PGDATA:-$REPO_ROOT/.postgres}"
export PGHOST="${PGHOST:-$PGDATA}"
export PGUSER="${PGUSER:-postgres}"
export PGDATABASE="${PGDATABASE:-rabbigerzi}"
export DB_HOST="${DB_HOST:-127.0.0.1}"
export DB_PORT="${DB_PORT:-5432}"
export DB_NAME="${DB_NAME:-rabbigerzi}"
export DB_USER="${DB_USER:-postgres}"
export DB_PASSWORD="${DB_PASSWORD:-}"
echo "[serve] waiting for postgres..."
until pg_isready -h "$PGHOST" -q 2>/dev/null; do
sleep 1
done
echo "[serve] creating database if it does not exist..."
createdb --no-password "$PGDATABASE" 2>/dev/null || echo "[serve] database already exists"
echo "[serve] running migrations..."
php "$REPO_ROOT/backend/bin/migrate"
echo "[serve] seeding..."
php "$REPO_ROOT/backend/bin/seed"
echo "[serve] starting PHP dev server..."
exec php -S 127.0.0.1:8000 -t "$REPO_ROOT/backend/public/"

View file

@ -3,7 +3,9 @@
use App\Auth\BcryptPasswordHasher; use App\Auth\BcryptPasswordHasher;
use App\Auth\Clock; use App\Auth\Clock;
use App\Auth\PasswordHasher; use App\Auth\PasswordHasher;
use App\Auth\PostgresSessionRepository;
use App\Auth\RandomTokenGenerator; use App\Auth\RandomTokenGenerator;
use App\Auth\SessionRepository;
use App\Auth\SystemClock; use App\Auth\SystemClock;
use App\Auth\TokenGenerator; use App\Auth\TokenGenerator;
use App\Auth\UseCases\AuthenticateUser\AuthenticateUser; use App\Auth\UseCases\AuthenticateUser\AuthenticateUser;
@ -26,6 +28,7 @@ $builder->addDefinitions([
// Repositories // Repositories
UserRepository::class => DI\create(PostgresUserRepository::class), UserRepository::class => DI\create(PostgresUserRepository::class),
SessionRepository::class => DI\create(PostgresSessionRepository::class),
// Use cases // Use cases
AuthenticateUser::class => DI\autowire(), AuthenticateUser::class => DI\autowire(),

View file

@ -0,0 +1,34 @@
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class SessionModel extends Model
{
protected $table = 'sessions';
public $timestamps = false;
protected $primaryKey = 'token';
public $incrementing = false;
protected $fillable = [
'token',
'user_id',
'expires_at',
'created_at',
];
protected $casts = [
'expires_at' => 'datetime',
'created_at' => 'datetime',
];
public function user(): BelongsTo
{
return $this->belongsTo(UserModel::class, 'user_id');
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace App\Database\Migrations;
use App\Database\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;
class CreateSessionsTable extends Migration
{
public function up(): void
{
Capsule::schema()->create('sessions', function ($table) {
$table->string('token')->primary();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users')
->cascadeOnDelete();
$table->dateTime('expires_at');
$table->dateTime('created_at');
});
}
public function down(): void
{
Capsule::schema()->dropIfExists('sessions');
}
}
return CreateSessionsTable::class;

View file

@ -24,6 +24,25 @@
postgresql postgresql
process-compose process-compose
]; ];
shellHook = ''
REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
export PGDATA="$REPO_ROOT/.postgres"
export PGHOST="$PGDATA"
export PGUSER="postgres"
export PGDATABASE="rabbigerzi"
if [ ! -d "$PGDATA" ]; then
echo "[pg] initializing cluster at $PGDATA"
initdb --auth=trust --username=postgres --no-locale --encoding=UTF8 >/dev/null
{
echo "listen_addresses = '127.0.0.1'"
echo "unix_socket_directories = '$PGDATA'"
} >> "$PGDATA/postgresql.conf"
fi
echo "[dev] run 'process-compose up' to start postgres + backend + vite"
'';
}; };
} }
); );

View file

@ -1,9 +1,22 @@
version: "1" version: "0.5"
processes: processes:
postgres:
command: postgres -D "$PGDATA" -k "$PGDATA" -c listen_addresses=127.0.0.1
shutdown:
signal: 2
readiness_probe:
exec:
command: pg_isready -h "$PGDATA"
initial_delay_seconds: 1
period_seconds: 2
backend: backend:
command: php -S 127.0.0.1:8000 -t backend/public/ command: bash backend/bin/serve
working_dir: . working_dir: .
depends_on:
postgres:
condition: process_healthy
availability: availability:
restart: always restart: always