<?php
namespace App\Controller;
use App\Entity\Internal\ApiUser;
use App\Entity\Internal\TwoFaConfig;
use App\Helper\LoginHelper;
use Doctrine\ORM\EntityManagerInterface;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
class UserController extends AbstractController
{
/**
* @Route("/api/me", name="users_me")
*/
public function me(SerializerInterface $serializer, EntityManagerInterface $internalEntityManager): JsonResponse
{
if (!$this->getUser() || $this->getUser() instanceof ApiUser) {
throw new UnauthorizedHttpException('Bearer');
}
$twoFaConfig = $internalEntityManager->getRepository(TwoFaConfig::class)->findOneBy([
'userId' => $this->getUser()->getUser()->getUserId(),
]);
$this->getUser()->setTwoFaStatus($twoFaConfig?->getStatus() ?? TwoFaConfig::STATUS_DISABLED);
return new JsonResponse($serializer->normalize($this->getUser(), 'json', ['groups' => 'user:read']));
}
/**
* @Route("/api/impersonate", name="users_impersonate", methods={"POST"})
*/
public function impersonate(Request $request, JWTTokenManagerInterface $JWTManager, EntityManagerInterface $entityManager): JsonResponse
{
$data = json_decode($request->getContent(), true);
if (!isset($data['secretKey']) || $data['secretKey'] != $_ENV['APP_SECRET']) {
throw new AccessDeniedHttpException();
}
$data['origin'] = $this->getUser()->getUser()->getUserId();
$userId = (int)$data['userId'] ?? 0;
unset($data['userId'], $data['secretKey']);
$user = LoginHelper::fetchUser($entityManager, 'user_id', $userId);
if ($user) {
$impToken = $JWTManager->createFromPayload($user, $data);
return new JsonResponse([
'impToken' => $impToken,
]);
}
throw new NotFoundHttpException('User not found');
}
}