<?php
namespace App\Security\Supplier\Authorization;
use App\Entity\Supplier;
use App\Exception\AuthorizationFailedException;
use App\Service\Redis;
use Doctrine\ORM\EntityManagerInterface;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Signature\Algorithm\HS256;
use Jose\Component\Signature\Algorithm\HS512;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Class RITAuthorization
* @package App\Security\Supplier\Authorization
*/
class RITAuthorization extends AbstractAuthorization implements AuthenticationEntryPointInterface
{
/** @var EntityManagerInterface */
private EntityManagerInterface $em;
/** @var NormalizerInterface */
private NormalizerInterface $normalizer;
/** @var Redis */
private Redis $redis;
/**
* RITAuthorization constructor.
* @param EntityManagerInterface $em
* @param NormalizerInterface $normalizer
* @param Redis $redis
*/
public function __construct(
EntityManagerInterface $em,
NormalizerInterface $normalizer,
Redis $redis
)
{
$this->em = $em;
$this->redis = $redis;
$this->normalizer = $normalizer;
parent::__construct(new AlgorithmManager([new HS512(), new HS256()]));
}
/**
* @param Request $request
* @param AuthenticationException|null $authException
* @return Response
* @throws AuthorizationFailedException
*/
public function start(Request $request, AuthenticationException $authException = null)
{
if ($this->supports($request)) {
$credentials = $this->getCredentials($request);
if ($credentials) {
$customer_repository = $this->em->getRepository(Supplier::class);
$supplier = $customer_repository->findOneBy(["email" => $credentials["email"]]);
if (is_a($supplier, Supplier::class)) {
$password_hash = $supplier->getPassword();
$password = $credentials["password"];
if (password_verify($password, $password_hash)) {
return $this->onAuthorizationSuccess($supplier);
} else {
throw new AuthorizationFailedException();
}
} else {
throw new AuthorizationFailedException();
}
}
}
throw new AuthorizationFailedException();
}
/**
* @inheritDoc
*/
public function supports(Request $request)
{
return $request->request->has("email") and $request->request->has("password");
}
/**
* @inheritDoc
*/
public function getCredentials(Request $request)
{
return [
"email" => $request->get("email"),
"password" => $request->get("password"),
];
}
/**
* @param Supplier $supplier
* @return Response
*/
public function onAuthorizationSuccess(Supplier $supplier)
{
$access_token = $this->makeAccessToken([
"user_id" => $supplier->getId()
]);
return new JsonResponse([
"access_token" => $access_token,
"refresh_token" => null
]);
}
}