<?php
namespace App\Controller;
use App\Form\User\UserForgottenPasswordType;
use App\Form\User\UserResetPasswordType;
use App\Manager\TokenManager;
use App\Model\Operation\Draw;
use App\Model\Token;
use App\Service\APIKiwi;
use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
use KnpU\OAuth2ClientBundle\Client\Provider\FacebookClient;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
class SecurityController extends APIController
{
/**
* @Route("/connexion", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
$this->redirectionDraw();
if ($this->getUser()) {
return $this->redirectToRoute('kiwi_homepage');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
if ($error) {
$error = 'Email ou mot de passe incorrect';
}
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'target_path' => $this->requestStack->getSession()->get('_target_path'),
'target_path_params' => $this->requestStack->getSession()->get('_target_path_params'),
]);
}
/**
* @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.');
}
/**
* @Route("/mot-de-passe-oublie", name="kiwi_forgotten_password_user")
*/
public function forgottenPassword(Request $request, APIKiwi $APIKiwi)
{
$form = $this->createForm(UserForgottenPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$response = $APIKiwi->postPublicKiwi([
'path' => '/public/request-reset-password',
'data' => [
'templateId' => $_ENV['TEMPLATE_FORGOTTEN_PASSWORD_ID'],
'email' => $data->getEmail(),
'url' => $request->getSchemeAndHttpHost().'/reinitialiser-mot-de-passe/'
]
]);
$error = null;
if ($response->getStatusCode() === 200) {
$error = json_decode($response->getContent(), true)['error'];
}
return $this->render('user/success_forgotten_password.html.twig', ['error' => $error]);
}
return $this->render('user/forgotten_password.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/reinitialiser-mot-de-passe/{token}", name="kiwi_reinit_password_user")
*/
public function resetPassword(Request $request, APIKiwi $APIKiwi, $token, TokenManager $tokenManager, TranslatorInterface $translator)
{
$data = $APIKiwi->getPublicKiwi('tokens/'.$token);
$token = $this->deserialize($data->getContent(), Token::class, 'get_token');
if (!$tokenManager->checkValidityToken($token)) {
return $this->render('user/expired_token.html.twig');
}
$form = $this->createForm(UserResetPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$url = sprintf(
'/users/%s/tokens/%s',
$token->getUser()->getId(),
$token->getId()
);
$APIKiwi->putPublicKiwi(
$url,
[
'data' => [
'plainPassword' => $data->getPlainPassword(),
]
]);
$this->addFlash('success', $translator->trans('default.forgotten_password.success.reset_password'));
return $this->redirectToRoute('app_login');
}
return $this->render('user/reset_password.html.twig', [
'form' => $form->createView(),
]);
}
private function redirectionDraw()
{
if ('kiwi_operation_draw_show' === $this->requestStack->getSession()->get('_target_path')) {
$drawResp = $this->APIKiwi->getPublicKiwi('draw/'. $this->requestStack->getSession()->get('kiwi_operation_draw_id'));
$draw = $this->deserialize($drawResp->getContent(), Draw::class, 'get_draw');
if (Draw::DRAW_TYPE_DEMAT === $draw->getDrawType()) {
$this->requestStack->getSession()->set('_target_path', 'kiwi_participation_confirm_register_participation_draw');
} else {
$this->requestStack->getSession()->set('_target_path', 'kiwi_operation_draw_address_delivery_user');
}
}
}
/**
* @param ClientRegistry $clientRegistry
* @Route("/connect/facebook", name="facebook_connect")
*/
public function connect(ClientRegistry $clientRegistry): RedirectResponse
{
/** @var FacebookClient $client */
$client = $clientRegistry->getClient('facebook');
return $client->redirect([
'public_profile', 'email', 'hometown'
]);
}
/**
* @Route("/supprimer-compte/", name="kiwi_soft_delete_user")
*/
public function softDelete()
{
$userId = $this->getUser()->getId();
$templateId = $_ENV['TEMPLATE_DELETE_ACCOUNT_ID'];
try {
$this->APIKiwi->postKiwi([
'path' => sprintf('/users/softdelete/%s/%s', $userId, $templateId),
'token' => $this->getUser()->getToken(),
'templateId' => $templateId,
]);
} catch (\Exception $exception) {
throw new BadRequestHttpException($exception->getMessage());
}
return $this->redirectToRoute('app_logout');
}
/**
* @Route("/telecharger-mes-donnees/", name="kiwi_download_personnal_data_user")
*/
public function downloadpersonalData()
{
$userId = $this->getUser()->getId();
try {
$response = $this->APIKiwi->getKiwi([
'path' => sprintf('/users/download-personal-data/%s', $userId),
'token' => $this->getUser()->getToken(),
]);
} catch (\Exception $exception) {
throw new BadRequestHttpException($exception->getMessage());
}
return $this->redirect(json_decode($response->getContent(), true)['url']);
}
}