<?php
namespace App\Misc;
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\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Http\Authenticator\AbstractAuthenticator;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\Authenticator\Passport\SelfValidatingPassport;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\CustomCredentials;
use App\Exception\AccessDeniedException;
use App\Entity\User;
class AppAuthenticator extends AbstractAuthenticator
{
/**
* Called on every request to decide if this authenticator should be
* used for the request. Returning `false` will cause this authenticator
* to be skipped.
*/
public function supports(Request $request): ?bool
{
return $request->headers->has('X-W-Auth');
}
public function authenticate(Request $request): PassportInterface
{
$authRegex = '/UsernameToken Email="(?P<email>[^"]+)", PasswordDigest="(?P<digest>[^"]+)", Nonce="(?P<nonce>[a-zA-Z0-9+\/]+={0,2})", Created="(?P<created>[^"]+)"/';
if (
1 !== preg_match($authRegex, $request->headers->get('X-W-Auth'), $matches)
|| $matches['email'] == 'undefined'
) {
throw new AccessDeniedException(AccessDeniedException::INVALID_TOKEN, 'token check');
}
return new Passport(new UserBadge($matches['email']), new CustomCredentials(
function ($credentials, User $user) use ($request) {
if (!$user->getAuthPermitted()) {
throw new AccessDeniedException(AccessDeniedException::NOT_PERMITTED, 'authenticate');
}
$rawString = $credentials['nonce'] . $credentials['created'] . hash('sha256', $user->getPassword());
$expected = hash('sha256', $rawString);
return hash_equals($expected, $credentials['digest']);
},
[
'digest' => $matches['digest'],
'nonce' => $matches['nonce'],
'created' => $matches['created'],
'host' => $request->getHost(),
]
));
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
{
// on success, let the request continue
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response
{
throw new AccessDeniedException(AccessDeniedException::WRONG_TOKEN, 'token check');
}
}