<?php
namespace App\Controller\Security;
use App\Controller\API\ApiTrait;
use App\Form\CrmUser\LoginType;
use App\Repository\ServiceFormRepository;
use App\Repository\ServiceSectionGroupRepository;
use App\Service\BarrierCache;
use Drenso\OidcBundle\OidcClientInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Security\Core\User\UserInterface;
class SecurityController extends AbstractController
{
use ApiTrait;
public function __construct(
private readonly ParameterBagInterface $parameterBag,
)
{
}
#[Route('/login_oidc', name: 'login_oidc')]
public function loginOIDC(OidcClientInterface $oidcClient): RedirectResponse
{
// Redirect to authorization @ OIDC provider
$redirect = $oidcClient->generateAuthorizationRedirect(
null,
['openid', 'account', 'email', 'profile', 'phone', 'address'],
false,
[
"callback_uri" => 'http://localhost/infonot-sso-callback'
],
);
return $redirect;
}
#[Route('/login_oidc_exist', name: 'login_oidc_exist')]
public function loginOIDCfromExistProfile(
BarrierCache $barrierCache,
OidcClientInterface $oidcClient,
UserInterface $user): RedirectResponse
{
// Redirect to authorization @ OIDC provider
$redirect = $oidcClient->generateAuthorizationRedirect(
null,
['openid', 'account', 'email', 'profile', 'phone', 'address'],
false,
[
"callback_uri" => 'http://localhost/infonot-sso-callback'
],
);
$query = parse_url($redirect->getTargetUrl(), PHP_URL_QUERY);
$params = [];
parse_str($query, $params);
if (($params['state'] ?? false) && $user && $user->getEmail()) {
$barrierCache->setValue('oidc_' . $params['state'], $user->getId());
}
return $redirect;
}
/**
* @Route("/login_check", name="login_check")
* @Security("is_granted('ROLE_NOTARY') or is_granted('ROLE_REFOVOD')")
*/
public function loginCheckAction(): Response
{
return new Response();
}
/**
* @Route("/partner_login_check", name="partner_login_check")
* @Security("is_granted('ROLE_NOTARY') or is_granted('ROLE_REFOVOD')")
*/
public function partnerLoginCheckAction(): Response
{
return new Response();
}
/**
* @Route("/login", name="app_login")
*/
public function login(
AuthenticationUtils $authenticationUtils,
ServiceFormRepository $serviceFormRepository,
ServiceSectionGroupRepository $serviceSectionGroupRepository,
Request $request
): Response
{
if ($this->isGranted('ROLE_NOTARY')) {
return $this->redirectToRoute('area_notary_index');
}
if ($request->getHost() === $this->getParameter('public_appraiser_domain')) {
return $this->forward(AppraiserController::class . '::homepage', [
'authenticationUtils' => $authenticationUtils,
'serviceFormRepository' => $serviceFormRepository,
'serviceSectionGroupRepository' => $serviceSectionGroupRepository,
]);
}
list($error, $lastUsername, $groupsWithSections, $paperCopy) =
$this->getLoginPageData($authenticationUtils, $serviceSectionGroupRepository, $serviceFormRepository);
// Костыль, но для срочности. Определим правельный paperCopy, из релевантного groupsWithSections
// TODO переработать
/** @see 271 */
foreach($groupsWithSections[0]['sections'] as $section) {
foreach($section['serviceForms'] as $form) {
if($form['icon'] !== 'paper-copy') {
continue;
}
$paperCopy = $form;
}
}
return $this->render('publicPages/notaryLandingPage.html.twig',
[
'controller_name' => 'Сервис электронной оценки',
'is_login' => true,
'last_username' => $lastUsername,
'error' => $error,
'group' => $groupsWithSections[0],
'paperCopy' => $paperCopy,
]);
}
/**
* @Route("/remote/login", name="app_login_ajax", methods={"GET", "POST"})
*/
public function loginAjax(AuthenticationUtils $authenticationUtils): Response
{
// Если пользователь уже авторизован (успешный логин)
if ($this->isGranted('ROLE_USER')) {
$redirectUrl = $this->generateUrl('area_client_index');
if ($this->isGranted('ROLE_NOTARY')) {
$redirectUrl = $this->generateUrl('area_notary_index');
}
if ($this->isGranted('ROLE_PARTNER')) {
$redirectUrl = $this->generateUrl('area_partner_index');
}
if ($this->isGranted('ROLE_WORKER')) {
$redirectUrl = $this->generateUrl('area_notary_index');
}
if ($this->isGranted('ROLE_INFO_NOT')) {
$redirectUrl = $this->generateUrl('area_infonot_balance');
}
if ($this->isGranted('ROLE_REFOVOD')) {
$redirectUrl = $this->generateUrl('area_refovod_balance');
}
return $this->response([
'success' => true,
'redirect' => $redirectUrl
]);
}
$error = $authenticationUtils->getLastAuthenticationError();
if ($error) {
return $this->response(['error' => $error->getMessage()], 400);
}
// Если нет ошибки и пользователь не аутентифицирован - значит форма еще не отправлена
return $this->response(['error' => 'Неверный email или пароль'], 400);
}
/**
* @Route("/r-p/{code}", name="app_main_referal")
*/
public function mainForReferal(
string $code,
AuthenticationUtils $authenticationUtils,
ServiceFormRepository $serviceFormRepository,
ServiceSectionGroupRepository $serviceSectionGroupRepository,
): Response
{
if ($this->isGranted('ROLE_NOTARY')) {
return $this->redirectToRoute('area_notary_index');
}
list($error, $lastUsername, $groupsWithSections, $paperCopy) =
$this->getLoginPageData($authenticationUtils, $serviceSectionGroupRepository, $serviceFormRepository);
// Костыль, но для срочности. Определим правельный paperCopy, из релевантного groupsWithSections
// TODO переработать
/** @see 271 */
foreach($groupsWithSections[0]['sections'] as $section) {
foreach($section['serviceForms'] as $form) {
if($form['icon'] !== 'paper-copy') {
continue;
}
$paperCopy = $form;
}
}
return $this->render('publicPages/notaryLandingPage.html.twig',
[
'controller_name' => 'Сервис электронной оценки',
'is_login' => true,
'last_username' => $lastUsername,
'error' => $error,
'group' => $groupsWithSections[0],
'paperCopy' => $paperCopy,
'registerCode' => $code,
]);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
protected function getLoginPageData(
AuthenticationUtils $authenticationUtils,
ServiceSectionGroupRepository $serviceSectionGroupRepository,
ServiceFormRepository $serviceFormRepository,
): array
{
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
$groupsWithSections = $serviceSectionGroupRepository->getList();
$services = [];
foreach ($serviceFormRepository->findAll() ?? [] as $service) {
$services[$service->getId()] = $service;
}
$paperCopy = 0;
foreach ($groupsWithSections as $key => &$group) {
foreach ($group['sections'] as $sectionKey => $section) {
foreach ($section['serviceForms'] ?? [] as $serviceForm) {
if ($services[$serviceForm['id']]->getIcon() === 'paper-copy') {
//Отдельно отчет
$paperCopy = $services[$serviceForm['id']];
continue;
}
$groupsWithSections[$key]['sections'][$sectionKey]['forms'][] = $services[$serviceForm['id']];
}
}
$group['sections'] = array_reverse($group['sections']);
}
return [$error, $lastUsername, $groupsWithSections, $paperCopy];
}
}