User session management for Slim Framework
composer install battis/user-sessionSee example for sample implementation. The highlights are:
Use UserSession\Dependencies to prepare container with dependency definitions (this should be done before any additional app-specific definitions wherein you might want to override any of the UserSession defaults):
/** @var DI\ContainerBuilder $containerBuilder */
$containerBuilder->addDefinitions(
Battis\UserSession\Dependencies::definitions()
);Define implementations of UserEntityInterface and UserRepositoryInterface and
namespace Example;
class UserEntity implements Battis\UserSession\Entities\UserEntityInterface
{
public function getIdentifier(): string
{
// ...
}
public function passwordVerify(string $password): bool
{
// ...
}
}<?php
namespace Example;
class UserRepository implements Battis\UserSession\Repositories\UserRepositoryInterface
{
public function getUserEntityByUsername(
// ...
}
}Define these implementations (or, at least, your UserRepositoryInterface implementation) in the container:
/** @var DI\ContainerBuilder $containerBuilder */
$containerBuilder->addDefinitions([
Battis\UserSession\Repositories\UserRepositoryInterface::class => fn() => new Example\UserRepository(),
]);Use UserSession\Controller to define authentication endpoints (/auth/login and /auth/logout):
/** @var Slim\App $app */
$app->group(
Battis\UserSession\Controller::ENDPOINT,
Battis\UserSession\Controller::class
);Add a user session that provides access to the currently logged-in user to an endpoint (or group) by adding the UserSession\Middleware\Session middleware:
/** @var Slim\App $app */
$app
->get('/home', Example\PageRenderer::class)
->add(Battis\UserSession\Middleware\Session::class);Restrict access to an endpoint (or group) to authenticated users by adding the UserSession\Middleware\RequireAuthentication middleware:
/** @var Slim\App $app */
$app
->get('/protected', Example\PageRenderer::class)
->add(Battis\UserSession\Middleware\RequireAuthentication::class);