<?php
/*
* This file is part of the nellapp-core package.
*
* (c) Benjamin Georgeault
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nellapp\Bundle\SDKBundle\Sync\Security;
use Nellapp\Bundle\SDKBundle\Sync\Security\User\Core;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
/**
* Class CoreAuthenticator
*
* @author Benjamin Georgeault
* @method TokenInterface createToken(Passport $passport, string $firewallName)
*/
class CoreAuthenticator extends AbstractAuthenticator
{
public function __construct(
private string $syncSecret,
) {}
public function supports(Request $request): bool
{
return preg_match('/^\s*Core\s+[a-zA-Z0-9]+/i', $request->headers->get('Authorization', ''));
}
public function authenticate(Request $request): Passport
{
if (null === $authorization = $request->headers->get('authorization')) {
throw new AuthenticationException('Invalid request parameters');
}
$valid = preg_match('/^Core (.+)/', $authorization, $matches);
$credentials = $this->getCredentials($request);
$validCredentials = $this->checkCredentials($credentials);
if (!$valid || count($matches) !== 2 || !$validCredentials) {
throw new AuthenticationException('Invalid request parameters');
}
return new SelfValidatingPassport(new UserBadge($matches[1], function(string $token) use ($credentials) {
return $this->getUser($credentials);
}));
}
public function getCredentials(Request $request): ?string
{
return trim(preg_replace('/^\s*Core\s+/', '', $request->headers->get('Authorization')));
}
public function getUser($credentials): ?Core
{
if (null === $credentials) {
return null;
}
return new Core();
}
public function checkCredentials($credentials): bool
{
return $credentials === $this->syncSecret;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $firewallName): ?Response
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
return new JsonResponse('', Response::HTTP_UNAUTHORIZED);
}
}