<?php namespace Nen\Bundle\KennisbankPlatformBundle\Controller;
use Nen\Bundle\KennisbankPlatformBundle\Authentication\NenConnectClient;
use Nen\Bundle\KennisbankPlatformBundle\Authentication\ResponseException;
use App\Entity\User;
use Nen\Bundle\KennisbankPlatformBundle\Exceptions\InvalidLicenseException;
use Nen\Bundle\KennisbankPlatformBundle\Exceptions\UserUnknownException;
use Nen\Bundle\KennisbankPlatformBundle\Exceptions\ValidationException;
use Nen\Bundle\KennisbankPlatformBundle\Exceptions\WithErrorsException;
use Nen\Bundle\KennisbankPlatformBundle\Form\UserType;
use Nen\Bundle\KennisbankPlatformBundle\Handler\ActivationHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\AddUserHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\ChangeUsernameHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\ForgotPasswordHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\LicenseRequestHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\LoginHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\RegistrationHandler;
use Nen\Bundle\KennisbankPlatformBundle\Handler\ResetPasswordHandler;
use Nen\Bundle\KennisbankPlatformBundle\Repository\CompanyRepository;
use Nen\Bundle\KennisbankPlatformBundle\Support\LicenseHelper;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use function Symfony\Component\Translation\t;
/**
* Gebruikers Controller
*
* @author G.P. Gautier <ggautier@thirdwave.nl>
* @version 0.5.0, 2015/12/23
*/
class GebruikersController extends SiteController
{
/**
* @var bool
*/
public static $trialIsNotTrial = false;
// /**
// * Inloggen
// */
// public function inloggen()
// {
// $handler = new LoginHandler($this->app);
// $continue = $this->getContinueUrl();
// $this->response->data['form'] = [
// 'continue' => $continue,
// 'username' => $this->request->request->get('username')
// ];
// if ($this->request->getMethod() !== 'POST') {
// return;
// }
// try {
// $handler->handle($this->request->request->all());
// } catch (InvalidLicenseException $e) {
// $record = User::with('company')->where('username', $this->request->request->get('username'))->first();
// if ((int)$record->company->license_trial === 1) {
// $this->response->data['record'] = $record;
// $this->response->data['expired'] = true;
// $this->app['session']->set('expired', $record->id);
// } else {
// $this->response->data['form']['errors'] = $e->getErrors();
// }
// return;
// } catch (WithErrorsException $e) {
// $this->response->data['form']['errors'] = $e->getErrors();
// return;
// }
// $this->response->redirect($continue);
// }
// /**
// * Uitloggen
// */
// public function uitloggen()
// {
// $this->app['authentication']->logout();
// $this->response->redirect($this->app['router']->getRouteUrl('gebruikers_inloggen'));
// }
// /**
// * @Route("/nen-connect", name="gebruikers_nen_connect")
// */
// public function nenConnectSso(NenConnectClient $nenConnectClient)
// {
// try {
// $url = $nenConnectClient->singleSingOn($this->getUser()->getUsername());
// } catch (ResponseException $e) {
// mail('bugreports@thirdwave.nl', 'NEN Connect SSO Melding', $e->getMessage());
//
// $this->app['flash']->add('error', $this->translate('Doorverwijzing naar NEN Connect is op dit moment niet beschikbaar.'));
//
// return new RedirectResponse($this->app['router']->getRouteUrl('home'));
// }
//
// return new RedirectResponse($url);
// }
/**
* @Route("/registreren", name="register")
*
* Gebruiker registreren
*/
public function registreren(Request $request, CompanyRepository $companyRepository, AddUserHandler $addUserHandler)
{
$user = new User();
$form = $this->createForm(UserType::class, $user, ['validation_groups' => ['user'], 'type' => 'register']);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($form->has('hash')) {
$hash = $form->get('hash')->getData();
} else {
$hash = null;
}
$company = $companyRepository->findOneBy(['licenseCode' => $form->get('license_code')->getData()]);
if (empty($company)) {
$this->addFlash('error', t('Kan geen organisatie vinden voor abonnementscode.'));
return $this->render('@KennisbankPlatform/pages/register.html.twig', [
'form' => $form->createView()
]);
}
if (count($company->getUsers()) >= $company->getLicenseAmount()) {
$this->addFlash('error', t('Kan geen gebruikers meer toevoegen voor deze organisatie.'));
return $this->render('@KennisbankPlatform/pages/register.html.twig', [
'form' => $form->createView()
]);
}
$user->setCompany($company);
$addUserHandler->handle($user, $hash);
$this->addFlash('success', t('U ontvangt een e-mail om uw gebruiker te activeren via %username%.', ['%username%' => $user->getUsername()]));
return $this->redirectToRoute('home');
}
return $this->render('@KennisbankPlatform/pages/register.html.twig', [
'form' => $form->createView()
]);
}
// /**
// * @Route("/abonnement", name="gebruikers_licentie")
// */
// public function licentie(Request $request, LicenseHelper $licenseHelper)
// {
// return $this->render('@KennisbankPlatform/gebruikers/licentie.twig', [
// 'couponcode' => $request->query->get('couponcode'),
// 'licenses' => $licenseHelper->getLicenses($this->getParameter('license'))
// ]);
// }
// /**
// *
// */
// public function omzetten(LicenseHelper $licenseHelper)
// {
// if ($this->getUser() && !$this->getUser()->company->canUpgradeLicense()) {
// $this->app['flash']->add('error', $this->translate('U kunt dit abonnement niet omzetten.'));
// $this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
// return;
// }
// if ($id = $this->app['session']->get('expired')) {
// $record = User::find($id);
// $this->response->data['record'] = $record;
// }
// $this->response->data['licenses'] = $licenseHelper->getLicenses($this->app['config']['license']);
// }
/**
* Licentie aanvragen
* @Route("/abonnement/aanvragen", name="gebruikers_aanvragen")
*
* @param LicenseRequestHandler $handler
*/
public function aanvragen(LicenseRequestHandler $handler = null)
{
if (empty($handler)) {
$handler = new LicenseRequestHandler($this->app);
}
$license = $licenseHelper->getLicense(
array_merge($this->request->request->all(), $this->request->query->all()),
$this->app['config']['license']
);
if (empty($license)) {
$this->app['flash']->add('error', $this->translate('Kies eerst een geldig abonnement.'));
$this->app['response']->redirect($this->app['router']->getRouteUrl('gebruikers_licentie'));
return;
}
$couponcode = $this->request->get('couponcode');
if (!empty($couponcode)) {
$license['couponcode'] = $couponcode;
}
$this->response->data['couponcode'] = $couponcode;
$this->response->data['licenses'] = $licenseHelper->getLicenses($this->app['config']['license']);
$this->response->data['license'] = $license;
if (!empty($license['upgrade'])) {
if ($id = $this->app['session']->get('expired')) {
$record = User::find($id);
} else {
$record = $this->getUser();
}
if (empty($record)) {
$this->app['flash']->add(
'error',
$this->translate('Kan geen geldige gebruiker vinden voor het omzetten van dit proefabonnement.')
);
$this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
return;
}
$handler->setUser($record);
$handler->setCompany($record->company);
$handler->setData(
[
'user' => $record->toArray(),
'company' => $record->company->toArray(),
]
);
}
$handler->setLicense($license);
if ($this->request->getMethod() !== 'POST') {
return;
}
$handler->setData($this->request->request->all());
try {
$handler->handle([]);
} catch (ValidationException $e) {
$handler->error($e->getErrors());
return;
}
$user = $handler->getUser();
$trial = !empty($user->company->license_trial);
if ($trial) {
$mails = [
'activeren' => 'activeren-licentie-proef',
'klantenservice' => 'licentie-klantenservice-proef'
];
} else {
$mails = [
'activeren' => 'activeren-licentie',
'klantenservice' => 'licentie-klantenservice'
];
}
if (!empty($license['upgrade'])) {
$this->mail(
array_merge(
$this->app['config']['email']['default'],
$this->app['config']['email']['welkom-licentie'],
[
'to' => [$user->username => $user->getFullnameAttribute()]
]
),
[
'user' => $user->toArray(),
'company' => $user->company->toArray()
]
);
} else {
$this->mail(
array_merge(
$this->app['config']['email']['default'],
$this->app['config']['email'][$mails['activeren']],
[
'to' => [$user->username => $user->getFullnameAttribute()]
]
),
[
'user' => $user->toArray(),
'company' => $user->company->toArray()
]
);
}
if ((static::$trialIsNotTrial || $mails['klantenservice'] !== 'licentie-klantenservice-proef')) {
$this->mail(
array_merge(
$this->app['config']['email']['default'],
$this->app['config']['email'][$mails['klantenservice']]
),
[
'user' => $user->toArray(),
'company' => $user->company->toArray()
]
);
}
if ($this->app['session']->has('expired')) {
$this->app['authentication']->login($user);
$this->app['session']->remove('expired');
}
if (!empty($license['upgrade'])) {
$this->app['flash']->add('success', $this->translate('Uw abonnement is succesvol omgezet.'));
$this->app['response']->redirect($this->app['router']->getRouteUrl('beheer') . '?abonnement=upgrade');
return;
}
$this->app['session']->set('conversion', $trial ? 'trial' : 'regular');
$this->app['flash']->add('success', $this->translate('U ontvangt een e-mail om uw gebruiker te activeren via ') . $user->username);
$this->app['response']->redirect($this->app['router']->getRouteUrl('home') . '?abonnement=' . ($trial ? 'trial' : 'regular'));
}
// /**
// * Gebruiker activeren
// */
// public function activeren()
// {
// $handler = new ActivationHandler($this->app);
// $this->response->data['token'] = $this->request->get('token');
// $this->response->data['form'] = array_merge(
// [
// 'token' => $this->response->data['token']
// ],
// $this->request->request->all()
// );
// try {
// $handler->handle($this->response->data['form']);
// } catch (ValidationException $e) {
// $this->response->data['form']['errors'] = $e->getErrors();
// return;
// }
// if ($handler->isFinished()) {
// $user = $handler->getUser();
// $trial = !empty($user->company->license_trial);
// $mail = $trial ? 'welkom-licentie-proef' : 'welkom-licentie';
// $this->mail(
// array_merge(
// $this->app['config']['email']['default'],
// $this->app['config']['email'][$mail],
// [
// 'to' => [$user->username => $user->getFullnameAttribute()]
// ]
// ),
// [
// 'user' => $user->toArray(),
// 'company' => $user->company->toArray()
// ]
// );
// if (!$user->hasValidLicense()) {
// $this->app['flash']->add(
// 'warning',
// $this->translate('Uw account is nu actief maar uw abonnement is reeds verlopen.')
// );
// $this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
// return;
// }
// $this->app['authentication']->login($user);
// $this->app['flash']->add('success', $this->translate('Uw account is nu actief.'));
// $this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
// }
// }
// /**
// * Gebruikersnaam wijzigen.
// */
// public function gebruikersnaam()
// {
// $handler = new ChangeUsernameHandler($this->app);
// $handler->setData($this->request->query->all());
// try {
// $handler->handle([]);
// } catch (ValidationException $e) {
// $this->app['flash']->add('error', $this->translate('Ongeldig verzoek.'));
// $this->response->redirect($this->app['router']->getRouteUrl('home'));
// return;
// }
// $handler->success(
// 'U kunt nu inloggen met uw nieuwe gebruikersnaam.',
// $this->app['router']->getRouteUrl('home')
// );
// }
// /**
// * Wachtwoord wijzigen.
// */
// public function wachtwoord()
// {
// if ($token = $this->request->get('token')) {
// $this->wachtwoordInstellen($token);
// return;
// }
// $handler = new ForgotPasswordHandler($this->app);
// $this->response->data['renew'] = $this->request->query->get('renew');
// if ($this->request->getMethod() !== 'POST') {
// return;
// }
// $this->response->data['form'] = $this->request->request->all();
// $message = 'Indien de gebruikersnaam bekend is, ontvangt u een e-mail met instructies.';
// try {
// $handler->handle($this->response->data['form']);
// } catch (ValidationException $e) {
// $this->response->data['form']['errors'] = $e->getErrors();
// return;
// } catch (UserUnknownException $e) {
// $this->app['flash']->add('success', $this->translate($message));
// $this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
// return;
// }
// $user = $handler->getUser();
// $this->mail(
// array_merge(
// $this->app['config']['email']['default'],
// $this->app['config']['email']['wachtwoord'],
// [
// 'to' => [$user->username => $user->getFullnameAttribute()]
// ]
// ),
// [
// 'user' => $user->toArray(),
// 'company' => $user->company->toArray()
// ]
// );
// $this->app['flash']->add('success', $this->translate($message));
// $this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
// }
// /**
// * Nieuw wachtwoord instellen.
// *
// * @param string $token
// */
// public function wachtwoordInstellen($token)
// {
// $this->response->data['reset'] = true;
// $this->response->data['token'] = $token;
// $this->response->data['form'] = $this->request->request->all();
// $data = array_merge(
// $this->response->data['form'],
// ['token' => $token]
// );
// $handler = new ResetPasswordHandler($this->app);
// try {
// $handler->handle($data);
// } catch (ValidationException $e) {
// $this->response->data['form']['errors'] = $e->getErrors();
// return;
// }
// if ($handler->isFinished()) {
// $user = $handler->getUser();
// if (!$user->hasValidLicense()) {
// $this->app['flash']->add(
// 'warning',
// $this->translate('Uw wachtwoord is succesvol aangepast maar uw abonnement is reeds verlopen.')
// );
// $this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
// return;
// }
// $this->app['authentication']->login($handler->getUser());
// $this->app['flash']->add('success', $this->translate('Uw wachtwoord is succesvol aangepast.'));
// $this->app['response']->redirect($this->app['router']->getRouteUrl('home'));
// }
// }
// /**
// * @return string
// */
// protected function getContinueUrl()
// {
// $continue = $this->request->get('continue');
// if (empty($continue)) {
// $continue = $this->app['router']->getRouteUrl('werkboek');
// }
// $continue = parse_url($continue, PHP_URL_PATH);
// return $continue;
// }
}