<?php
namespace App\Controller;
use App\Entity\CompanySettings;
use App\Entity\CompanyUser;
use App\Entity\TcUserType;
use App\Entity\User;
use App\Repository\CompanyRepository;
use App\Utils\CompanyHelper;
use App\Utils\MailSpool;
use App\Utils\UserManageHelper;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
class SecurityController extends AbstractController
{
private $CompanyRepository;
private $translator;
private $mailSpool;
private $em;
private $passwordHasher;
/**
* @var Container
*/
public $container;
public function __construct(CompanyRepository $CompanyRepository, MailSpool $mailSpool, EntityManagerInterface $entityManager, TranslatorInterface $translator, UserPasswordHasherInterface $passwordHasher)
{
$this->em = $entityManager;
$this->CompanyRepository = $CompanyRepository;
$this->translator = $translator;
$this->passwordHasher = $passwordHasher;
}
/**
* @Route("/login", name="app_login")
* User login
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
if (array_intersect(['ROLE_DAILY_PLAN_VIEW', 'ROLE_DAILY_PLAN_ADMIN', 'ROLE_ADMIN', 'ROLE_USER'], $this->getUser()->getRoles())) {
return $this->redirectToRoute('line_manager');
} elseif (array_intersect(['ROLE_OPERATOR_SETTINGS_ADMIN', 'ROLE_OPERATOR_SETTINGS_VIEW'], $this->getUser()->getRoles())) {
return $this->redirectToRoute('workstation_operator');
} else {
return $this->redirectToRoute('user');
}
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/signin.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}
/**
* @Route("/logout", name="app_logouts")
*/
public function logout()
{
// throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
/**
* save invite user details.
*
* @return JsonResponse
*/
public function userRegistration(Request $request, UserManageHelper $userManageHelper, CompanyHelper $CompanyHelper, ?ContainerInterface $container = null)
{
$data = '';
$postData = $request->get('formdata');
$recaptcha = $postData['g-recaptcha-response'];
$secret_key = $container->getParameter('recaptcha_saas_secret');
$url = 'https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$recaptcha;
$response = file_get_contents($url);
$response = json_decode($response);
if (true != $response->success) {
return new JsonResponse(['msg' => 'verify the recaptcha', 'status' => 'error']);
}
if (empty($postData['company_id'])) {
$postData['plan_validity'] = $container->getParameter('plan_validity');
$companyData = $CompanyHelper->createCompany($postData);
$postData['company_id'] = $companyData['companyId'];
$postData['user_type'] = $companyData['adminUserTypeId'];
$postData['reg_type'] = 'user_registration';
$userTypeObj = $this->em->getRepository(TcUserType::class)->find($companyData['adminUserTypeId']);
} else {
$postData['reg_type'] = 'user_invite_registration';
$userTypeObj = $this->em->getRepository(TcUserType::class)->find($postData['user_type']);
// Restriction for user create according to plans
$noOfUsers = $this->em->getRepository(CompanySettings::class)->getDefaultUserByCompanyId($postData['company_id']);
$userCount = $this->em->getRepository(CompanyUser::class)->getUserCountByCompanyId($postData['company_id']);
if ($noOfUsers < $userCount) {
return new JsonResponse(['message' => $this->translator->trans('SIGN_UP_PLAN_LIMIT_WARNING'), 'status' => 'limitExceeded']);
}
}
if (isset($postData['invite_id']) && '' !== $postData['invite_id']) { // If invited user
$postData['is_verified'] = 1;
}
$postData['roles'] = json_decode($userTypeObj->getRoles());
if (!empty($postData)) {
$data = $userManageHelper->signUpUser($postData);
$postData['userId'] = $data['userId'];
}
return new JsonResponse(['msg' => $this->translator->trans('USER_ADDED_SUCCESS_MSG'), 'data' => $data, 'status' => 'success']);
}
/**
* To send mail by $mailLogId from route path.
*
* @param type $mailLogId
*
* @return JsonResponse
*/
public function sendMailAction($mailLogId, MailSpool $mailSpool, Request $request)
{
$mailLogIdArray = $request->get('mailLogIds');
if (!empty($mailLogId) && 0 == !$mailLogId) {
$mailSpool->sendFromSpool($mailLogId);
}
if (!empty($mailLogIdArray)) {
$mailSpool->sendFromSpool($mailLogId);
}
return new JsonResponse(['msg' => $mailLogId.' - Mail sent!!', 'status' => 'success']);
}
/**
* Method signupVerificationAction.
*
* @param int $userId
*
* @return void
*/
public function signupVerificationAction($userId, Request $request)
{
$userId = $userId;
$data = $this->em->getRepository(User::class)->getUserDetailsById($userId);
return $this->render('security/verification.html.twig', ['data' => $data]);
}
/**
* function for terms and conditions.
*/
public function termsAndConditions()
{
return $this->render('security/terms_conditions.html.twig');
}
/**
* Method privacyPolicy.
*
* @return void
*/
public function privacyPolicy()
{
return $this->render('security/privacy_policy.html.twig');
}
/**
* Method endUserLicenseAgreement.
*
* @return void
*/
public function endUserLicenseAgreement()
{
return $this->render('security/end_user_license_agreement.html.twig');
}
/**
* Method saveNewUserPassword.
*
* @return void
*/
public function saveNewUserPassword(Request $request)
{
$details = $request->get('formData');
$params = $details['setPassword'];
$user = $this->em->getRepository(User::class)->findOneBy([
'id' => $params['userId'],
]);
$params['loginUserId'] = $params['userId'];
$params['password'] = $this->passwordHasher->hashPassword($user, $params['password']);
$this->em->getRepository(User::class)->save($params, $params['userId']);
return new JsonResponse(['msg' => $this->translator->trans('PROFILE_UPDATED'), 'status' => 'success']);
}
/**
* Method checkUserEmail - to check for any existing users.
*
* @return JsonResponse
*/
public function checkUserEmail(Request $request, UserManageHelper $userManageHelper)
{
$email = $request->get('email');
$checkEmail = $this->em->getRepository(User::class)->isUserExist($email);
if ($checkEmail) {
return new JsonResponse(['status' => 'error', 'msg' => $this->translator->trans('ALREADY_EXISTS')]);
} else {
return new JsonResponse(['status' => 'success', 'result' => 'ok', 'valid' => true]);
}
}
/**
* Method checkInvalidEmail - to restrict unwanted mail-ids.
*
* @return JsonResponse
*/
public function checkInvalidEmail(Request $request, UserManageHelper $userManageHelper)
{
$invalidEmails = $userManageHelper->getInvalidEmails();
$email = $request->get('inv-email');
$emailSuffix = substr($email, strpos($email, '@') + 1);
if (in_array($emailSuffix, $invalidEmails)) {
return new JsonResponse(['status' => 'error', 'msg' => $this->translator->trans('EMAIL_VALIDATION')]);
} else {
return new JsonResponse(['status' => 'success', 'result' => 'ok', 'valid' => true]);
}
}
}