<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class PostCMPController extends AbstractController
{
#[Route('/post-cmp', name: 'app_post_cmp', methods: ['GET'])]
public function index(Request $request): RedirectResponse | Response
{
// Check if the user has accepted the consent cookie
$consentCookie = $request->cookies->get('consent');
if ($consentCookie === 'yes') {
// Check if the First-ID cookie exists
$firstIdCookie = $request->cookies->get('firstid');
if (!$firstIdCookie) {
// Redirect to the First-ID gate
$redirectHostUrlEncode = urlencode($request->getSchemeAndHttpHost());
$redirectPath = '/handle-first-id-redirect';
$redirectUriUrlEncode = urlencode($redirectHostUrlEncode . $redirectPath);
return new RedirectResponse(
"https://gate.first-id.fr?redirectHost=$redirectHostUrlEncode&redirectUri=$redirectUriUrlEncode",
Response::HTTP_FOUND
);
}
}
// Render your base template
return $this->render('post-cmp/post-cmp.html.twig');
}
/**
* @Route("/handle-first-id-redirect", name="app_handle_first_id_redirect")
*/
#[Route('/post-cmp/handle-first-id-redirect', name: 'app_post_cmp_handle_first_id_redirect', methods: ['GET'])]
public function handleFirstIdRedirect(Request $request): Response
{
// Check if the "firstId" query parameter is present in the URL
if ($request->query->has('firstId') && $request->query->has('redirectUri')) {
$firstId = $request->query->get('firstId');
$redirectUri = $request->query->get('redirectUri');
// Create the First-ID cookie
$response = $this->redirect(urldecode($redirectUri));
$response->headers->setCookie(
new Cookie(
'firstid',
$firstId,
time() + (60 * 60 * 24 * 180), // 180 days
)
);
// Remove the "firstId" and "redirectUri" query parameters from the URL
$params = $request->query->all();
unset($params['firstId']);
unset($params['redirectUri']);
$finalUrl = urldecode($redirectUri);
if (!empty($params)) {
$finalUrl .= '?' . http_build_query($params);
}
$response->setTargetUrl($finalUrl);
return $response;
}
// If the "firstId" query parameter is not present, redirect to the homepage
return $this->render('base.html.twig');
}
}