<?php
namespace App\Controller;
use App\Entity\AppUser;
use App\Form\ActivationTokenAgainType;
use App\Form\ChangePasswordType;
use App\Form\ForgottenPasswordType;
use App\Form\RegistrationType;
use App\Form\ProfileType;
use App\Model\UrlGenerator;
use App\Traits\Uploader;
use App\Validator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\String\Slugger\SluggerInterface;
class SecurityController extends DefaultController
{
use UrlGenerator;
use Validator;
use Uploader;
private $userRepository;
private $encoder;
private $mailer;
private $router;
private $eventDispatcher;
private $entityManager;
public function __construct(EntityManagerInterface $em,UserPasswordEncoderInterface $encoder,\Swift_Mailer $mailer,RouterInterface $router)
{
$this->userRepository = $em->getRepository(AppUser::class);
$this->encoder = $encoder;
$this->mailer = $mailer;
$this->router = $router;
$this->entityManager = $em;
}
/**
* @Route("/registrace", name="app_registration")
*/
public function registration(Request $request) :Response
{
$user = new AppUser();
$appParameters = $this->loadAppParameters();
$publicKey = $appParameters['Captcha']['public-key'];
$clientIPAdress = $_SERVER['REMOTE_ADDR'] == '::1' ? '89.24.215.86' : $_SERVER['REMOTE_ADDR'];
$form = $this->createForm(RegistrationType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
/* get recaptcha */
$recaptchaResponse = $form->get('recaptchaResponse')->getData();
// $recaptchaResponse2 = $form->get('g-recaptcha-response')->getData();
$recaptchaSecret = $appParameters['Captcha']['secret-key'];
$post_data = http_build_query(
array(
'secret' => $recaptchaSecret,
'response' => $recaptchaResponse,
'remoteip' => $clientIPAdress
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$recaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
// ziskani recaptcha ranku
//$recaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify'. '?secret=' . $recaptchaSecret . '&response=' . $recaptchaResponse . 'remoteip=' . $clientIPAdress);
$recaptcha = json_decode($recaptcha);
if ($recaptcha->success == false)
{
print_r($recaptcha);
print($clientIPAdress);
print_r($recaptchaResponse);
// print_r($recaptchaResponse2);
die;
// $errorMessage = $recaptcha->error-codes;
$this->addFlash(
'error',
'Chyba při ověřování uživatele, reCAPTCHAerror, zkuste prosím registraci později.'
);
return $this->redirectToRoute('app_login');
}
print_r($recaptcha);
if ($recaptcha->success)
{
$hash = $this->encoder->encodePassword($user, $user->getPassword());
$user->setPassword($hash)
->setRoles(['ROLE_USER']);
$this->userRepository->newUser($user);
$url = $this->getFullUrl($this->router,
$this->generateUrl('app_activate', ['token' => $user->getActivationToken()])
);
$this->sendLinkByEmail('AKTIVACE ÚČTU',
$appParameters['Email']['no-reply'],
$user->getEmail(),
'emails/activate_account.html.twig',
$url);
$this->addFlash(
'success',
'Registrace proběhla úspěšně. Na váš email jsem vám zaslali aktivační link.'
);
return $this->redirectToRoute('app_login');
}
}
return $this->render('security/registration.html.twig',array('form' =>$form->createView(),'publicKeyCaptcha' => $publicKey ) );
}
/**
* @param $token
* @Route ("/aktivace-uctu={token}", name="app_activate")
*/
public function activateAccount($token) : Response
{
$user = $this->userRepository->findOneBy(['activationToken' => $token]);
if(!$user)
return $this->redirectToRoute('app_login',['activation' => false]);
$user
->setActive(true)
->setActivationToken(null);
$this->userRepository->update($user);
$this->addFlash(
'success',
'Učet byl úspěšně aktivován'
);
return $this->redirectToRoute('app_login');
}
/**
* @return Response
* @Route ("/poslat-znovu-aktivacni-email", name="app_activate_again")
*/
public function sendActivationTokenAgain(Request $request)
{
$form = $this->createForm(ActivationTokenAgainType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$email = $form->get('email')->getData();
$user = $this->userRepository
->findOneBy(['email' => $email]);
if (!$user) {
$this->addFlash(
'error',
'Uživatel s touto emailovou adresou nebyl nazelen.'
);
return $this->redirectToRoute('app_activate_again');
}
if ($user->isActive()) {
$this->addFlash(
'error',
'Učet byl již aktivován !'
);
return $this->redirectToRoute('app_activate_again');
}
$token = $this->userRepository
->setNewActivationToken($user);
if (!$token) {
$this->addFlash(
'warning',
'Autorizační token je možné vygenerovat jednou za půl hodiny.'
);
return $this->redirectToRoute('app_activate_again');
}
$url = $this->getFullUrl( $this->router,
$this->generateUrl('app_activate',['token' => $token])
);
$appParameters = $this->loadAppParameters();
$this->sendLinkByEmail('AKTIVACE ÚČTU',
$appParameters['Email']['no-reply'],
$user->getEmail(),
'emails/activate_account.html.twig',
$url);
$this->addFlash(
'success',
'Váš účet byl úspěšně vytvořen. Na vámi zadanou emailovou adresu jsme vám poslalí aktivační link'
);
return $this->redirectToRoute('app_login');
}
return $this->render('security/activation_token_again.html.twig',[ 'form' => $form->createView() ]);
}
/**
* @Route("/", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
return $this->redirectToRoute('app_dashboard');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @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.');
}
public function sendLinkByEmail($subject,$from,$to,$template,$url)
{
$message = (new \Swift_Message($subject))
->setFrom($from)
->setTo($to)
->setBody(
$this->renderView(
$template,
['url' => $url]
),
'text/html'
)
;
return $this->mailer->send($message);
}
/**
* @Route ("/zadost-zmena-hesla",name="app_forgotten_password")
*/
public function forgottenPasswordRequest(Request $request)
{
$form = $this->createForm(ForgottenPasswordType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$email = $form->get('email')->getData();
$user = $this->userRepository
->findOneBy(['email' => $email]);
if (!$user) {
$this->addFlash(
'error',
'Uživatel s touto emailovou adresou nebyl nazelen.'
);
return $this->redirectToRoute('app_forgotten_password');
}
$token = $this->userRepository
->setNewForgottenToken($user);
if ($token == false) {
$this->addFlash(
'warning',
'O změnu hesla je možne požádat každých 30 minut'
);
return $this->redirectToRoute('app_forgotten_password');
}
$url = $this->getFullUrl( $this->router,
$this->generateUrl('app_change_password',['token' => $token])
);
$appParameters = $this->loadAppParameters();
$emailStatus = $this->sendLinkByEmail('ZMĚNA HESLA',
$appParameters['Email']['no-reply'],
$user->getEmail(),
'emails/forgotten_password.html.twig',
$url
);
if ($emailStatus == 0)
{
$this->addFlash(
'warning',
'Chyba při odesílání emailu'
);
}
elseif ($emailStatus > 0)
{
$this->addFlash(
'success',
'Email ke změně hesla byl úspěšně odeslán. Zkontrolujte si emailovou schránku'
);
}
else
{
$this->addFlash(
'warning',
'Neznámý chybový stav (email)'
);
}
return $this->redirectToRoute('app_login');
}
return $this->render('security/forgotten_password.html.twig',['form' => $form->createView()]);
}
/**
* @Route ("/zmena-hesla={token}",name="app_change_password")
*/
public function changePassword($token, Request $request)
{
$user = $this->userRepository
->findOneBy(['lostPasswordToken' => $token]);
if (!$user) {
$this->addFlash(
'error',
'Autorizační token není možné najít'
);
return $this->redirectToRoute('app_login');
}
$form = $this->createForm(ChangePasswordType::class,$user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$password = $form->get('password')->getData();
$hash = $this->encoder->encodePassword($user, $password);
$user->setPassword($hash);
$this->userRepository->update($user);
$this->addFlash(
'success',
'Vaše heslo bylo uspěšně změněno. Můžete se přihlásit'
);
return $this->redirectToRoute('app_login');
}
return $this->render('security/forgotten_password_change.html.twig',['form' => $form->createView()]);
}
/**
* @Route("/profil", name="app_editProfile")
*/
public function editProfile(Request $request,SluggerInterface $slugger)
{
$profile = $this->userRepository->find($this->getUser()->getId());
$signExists = is_null($profile->getSign()) ? true : false;
if (is_null($profile)) {
$this->addFlash(
'error',
'Tohoto uživatele není možné najít'
);
return $this->redirectToRoute('app_registration');
}
$form = $this->createForm(ProfileType::class,$profile,['signNotExist' => $signExists]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$signatureFile = $form->get('signatureFile')->getData();
if (!empty($signatureFile)) {
$fileInfo = getimagesize($signatureFile);
$signValid = $this->imageValidate($fileInfo,array('width' =>300,'height' =>100 ));
if ($signValid['valid'] == false)
{
$this->addFlash(
'error',
$signValid['message']
);
return $this->redirectToRoute('app_editProfile');
}
// smaze se puvodni soubor s podpisem
$oldSign = $profile->getSign();
if ($oldSign) {
$this->remove($this->getParameter('dir_signatures') . '/' . $oldSign);
}
$originalFilename = pathinfo($signatureFile->getClientOriginalName(), PATHINFO_FILENAME);
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$signatureFile->guessExtension();
try {
$signatureFile->move(
$this->getParameter('dir_signatures'),
$newFilename
);
$profile->setSign($newFilename);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
}
$password = $form->get('password')->getData();
if (!empty($password)) {
$hash = $this->encoder->encodePassword($profile, $password);
$profile->setPassword($hash);
}
$this->userRepository->update($profile);
$this->addFlash('success','Profil aktualizován');
return $this->redirectToRoute('app_editProfile');
}
return $this->render('security/profile.html.twig',['form' => $form->createView()]);
}
}