first commit
This commit is contained in:
46
src/Http/ClientIdResolver.php
Normal file
46
src/Http/ClientIdResolver.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* ClientIdResolver
|
||||
*
|
||||
* Resolves a stable, anonymous client identifier for browser-based users.
|
||||
* The identifier is stored as an HttpOnly cookie.
|
||||
*/
|
||||
final class ClientIdResolver
|
||||
{
|
||||
private const COOKIE_NAME = 'ai_client_id';
|
||||
|
||||
public function resolve(Request $request, Response $response): string
|
||||
{
|
||||
$clientId = $request->cookies->get(self::COOKIE_NAME);
|
||||
|
||||
if (is_string($clientId) && $clientId !== '') {
|
||||
return $clientId;
|
||||
}
|
||||
|
||||
$clientId = Uuid::v4()->toRfc4122();
|
||||
|
||||
$response->headers->setCookie(
|
||||
new Cookie(
|
||||
name: self::COOKIE_NAME,
|
||||
value: $clientId,
|
||||
expire: strtotime('+1 year'),
|
||||
path: '/',
|
||||
secure: false, // set true in production with HTTPS
|
||||
httpOnly: true,
|
||||
sameSite: Cookie::SAMESITE_LAX
|
||||
)
|
||||
);
|
||||
|
||||
return $clientId;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user