<?php
namespace App\Controller\masteradminController;
use App\Controller\oAuthLoginController\LoginController;
use App\Entity\User;
use App\Entity\UserProfil;
use App\Repository\FirebaseNotificationRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Uid\Uuid;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils, Request $request): Response
{
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$loginError = $request->hasSession() ? $request->getSession()->get('login_error', '') : '';
$request->getSession()->remove('login_error');
return $this->render('security/login.html.twig',
[
'last_username' => $lastUsername,
'error' => $error,
'login_error' => $loginError
]
);
}
#[Route(path: '/app-login', name: 'smartphone_app_login')]
public function app_login(Request $request,
FirebaseNotificationRepository $firebaseNotificationRepository,
TokenStorageInterface $tokenStorage,
LoginController $loginController,
LoggerInterface $logger): Response
{
$token = $request->query->get('token');
$model = $request->query->get('model');
$goUrl = $request->query->get('goUrl');
$request->getSession()->set('appUser', true);
$logger->error('Token:' . $token);
$logger->error('model:' . $model);
$logger->error('goUrl:' . $goUrl);
$url = $_ENV["WEBSITE_URL"] . '/user/start';
$url2 = $_ENV["WEBSITE_URL"] . '/logout';
$url3 = $_ENV["WEBSITE_URL"] . '/user/firma/startseite/0/info';
if(strlen($goUrl) > 5) {
$url = $goUrl;
}
if(strlen($token) < 10 || strlen($model) < 3) {
return $this->redirect($url);
}
$logger->error('erfolgreich 1');
$firebaseToken = $firebaseNotificationRepository->findOneBy(['token' => $token]);
if($firebaseToken == null) {
return $this->redirect($url);
}
$logger->error('erfolgreich 2');
$differenz = $firebaseToken->getDatum()->diff(new \DateTime('now', new \DateTimeZone('Europe/Berlin')));
if($differenz->days > 365) {
return $this->redirect($url);
}
$logger->error('erfolgreich 3');
/*
$deviceInformation = json_decode($firebaseToken->getDeviceInformation(), true);
if($deviceInformation['model'] != $model) {
return $this->redirectToRoute('user_start');
}
*/
$tokenEinstellungen = json_decode($firebaseToken->getEinstellungen(), true);
if($tokenEinstellungen['auto-login'] != 1) {
return $this->redirect($url2);
}
$logger->error('erfolgreich 4');
$request->getSession()->set('appUserTyp', $firebaseToken->getTyp());
//Login
$loginController->loginUser($firebaseToken->getUser(), $tokenStorage, $request);
$request->getSession()->set('firebaseToken', $firebaseToken->getToken());
if(strlen($goUrl) < 6) {
if ($firebaseToken->getUser()->getFirmenProfil() != null) {
$url = $url3;
}
}
$logger->error('Login erfolgreich');
return $this->redirect($url);
}
#[Route(path: '/login/registrierung', name: 'app_login_registrierung')]
public function registerAccount(Request $request,
UserRepository $userRepository,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordHasherEncoder,
MailerInterface $mailer,
UrlGeneratorInterface $urlGenerator,
HttpClientInterface $client): Response
{
$responseData = [];
$responseData['success'] = false;
$responseData['message'] = '';
//Validierung
$vorname = $request->get('vorname');
$nachname = $request->get('nachname');
$email = $request->get('email');
$password = $request->get('password');
$newsletter = $request->get('newsletter');
if ($vorname == null || strlen($vorname) < 1) {
$responseData['message'] = 'Bitte Vorname angeben!';
return new JsonResponse($responseData);
}
if ($nachname == null || strlen($nachname) < 1) {
$responseData['message'] = 'Bitte Nachname angeben!';
return new JsonResponse($responseData);
}
if ($email == null || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
$responseData['message'] = 'Bitte gültige E-Mail angeben!';
return new JsonResponse($responseData);
}
if ($password == null || strlen($password) < 6) {
$responseData['message'] = 'Bitte längeres Kennwort!';
return new JsonResponse($responseData);
}
if (!is_numeric($newsletter)) {
$newsletter = 1;
}
//Validierung ReCaptcha
$recaptchaResponse = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'body' => [
'secret' => $_ENV["RECAPTCHA_SECRET"],
'response' => $request->get('g-recaptcha-response')
]
])->toArray();
if ($recaptchaResponse['success'] !== true || $recaptchaResponse['hostname'] !== $_SERVER['SERVER_NAME']) {
$responseData['message'] = 'Bitte Captcha neu ausführen';
return new JsonResponse($responseData);
}
//TODO Check AGB
//Prüfe ob Email schon vergeben
$emailCheckUser = $userRepository->findOneBy(['email' => $email]);
if ($emailCheckUser != null) {
$responseData['message'] = 'Diese E-Mail Adresse wurde bereits registriert!';
return new JsonResponse($responseData);
}
//Benutzer anlegen
$userID = $this->kontoErstellen($vorname, $nachname, $email, $password, 0, $newsletter, $userRepository, $entityManager, $passwordHasherEncoder);
$userNeu = $userRepository->findOneBy(['id' => $userID]);
//Optin Email Versenden
$this->sendOptinEmail($userNeu, $urlGenerator, $mailer);
/*$optinLink = $urlGenerator->generate('login_registrierung_ok', ['guid' => $userNeu->getGuid()], UrlGeneratorInterface::ABSOLUTE_URL);
$email = (new Email())
->from($_ENV["MAILER_SENDER"])
->to($email)
->subject('handwerkXcampus Bestätigungsemail')
->html('<p>Bestätigungstext</p><br><a href="' . $optinLink . '">Bestätigungslink</a>');
$mailer->send($email);*/
$responseData['success'] = true;
return new JsonResponse($responseData);
}
#[Route(path: '/login/registrierung/ok/{guid}', name: 'login_registrierung_ok')]
public function registrierungOK($guid, UserRepository $userRepository, EntityManagerInterface $entityManager): Response
{
$error = '';
$guidRichtig = $userRepository->findOneBy(['guid' => $guid]);
if ($guidRichtig != null) {
$guidRichtig->setFreigeschaltet(1);
$guidRichtig->setGuid(null);
$entityManager->persist($guidRichtig);
$entityManager->flush();
} else {
$error = 'Falscher Bestätigungscode!';
}
return $this->render('security/registrierung_ok.html.twig', ['error' => $error]);
}
#[Route(path: '/user/neue/mailadresse/{guid}', name: 'user_neue_mailadresse')]
public function login_neue_mailadresse($guid, UserRepository $userRepository, EntityManagerInterface $entityManager): Response
{
$error = '';
$ergebnis = '';
$user = $userRepository->findOneBy(['guid' => $guid]);
if ($user != null) {
$neueMail = $user->getAenderung();
$aenderungsIndex = $user->getAenderungsindex();
if ($aenderungsIndex == 1) {
$ergebnis = 'Die neue E-Mail Adresse für den Login wurde übernommen.';
$user->setEmail($neueMail);
$user->setProvisorischerMitarbeiter(null);
}
$user->setAenderung(null);
$user->setAenderungsindex(null);
$user->setGuid(null);
$entityManager->persist($user);
$entityManager->flush();
if ($aenderungsIndex == 2) {
$ergebnis = 'Die neue Benachrichtigungs E-Mail Adresse wurde übernommen.';
$userProfil = $user->getUserProfil();
$userProfil->setMailversand($neueMail);
$entityManager->persist($userProfil);
$entityManager->flush();
}
} else {
$error = 'Falscher Bestätigungscode, oder Änderungen wurden bereits übernommen!';
}
return $this->render('security/neue_email_adresse.html.twig', ['error' => $error, 'ergebnis' => $ergebnis]);
}
public function sendOptinEmail(User $user, UrlGeneratorInterface $urlGenerator, MailerInterface $mailer)
{
$optinLink = $urlGenerator->generate('login_registrierung_ok', ['guid' => $user->getGuid()], UrlGeneratorInterface::ABSOLUTE_URL);
$emailHTML = $this->render('emails/registrierung.html.twig', [
'preheader' => 'Bestätigung deiner Registrierung im handwerkXcampus',
'optinLink' => $optinLink,
'user' => $user,
])->getContent();
$email = (new Email())
->from($_ENV["MAILER_SENDER_NO_REPLY"])
->to($user->getEmail())
->subject('handwerkXcampus Registrierung')
->html($emailHTML);
$mailer->send($email);
}
public function sendNeueMailadresseEmail(User $user, UrlGeneratorInterface $urlGenerator, MailerInterface $mailer)
{
$optinLink = $urlGenerator->generate('user_neue_mailadresse', ['guid' => $user->getGuid()], UrlGeneratorInterface::ABSOLUTE_URL);
$emailHTML = $this->render('emails/neue_login_mailadresse.html.twig', [
'preheader' => 'Du möchtest deine E-Mail Adresse für den Login ändern?',
'optinLink' => $optinLink,
'user' => $user,
])->getContent();
$email = (new Email())
->from($_ENV["MAILER_SENDER_NO_REPLY"])
->to($user->getAenderung())
->subject('handwerkXcampus Änderung der Login E-Mail Adresse')
->html($emailHTML);
$mailer->send($email);
}
public function sendNeueVersandmailadresseEmail(User $user, UrlGeneratorInterface $urlGenerator, MailerInterface $mailer)
{
$optinLink = $urlGenerator->generate('user_neue_mailadresse', ['guid' => $user->getGuid()], UrlGeneratorInterface::ABSOLUTE_URL);
$emailHTML = $this->render('emails/neue_benachrichtigungs_mailadresse.html.twig', [
'preheader' => 'Du möchtest deine E-Mail Adresse für Benachrichtigungen ändern?',
'optinLink' => $optinLink,
'user' => $user,
])->getContent();
$email = (new Email())
->from($_ENV["MAILER_SENDER_NO_REPLY"])
->to($user->getAenderung())
->subject('handwerkXcampus Änderung der Benachrichtigungs E-Mail Adresse')
->html($emailHTML);
$mailer->send($email);
}
public function sendKennwortVergessenEmail(User $user, UrlGeneratorInterface $urlGenerator, MailerInterface $mailer)
{
$optinLink = $urlGenerator->generate('user_kennwort_neu', ['guid' => $user->getGuid()], UrlGeneratorInterface::ABSOLUTE_URL);
$emailHTML = $this->render('emails/kennwort_vergessen.html.twig', [
'preheader' => 'Du möchtest dein Kennwort für den handwerkXcampus zurücksetzen?',
'optinLink' => $optinLink,
'user' => $user,
])->getContent();
$email = (new Email())
->from($_ENV["MAILER_SENDER_NO_REPLY"])
->to($user->getEmail())
->subject('handwerkXcampus Kennwort zurücksetzen')
->html($emailHTML);
$mailer->send($email);
}
#[Route(path: '/user/kennwort/neu/{guid}', name: 'user_kennwort_neu')]
public function user_kennwort_neu($guid, UserRepository $userRepository, EntityManagerInterface $entityManager): Response
{
$user = null;
$neueGuid = null;
if ($guid == 'kennwort_neu') {
$neueGuid = Uuid::v4();
$user = $userRepository->findOneBy(['id' => $this->getUser()->getId()]);
if ($user == null) {
return $this->redirectToRoute('user_start');
}
$user->setGuid($neueGuid);
$entityManager->persist($user);
$entityManager->flush();
} else {
$user = $userRepository->findOneBy(['guid' => $guid]);
$neueGuid = $user?->getGuid();
}
return $this->render('security/kennwort_zuruecksetzen.html.twig', ['user' => $user, 'guid' => $neueGuid]);
}
public function kontoErstellen($vorname, $nachname, $email, $password, $freigeschaltet, $newsletter,
UserRepository $userRepository,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordHasherEncoder): int
{
$datum = new \DateTime('now', new \DateTimeZone('Europe/Berlin'));
$user = new User();
$user->setEmail(strtolower($email));
$user->setFreigeschaltet($freigeschaltet);
$user->setGuid(Uuid::v4());
$user->setAngelegtAm($datum);
$user->setLetzterLogin($datum);
$user->setFirmenProfil(null);
$user->setZweiFaktor(0);
$user->setNeueRoles(null);
$hashedPassword = '';
if (strlen($password) > 0) {
$hashedPassword = $passwordHasherEncoder->hashPassword($user, $password);
}
$user->setPassword($hashedPassword);
$user->setRoles((array)["ROLE_MITGLIED"]);
$entityManager->persist(($user));
$entityManager->flush();
$neueID = $user->getId();
$userProfil = new UserProfil();
$userNeu = $userRepository->findOneBy(['id' => $neueID]);
$userProfil->setUser($userNeu);
$userProfil->setVorname($vorname);
$userProfil->setNachname($nachname);
$userProfil->setMailversand(strtolower($email));
$userProfil->setNewsletter($newsletter);
$entityManager->persist(($userProfil));
$entityManager->flush();
return $neueID;
}
#[Route(path: '/logout_intern', name: 'app_logout_intern')]
public function logout_intern(): void
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
#[Route(path: '/logout', name: 'app_logout')]
public function logout (Request $request, FirebaseNotificationRepository $firebaseNotificationRepository, EntityManagerInterface $entityManager): RedirectResponse
{
$redirectResponse = $this->redirectToRoute('app_logout_intern');
$firebaseToken = $request->getSession()->get('firebaseToken');
if($firebaseToken != null) {
$firebaseTokenObj = $firebaseNotificationRepository->findOneBy(['token' => $firebaseToken, 'user' => $this->getUser()]);
if($firebaseTokenObj != null) {
$firebaseEinstellungen = json_decode($firebaseTokenObj->getEinstellungen(), true);
$firebaseEinstellungen['auto-login'] = 0;
$firebaseTokenObj->setEinstellungen(json_encode($firebaseEinstellungen));
$entityManager->persist($firebaseTokenObj);
$entityManager->flush();
$redirectResponse->headers->setCookie(Cookie::create('app_user', true));
}
}
return $redirectResponse;
}
#[Route(path: '/after-logout', name: 'app_logout_after')]
public function after_logout (Request $request): RedirectResponse
{
if($request->cookies->get('app_user')) {
$request->getSession()->set('appUser', true);
}
return $this->redirectToRoute('user_start');
}
}