Merge pull request #178 from nlegoff/tests_login

Add tests for the new root controllers
This commit is contained in:
Romain Neutron
2012-08-21 09:15:38 -07:00
21 changed files with 1682 additions and 550 deletions

View File

@@ -57,7 +57,6 @@ return call_user_func(function() {
$app->mount('/feeds/', new RSSFeeds()); $app->mount('/feeds/', new RSSFeeds());
$app->mount('/account/', new Account()); $app->mount('/account/', new Account());
$app->mount('/login/authenticate/', new AuthenticateController());
$app->mount('/login/', new Login()); $app->mount('/login/', new Login());
$app->mount('/developers/', new Developers()); $app->mount('/developers/', new Developers());

View File

@@ -1,113 +0,0 @@
<?php
namespace Alchemy\Phrasea\Controller\Login;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
class Authenticate implements ControllerProviderInterface
{
public function connect(Application $app)
{
$controllers = $app['controllers_factory'];
$controllers->post('/', __CLASS__ . '::authenticate')
->before(function() use ($app) {
return $app['phraseanet.core']['Firewall']->requireNotAuthenticated($app);
});
return $controllers;
}
public function authenticate(Application $app, Request $request)
{
/* @var $Core \Alchemy\Phrasea\Core */
$Core = $app['phraseanet.core'];
$appbox = \appbox::get_instance($Core);
$session = $appbox->get_session();
$registry = $appbox->get_registry();
if ($registry->get('GV_captchas')
&& trim($registry->get('GV_captcha_private_key')) !== ''
&& trim($registry->get('GV_captcha_public_key')) !== '')
include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php');
$is_guest = false;
if (null !== $request->get('nolog') && \phrasea::guest_allowed()) {
$is_guest = true;
}
if ((null !== $request->get('login') && null !== $request->get('pwd')) || $is_guest) {
/**
* @todo dispatch an event that can be used to tweak the authentication
* (LDAP....)
*/
// $app['dispatcher']->dispatch();
try {
if ($is_guest) {
$auth = new \Session_Authentication_Guest($appbox);
} else {
$captcha = false;
if ($registry->get('GV_captchas')
&& trim($registry->get('GV_captcha_private_key')) !== ''
&& trim($registry->get('GV_captcha_public_key')) !== ''
&& ! is_null($request->get("recaptcha_challenge_field")
&& ! is_null($request->get("recaptcha_response_field")))) {
$checkCaptcha = recaptcha_check_answer($registry->get('GV_captcha_private_key'), $_SERVER["REMOTE_ADDR"], $request->get("recaptcha_challenge_field"), $request->get("recaptcha_response_field"));
if ($checkCaptcha->is_valid) {
$captcha = true;
}
}
$auth = new \Session_Authentication_Native($appbox, $request->get('login'), $request->get('pwd'));
$auth->set_captcha_challenge($captcha);
}
$session->authenticate($auth);
} catch (\Exception_Session_StorageClosed $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=session");
} catch (\Exception_Session_RequireCaptcha $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=captcha");
} catch (\Exception_Unauthorized $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=auth");
} catch (\Exception_Session_MailLocked $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=mail-not-confirmed&usr=" . $e->get_usr_id());
} catch (\Exception_Session_WrongToken $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=token");
} catch (\Exception_InternalServerError $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=session");
} catch (\Exception_ServiceUnavailable $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=maintenance");
} catch (\Exception_Session_BadSalinity $e) {
$date = new \DateTime('5 minutes');
$usr_id = \User_Adapter::get_usr_id_from_login($request->get('login'));
$url = \random::getUrlToken(\random::TYPE_PASSWORD, $usr_id, $date);
$url = '/account/forgot-password/?token=' . $url . '&salt=1';
return $app->redirect($url);
} catch (\Exception $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=" . _('An error occured'));
}
if ($app['browser']->isMobile()) {
return $app->redirect("/lightbox/");
} elseif ($request->get('redirect')) {
return $app->redirect($request->get('redirect'));
} elseif (true !== $app['browser']->isNewGeneration()) {
return $app->redirect('/client/');
} else {
return $app->redirect('/prod/');
}
} else {
return $app->redirect("/login/");
}
}
}

View File

@@ -13,7 +13,9 @@ namespace Alchemy\Phrasea\Controller\Root;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
/** /**
@@ -45,7 +47,8 @@ class Account implements ControllerProviderInterface
* *
* return : HTML Response * return : HTML Response
*/ */
$controllers->get('/', $this->call('displayAccount'))->bind('account'); $controllers->get('/', $this->call('displayAccount'))
->bind('account');
/** /**
* Update account route * Update account route
@@ -152,22 +155,8 @@ class Account implements ControllerProviderInterface
* *
* return : HTML Response * return : HTML Response
*/ */
$controllers->get('/access/', $this->call('accountAccess'))->bind('account_access'); $controllers->get('/access/', $this->call('accountAccess'))
->bind('account_access');
// /**
// * Give account open sessions
// *
// * name : register_account
// *
// * description : Display form to create a new account
// *
// * method : GET
// *
// * parameters : none
// *
// * return : HTML Response
// */
// $controllers->get('/register/', $this->call('registerAccount'))->bind('register_account');
/** /**
* Give authorized applications that can access user informations * Give authorized applications that can access user informations
@@ -182,7 +171,8 @@ class Account implements ControllerProviderInterface
* *
* return : HTML Response * return : HTML Response
*/ */
$controllers->get('/reset-email/', $this->call('resetEmail'))->bind('reset_email'); $controllers->post('/reset-email/', $this->call('resetEmail'))
->bind('reset_email');
/** /**
* Grant access to an authorized app * Grant access to an authorized app
@@ -197,7 +187,8 @@ class Account implements ControllerProviderInterface
* *
* return : HTML Response * return : HTML Response
*/ */
$controllers->get('/reset-password/', $this->call('resetPassword'))->bind('reset_password'); $controllers->get('/reset-password/', $this->call('resetPassword'))
->bind('reset_password');
/** /**
* Give account open sessions * Give account open sessions
@@ -251,11 +242,13 @@ class Account implements ControllerProviderInterface
return $controllers; return $controllers;
} }
public function registerAccount(Application $app, Request $request) /**
{ * Reset Password
return new Response($app['twig']->render('account/register.html.twig')); *
} * @param Application $app
* @param Request $request
* @return Response
*/
public function resetPassword(Application $app, Request $request) public function resetPassword(Application $app, Request $request)
{ {
if (null !== $passwordMsg = $request->get('pass-error')) { if (null !== $passwordMsg = $request->get('pass-error')) {
@@ -278,11 +271,11 @@ class Account implements ControllerProviderInterface
} }
/** /**
* Reset email * Reset Email
* *
* @param \Silex\Application $app * @param Application $app
* @param \Symfony\Component\HttpFoundation\Request $request * @param Request $request
* @return \Symfony\Component\HttpFoundation\JsonResponse * @return RedirectResponse
*/ */
public function resetEmail(Application $app, Request $request) public function resetEmail(Application $app, Request $request)
{ {
@@ -339,9 +332,9 @@ class Account implements ControllerProviderInterface
/** /**
* Display reset email form * Display reset email form
* *
* @param \Silex\Application $app * @param Application $app
* @param \Symfony\Component\HttpFoundation\Request $request * @param Request $request
* @return \Symfony\Component\HttpFoundation\JsonResponse * @return Response
*/ */
public function displayResetEmailForm(Application $app, Request $request) public function displayResetEmailForm(Application $app, Request $request)
{ {
@@ -387,7 +380,7 @@ class Account implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* @return Response * @return RedirectResponse
*/ */
public function renewPassword(Application $app, Request $request) public function renewPassword(Application $app, Request $request)
{ {
@@ -425,8 +418,7 @@ class Account implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* * @return JsonResponse
* @return Response
*/ */
public function grantAccess(Application $app, Request $request, $application_id) public function grantAccess(Application $app, Request $request, $application_id)
{ {
@@ -443,12 +435,12 @@ class Account implements ControllerProviderInterface
, new \API_OAuth2_Application($appbox, $application_id) , new \API_OAuth2_Application($appbox, $application_id)
, $app['phraseanet.core']->getAuthenticatedUser() , $app['phraseanet.core']->getAuthenticatedUser()
); );
$account->set_revoked((bool) $request->get('revoke'), false);
} catch (\Exception_NotFound $e) { } catch (\Exception_NotFound $e) {
$error = true; $error = true;
} }
$account->set_revoked((bool) $request->get('revoke'), false);
return $app->json(array('success' => ! $error)); return $app->json(array('success' => ! $error));
} }
@@ -457,7 +449,6 @@ class Account implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function accountAccess(Application $app, Request $request) public function accountAccess(Application $app, Request $request)
@@ -474,7 +465,6 @@ class Account implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function accountAuthorizedApps(Application $app, Request $request) public function accountAuthorizedApps(Application $app, Request $request)
@@ -489,7 +479,6 @@ class Account implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function accountSessionsAccess(Application $app, Request $request) public function accountSessionsAccess(Application $app, Request $request)
@@ -502,7 +491,6 @@ class Account implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function displayAccount(Application $app, Request $request) public function displayAccount(Application $app, Request $request)
@@ -543,7 +531,6 @@ class Account implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function updateAccount(Application $app, Request $request) public function updateAccount(Application $app, Request $request)
@@ -555,7 +542,7 @@ class Account implements ControllerProviderInterface
$demands = (array) $request->get('demand', array()); $demands = (array) $request->get('demand', array());
if (0 === count($demands)) { if (0 !== count($demands)) {
$register = new \appbox_register($appbox); $register = new \appbox_register($appbox);
foreach ($demands as $baseId) { foreach ($demands as $baseId) {
@@ -640,7 +627,7 @@ class Account implements ControllerProviderInterface
foreach ($evtMngr->list_notifications_available($user->get_id()) as $notifications) { foreach ($evtMngr->list_notifications_available($user->get_id()) as $notifications) {
foreach ($notifications as $notification) { foreach ($notifications as $notification) {
$notifId = (int) $notification['id']; $notifId = $notification['id'];
$notifName = sprintf('notification_%d', $notifId); $notifName = sprintf('notification_%d', $notifId);
if (isset($requestedNotifications[$notifId])) { if (isset($requestedNotifications[$notifId])) {

View File

@@ -13,7 +13,9 @@ namespace Alchemy\Phrasea\Controller\Root;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
/** /**
@@ -178,8 +180,7 @@ class Developers implements ControllerProviderInterface
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* @param integer $id The application id * @param integer $id The application id
* * @return JsonResponse
* @return Response
*/ */
public function deleteApp(Application $app, Request $request, $id) public function deleteApp(Application $app, Request $request, $id)
{ {
@@ -205,8 +206,7 @@ class Developers implements ControllerProviderInterface
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* @param integer $id The application id * @param integer $id The application id
* * @return JsonResponse
* @return Response
*/ */
public function renewAppCallback(Application $app, Request $request, $id) public function renewAppCallback(Application $app, Request $request, $id)
{ {
@@ -237,8 +237,7 @@ class Developers implements ControllerProviderInterface
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* @param integer $id The application id * @param integer $id The application id
* * @return JsonResponse
* @return Response
*/ */
public function renewAccessToken(Application $app, Request $request, $id) public function renewAccessToken(Application $app, Request $request, $id)
{ {
@@ -276,8 +275,7 @@ class Developers implements ControllerProviderInterface
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* @param integer $id The application id * @param integer $id The application id
* * @return JsonResponse
* @return Response
*/ */
public function authorizeGrantpassword(Application $app, Request $request, $id) public function authorizeGrantpassword(Application $app, Request $request, $id)
{ {
@@ -289,12 +287,11 @@ class Developers implements ControllerProviderInterface
try { try {
$clientApp = new \API_OAuth2_Application($app['phraseanet.appbox'], $id); $clientApp = new \API_OAuth2_Application($app['phraseanet.appbox'], $id);
$clientApp->set_grant_password((bool) $request->get('grant', false));
} catch (\Exception_NotFound $e) { } catch (\Exception_NotFound $e) {
$error = true; $error = true;
} }
$clientApp->set_grant_password((bool) $request->get('grant', false));
return $app->json(array('success' => ! $error)); return $app->json(array('success' => ! $error));
} }
@@ -303,14 +300,11 @@ class Developers implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function newApp(Application $app, Request $request) public function newApp(Application $app, Request $request)
{ {
$error = false; if ($request->get('type') === \API_OAuth2_Application::DESKTOP_TYPE) {
if ($request->get("type") == "desktop") {
$form = new \API_OAuth2_Form_DevAppDesktop($app['request']); $form = new \API_OAuth2_Form_DevAppDesktop($app['request']);
} else { } else {
$form = new \API_OAuth2_Form_DevAppInternet($app['request']); $form = new \API_OAuth2_Form_DevAppInternet($app['request']);
@@ -318,11 +312,7 @@ class Developers implements ControllerProviderInterface
$violations = $app['validator']->validate($form); $violations = $app['validator']->validate($form);
if ($violations->count() == 0) { if ($violations->count() === 0) {
$error = true;
}
if ($error) {
$application = \API_OAuth2_Application::create($app['phraseanet.appbox'], $app['phraseanet.core']->getAuthenticatedUser(), $form->getName()); $application = \API_OAuth2_Application::create($app['phraseanet.appbox'], $app['phraseanet.core']->getAuthenticatedUser(), $form->getName());
$application $application
->set_description($form->getDescription()) ->set_description($form->getDescription())
@@ -338,7 +328,7 @@ class Developers implements ControllerProviderInterface
"form" => $form "form" => $form
); );
return $app['twig']->render('/developers/application.html.twig', $var); return $app['twig']->render('/developers/application_form.html.twig', $var);
} }
/** /**
@@ -346,7 +336,6 @@ class Developers implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function listApps(Application $app, Request $request) public function listApps(Application $app, Request $request)
@@ -362,7 +351,6 @@ class Developers implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
*
* @return Response * @return Response
*/ */
public function displayFormApp(Application $app, Request $request) public function displayFormApp(Application $app, Request $request)
@@ -380,7 +368,6 @@ class Developers implements ControllerProviderInterface
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* @param integer $id The application id * @param integer $id The application id
*
* @return Response * @return Response
*/ */
public function getApp(Application $app, Request $request, $id) public function getApp(Application $app, Request $request, $id)

View File

@@ -15,6 +15,7 @@ use Alchemy\Phrasea\Core;
use Silex\Application; use Silex\Application;
use Silex\ControllerProviderInterface; use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
/** /**
@@ -29,12 +30,62 @@ class Login implements ControllerProviderInterface
{ {
$controllers = $app['controllers_factory']; $controllers = $app['controllers_factory'];
/**
* Login
*
* name : homepage
*
* description : Login from phraseanet
*
* method : GET
*
* parameters : none
*
* return : HTML Response
*/
$controllers->get('/', $this->call('login')) $controllers->get('/', $this->call('login'))
->before(function() use ($app) { ->before(function() use ($app) {
return $app['phraseanet.core']['Firewall']->requireNotAuthenticated($app);
if (null !== $app['request']->get('postlog')) {
// if isset postlog parameter, set cookie and log out current user
// then post login operation like getting baskets from an invit session
// could be done by Session_handler authentication process
$app['phraseanet.appbox']->get_session()->set_postlog();
return $app->redirect("/login/logout/?redirect=" . $app['request']->get('redirect', 'prod'));
}
if ($app['phraseanet.core']->isAuthenticated()) {
return $app->redirect('/' . $app['request']->get('redirect', 'prod') . '/');
}
}) })
->bind('homepage'); ->bind('homepage');
/**
* Authenticate
*
* name : login_authenticate
*
* description : authenticate to phraseanet
*
* method : POST
*
* parameters : none
*
* return : HTML Response
*/
$controllers->post('/authenticate/', $this->call('authenticate'))
->before(function() use ($app) {
if ($app['phraseanet.core']->isAuthenticated()) {
return $app->redirect('/prod/');
}
})
->bind('login_authenticate');
/** /**
* Logout * Logout
* *
@@ -153,9 +204,9 @@ class Login implements ControllerProviderInterface
/** /**
* Send a confirmation mail after register * Send a confirmation mail after register
* *
* @param \Silex\Application $app * @param Application $app A Silex application where the controller is mounted on
* @param \Symfony\Component\HttpFoundation\Request $request * @param Request $request The current request
* @return \Symfony\Component\HttpFoundation\Response * @return RedirectResponse
*/ */
public function sendConfirmMail(Application $app, Request $request) public function sendConfirmMail(Application $app, Request $request)
{ {
@@ -180,9 +231,9 @@ class Login implements ControllerProviderInterface
/** /**
* Validation of email adress * Validation of email adress
* *
* @param \Silex\Application $app * @param Application $app A Silex application where the controller is mounted on
* @param \Symfony\Component\HttpFoundation\Request $request * @param Request $request The current request
* @return \Symfony\Component\HttpFoundation\Response * @return RedirectResponse
*/ */
public function registerConfirm(Application $app, Request $request) public function registerConfirm(Application $app, Request $request)
{ {
@@ -208,7 +259,6 @@ class Login implements ControllerProviderInterface
return $app->redirect('/login/?redirect=prod&notice=already'); return $app->redirect('/login/?redirect=prod&notice=already');
} }
$user->set_mail_locked(false);
\random::removeToken($code); \random::removeToken($code);
if (\PHPMailer::ValidateAddress($user->get_email())) { if (\PHPMailer::ValidateAddress($user->get_email())) {
@@ -244,13 +294,13 @@ class Login implements ControllerProviderInterface
* *
* @param Application $app A Silex application where the controller is mounted on * @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request * @param Request $request The current request
* @return Response * @return RedirectResponse
*/ */
public function renewPassword(Application $app, Request $request) public function renewPassword(Application $app, Request $request)
{ {
$appbox = $app['phraseanet.appbox']; $appbox = $app['phraseanet.appbox'];
if (null !== $mail = trim($request->get('mail'))) { if (null !== $mail = $request->get('mail')) {
if ( ! \PHPMailer::ValidateAddress($mail)) { if ( ! \PHPMailer::ValidateAddress($mail)) {
return $app->redirect('/login/forgot-password/?error=invalidmail'); return $app->redirect('/login/forgot-password/?error=invalidmail');
} }
@@ -272,8 +322,6 @@ class Login implements ControllerProviderInterface
return $app->redirect('/login/forgot-password/?error=mailserver'); return $app->redirect('/login/forgot-password/?error=mailserver');
} }
} }
return $app->redirect('/login/forgot-password/?error=noaccount');
} }
if ((null !== $token = $request->get('token')) if ((null !== $token = $request->get('token'))
@@ -301,7 +349,7 @@ class Login implements ControllerProviderInterface
return $app->redirect('/login/?notice=password-update-ok'); return $app->redirect('/login/?notice=password-update-ok');
} catch (\Exception_NotFound $e) { } catch (\Exception_NotFound $e) {
return $app->redirect('/login/forgot-password/?error=token');
} }
} }
} }
@@ -356,15 +404,15 @@ class Login implements ControllerProviderInterface
} }
if (null !== $passwordMsg = $request->get('pass-error')) { if (null !== $passwordMsg = $request->get('pass-error')) {
switch ($sentMsg) { switch ($passwordMsg) {
case 'pass-match': case 'pass-match':
$sentMsg = _('forms::les mots de passe ne correspondent pas'); $passwordMsg = _('forms::les mots de passe ne correspondent pas');
break; break;
case 'pass-short': case 'pass-short':
$sentMsg = _('forms::la valeur donnee est trop courte'); $passwordMsg = _('forms::la valeur donnee est trop courte');
break; break;
case 'pass-invalid': case 'pass-invalid':
$sentMsg = _('forms::la valeur donnee contient des caracteres invalides'); $passwordMsg = _('forms::la valeur donnee contient des caracteres invalides');
break; break;
} }
} }
@@ -380,9 +428,9 @@ class Login implements ControllerProviderInterface
/** /**
* Get the register form * Get the register form
* *
* @param \Silex\Application $app * @param Application $app A Silex application where the controller is mounted on
* @param \Symfony\Component\HttpFoundation\Request $request * @param Request $request The current request
* @return \Symfony\Component\HttpFoundation\Response * @return Response
*/ */
public function displayRegisterForm(Application $app, Request $request) public function displayRegisterForm(Application $app, Request $request)
{ {
@@ -440,9 +488,9 @@ class Login implements ControllerProviderInterface
/** /**
* Get the register form * Get the register form
* *
* @param \Silex\Application $app * @param Application $app A Silex application where the controller is mounted on
* @param \Symfony\Component\HttpFoundation\Request $request * @param Request $request The current request
* @return \Symfony\Component\HttpFoundation\Response * @return RedirectResponse
*/ */
public function register(Application $app, Request $request) public function register(Application $app, Request $request)
{ {
@@ -472,7 +520,7 @@ class Login implements ControllerProviderInterface
$needed['form_password'] = 'pass-invalid'; $needed['form_password'] = 'pass-invalid';
} }
if (false !== \PHPMailer::ValidateAddress($email = $request->get('form_email'))) { if (false === \PHPMailer::ValidateAddress($email = $request->get('form_email'))) {
$needed['form_email'] = 'mail-invalid'; $needed['form_email'] = 'mail-invalid';
} }
@@ -498,7 +546,7 @@ class Login implements ControllerProviderInterface
} }
if (sizeof($needed) > 0) { if (sizeof($needed) > 0) {
$app->redirect(sprintf('/register/?%s', http_build_query(array('needed' => $needed)))); return $app->redirect(sprintf('/register/?%s', http_build_query(array('needed' => $needed))));
} }
require_once($app['phraseanet.core']['Registry']->get('GV_RootPath') . 'lib/classes/deprecated/inscript.api.php'); require_once($app['phraseanet.core']['Registry']->get('GV_RootPath') . 'lib/classes/deprecated/inscript.api.php');
@@ -599,9 +647,9 @@ class Login implements ControllerProviderInterface
/** /**
* Logout from Phraseanet * Logout from Phraseanet
* *
* @param \Silex\Application $app * @param Application $app A Silex application where the controller is mounted on
* @param \Symfony\Component\HttpFoundation\Request $request * @param Request $request The current request
* @return \Symfony\Component\HttpFoundation\Response * @return RedirectResponse
*/ */
public function logout(Application $app, Request $request) public function logout(Application $app, Request $request)
{ {
@@ -619,27 +667,23 @@ class Login implements ControllerProviderInterface
return $app->redirect("/login/?logged_out=user" . ($appRedirect ? sprintf("&redirect=/%s", $appRedirect) : "")); return $app->redirect("/login/?logged_out=user" . ($appRedirect ? sprintf("&redirect=/%s", $appRedirect) : ""));
} }
/**
* Login into Phraseanet
*
* @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request
* @return Response
*/
public function login(Application $app, Request $request) public function login(Application $app, Request $request)
{ {
$appbox = $app['phraseanet.appbox']; $appbox = $app['phraseanet.appbox'];
$session = $appbox->get_session(); $registry = $app['phraseanet.core']['Registry'];
$registry = $appbox->get_registry();
require_once($registry->get('GV_RootPath') . 'lib/classes/deprecated/inscript.api.php'); require_once($registry->get('GV_RootPath') . 'lib/classes/deprecated/inscript.api.php');
if ($registry->get('GV_captchas') && trim($registry->get('GV_captcha_private_key')) !== '' && trim($registry->get('GV_captcha_public_key')) !== '') { if ($registry->get('GV_captchas') && trim($registry->get('GV_captcha_private_key')) !== '' && trim($registry->get('GV_captcha_public_key')) !== '') {
include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php'); include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php');
} }
if ($request->get('postlog')) {
$session->set_postlog(true);
return $app->redirect("/login/?redirect=" . $request->get('redirect'));
}
if ( ! $session->isset_postlog() && $session->is_authenticated() && $request->get('error') != 'no-connection') {
return $app->redirect($request->get('redirect', '/prod/'));
}
$warning = $request->get('error', ''); $warning = $request->get('error', '');
try { try {
@@ -737,6 +781,97 @@ class Login implements ControllerProviderInterface
)); ));
} }
/**
* Authenticate to phraseanet
*
* @param Application $app A Silex application where the controller is mounted on
* @param Request $request The current request
* @return RedirectResponse
*/
public function authenticate(Application $app, Request $request)
{
$appbox = $app['phraseanet.appbox'];
$session = $appbox->get_session();
$registry = $app['phraseanet.core']['Registry'];
$is_guest = false;
if (null !== $request->get('nolog') && \phrasea::guest_allowed()) {
$is_guest = true;
}
if (((null !== $login = $request->get('login')) && (null !== $pwd = $request->get('pwd'))) || $is_guest) {
/**
* @todo dispatch an event that can be used to tweak the authentication
* (LDAP....)
*/
// $app['dispatcher']->dispatch();
try {
if ($is_guest) {
$auth = new \Session_Authentication_Guest($appbox);
} else {
$captcha = false;
if ($registry->get('GV_captchas')
&& '' !== $privateKey = trim($registry->get('GV_captcha_private_key'))
&& trim($registry->get('GV_captcha_public_key')) !== ''
&& null !== $challenge = $request->get("recaptcha_challenge_field")
&& null !== $captachResponse = $request->get("recaptcha_response_field")) {
include($registry->get('GV_RootPath') . 'lib/vendor/recaptcha/recaptchalib.php');
$checkCaptcha = recaptcha_check_answer($privateKey, $_SERVER["REMOTE_ADDR"], $challenge, $captachResponse);
if ($checkCaptcha->is_valid) {
$captcha = true;
}
}
$auth = new \Session_Authentication_Native($appbox, $login, $pwd);
$auth->set_captcha_challenge($captcha);
}
$session->authenticate($auth);
} catch (\Exception_Session_StorageClosed $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=session");
} catch (\Exception_Session_RequireCaptcha $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=captcha");
} catch (\Exception_Unauthorized $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=auth");
} catch (\Exception_Session_MailLocked $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=mail-not-confirmed&usr=" . $e->get_usr_id());
} catch (\Exception_Session_WrongToken $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=token");
} catch (\Exception_InternalServerError $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=session");
} catch (\Exception_ServiceUnavailable $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=maintenance");
} catch (\Exception_Session_BadSalinity $e) {
$date = new \DateTime('5 minutes');
$usr_id = \User_Adapter::get_usr_id_from_login($request->get('login'));
$url = '/account/forgot-password/?token=' . \random::getUrlToken(\random::TYPE_PASSWORD, $usr_id, $date) . '&salt=1';
return $app->redirect($url);
} catch (\Exception $e) {
return $app->redirect("/login/?redirect=" . $request->get('redirect') . "&error=" . _('An error occured'));
}
if ($app['browser']->isMobile()) {
return $app->redirect("/lightbox/");
} elseif ($request->get('redirect')) {
return $app->redirect($request->get('redirect'));
} elseif (true !== $app['browser']->isNewGeneration()) {
return $app->redirect('/client/');
} else {
return $app->redirect('/prod/');
}
} else {
return $app->redirect("/login/");
}
}
/** /**
* Prefix the method to call with the controller class name * Prefix the method to call with the controller class name
* *
@@ -751,7 +886,7 @@ class Login implements ControllerProviderInterface
/** /**
* Get required fields configuration * Get required fields configuration
* *
* @param \Alchemy\Phrasea\Core $core * @param Core $core
* @return boolean * @return boolean
*/ */
private function getRegisterFieldConfiguration(Core $core) private function getRegisterFieldConfiguration(Core $core)
@@ -778,14 +913,13 @@ class Login implements ControllerProviderInterface
"demand" => true "demand" => true
); );
//on va chercher le fichier de configuration
$registerFieldConfigurationFile = $core['Registry']->get('GV_RootPath') . 'config/register-fields.php'; $registerFieldConfigurationFile = $core['Registry']->get('GV_RootPath') . 'config/register-fields.php';
if (is_file($registerFieldConfigurationFile)) { if (is_file($registerFieldConfigurationFile)) {
include $registerFieldConfigurationFile; include $registerFieldConfigurationFile;
} }
//on force les champs vraiment obligatoires si le mec a fumé en faisant sa conf //Override mandatory fields
$arrayVerif['form_login'] = true; $arrayVerif['form_login'] = true;
$arrayVerif['form_password'] = true; $arrayVerif['form_password'] = true;
$arrayVerif['form_password_confirm'] = true; $arrayVerif['form_password_confirm'] = true;

View File

@@ -180,7 +180,7 @@ class Manage extends Helper
$registry = \bootstrap::getCore()->getRegistry(); $registry = \bootstrap::getCore()->getRegistry();
if (false !== $urlToken) { if (false !== $urlToken) {
$url = sprintf('%slogin/forgotpwd.php?token=%s', $registry->get('GV_ServerName'), $urlToken); $url = sprintf('%slogin/forgot-password/?token=%s', $registry->get('GV_ServerName'), $urlToken);
\mail::send_credentials($url, $createdUser->get_login(), $createdUser->get_email()); \mail::send_credentials($url, $createdUser->get_login(), $createdUser->get_email());
} }
} }

View File

@@ -34,11 +34,4 @@ class Firewall
return $app->redirect('/login/logout/'); return $app->redirect('/login/logout/');
} }
} }
public function requireNotAuthenticated(Application $app)
{
if ($app['phraseanet.core']->isAuthenticated()) {
return $app->redirect('/prod/');
}
}
} }

View File

@@ -246,7 +246,7 @@ class eventsmanager_notify_autoregister extends eventsmanager_notifyAbstract
$body .= "</ul>\n"; $body .= "</ul>\n";
$body .= "<br/>\n<div><a href='/login/?redirect=/admin' target='_blank'>" $body .= "<br/>\n<div><a href='/login/?redirect=admin' target='_blank'>"
. _('admin::register: vous pourrez consulter son compte en ligne via l\'interface d\'administration') . _('admin::register: vous pourrez consulter son compte en ligne via l\'interface d\'administration')
. "</a></div>\n"; . "</a></div>\n";

View File

@@ -250,7 +250,7 @@ class eventsmanager_notify_register extends eventsmanager_notifyAbstract
$body .= "</ul>\n"; $body .= "</ul>\n";
$body .= "<br/>\n<div><a href='" . $this->registry->get('GV_ServerName') $body .= "<br/>\n<div><a href='" . $this->registry->get('GV_ServerName')
. "login/admin' target='_blank'>" . "login/?redirect=admin' target='_blank'>"
. _('admin::register: vous pourrez traiter ses demandes en ligne via l\'interface d\'administration') . _('admin::register: vous pourrez traiter ses demandes en ligne via l\'interface d\'administration')
. "</a></div>\n"; . "</a></div>\n";

View File

@@ -18,7 +18,7 @@
{% if baseInsc['CollsRegistered'] is not none %} {% if baseInsc['CollsRegistered'] is not none %}
{% for base in baseInsc['CollsRegistered']%} {% for base in baseInsc['CollsRegistered']%}
{% for collId, isTrue in base %} {% for collId, isTrue in base %}
{{ base_id == sbasId |base_from_coll(collId) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td colspan="3" style="text-align:center;"> <td colspan="3" style="text-align:center;">
{% trans 'login::register: acces authorise sur la collection ' %}{{ sbasId |sbas_names }} {% trans 'login::register: acces authorise sur la collection ' %}{{ sbasId |sbas_names }}
@@ -37,7 +37,7 @@
{% if baseInsc['CollsRefuse'] %} {% if baseInsc['CollsRefuse'] %}
{% for collId, isTrue in baseInsc['CollsRefuse'] %} {% for collId, isTrue in baseInsc['CollsRefuse'] %}
{{ base_id == sbasId |base_from_coll(collId) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td colspan="3" style="text-align: center;"> <td colspan="3" style="text-align: center;">
<span style="color: red;">{% trans 'login::register: acces refuse sur la collection ' %}{{ sbasId |sbas_names }}</span> <span style="color: red;">{% trans 'login::register: acces refuse sur la collection ' %}{{ sbasId |sbas_names }}</span>
@@ -55,7 +55,7 @@
{% if baseInsc['CollsWait'] %} {% if baseInsc['CollsWait'] %}
{% for collId, isTrue in baseInsc['CollsWait'] %} {% for collId, isTrue in baseInsc['CollsWait'] %}
{{ base_id == sbasId |base_from_coll(collId) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td colspan="3" style="text-align: center;"> <td colspan="3" style="text-align: center;">
<span style="color: orange;">{% trans 'login::register: en attente d\'acces sur' %} {{ sbasId |sbas_names }}</span> <span style="color: orange;">{% trans 'login::register: en attente d\'acces sur' %} {{ sbasId |sbas_names }}</span>
@@ -70,7 +70,7 @@
{% if baseInsc['CollsIntime'] %} {% if baseInsc['CollsIntime'] %}
{% for collId, isTrue in baseInsc['CollsIntime'] %} {% for collId, isTrue in baseInsc['CollsIntime'] %}
{{ base_id == sbasId |base_from_coll(collId) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td colspan="3" style="text-align: center;"> <td colspan="3" style="text-align: center;">
<span>{% trans 'login::register: acces temporaire sur' %} {{ sbasId |sbas_names }}</span> <span>{% trans 'login::register: acces temporaire sur' %} {{ sbasId |sbas_names }}</span>
@@ -85,7 +85,7 @@
{% if baseInsc['CollsOuttime'] %} {% if baseInsc['CollsOuttime'] %}
{% for collId, isTrue in baseInsc['CollsOuttime'] %} {% for collId, isTrue in baseInsc['CollsOuttime'] %}
{{ base_id == sbasId |base_from_coll(collId) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td colspan="3" style="text-align: center;"> <td colspan="3" style="text-align: center;">
<span style="color:red;">{% trans 'login::register: acces temporaire termine sur ' %}{{ sbasId |sbas_names }}</span> <span style="color:red;">{% trans 'login::register: acces temporaire termine sur ' %}{{ sbasId |sbas_names }}</span>
@@ -100,7 +100,7 @@
{% if baseInsc['CollsNonactif'] %} {% if baseInsc['CollsNonactif'] %}
{% for collId, isTrue in baseInsc['CollsNonactif'] %} {% for collId, isTrue in baseInsc['CollsNonactif'] %}
{{ base_id == (sbasId |base_from_coll(collId)) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td colspan="3" style="text-align: center;"> <td colspan="3" style="text-align: center;">
<span style="color:red;">{% trans 'login::register: acces supendu sur' %} {{ sbasId |sbas_names }}</span> <span style="color:red;">{% trans 'login::register: acces supendu sur' %} {{ sbasId |sbas_names }}</span>
@@ -114,7 +114,6 @@
{% endif %} {% endif %}
{% if (baseInsc['CollsCGU'] or baseInsc['Colls']) and baseInsc['inscript'] %} {% if (baseInsc['CollsCGU'] or baseInsc['Colls']) and baseInsc['inscript'] %}
{{ noDemand == false }}
{% if baseInsc['Colls'] %} {% if baseInsc['Colls'] %}
{% if baseInsc['CGU'] %} {% if baseInsc['CGU'] %}
<tr> <tr>
@@ -125,7 +124,7 @@
</tr> </tr>
{% endif %} {% endif %}
{% for collId, collName in baseInsc['Colls'] %} {% for collId, collName in baseInsc['Colls'] %}
{{ base_id == sbasId |base_from_coll(collId) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td style="text-align: right;">{{ collName }}</td> <td style="text-align: right;">{{ collName }}</td>
<td></td> <td></td>
@@ -138,7 +137,7 @@
{% endif %} {% endif %}
{% if baseInsc['CollsCGU'] %} {% if baseInsc['CollsCGU'] %}
{% for collId, collDesc in baseInsc['CollsCGU'] %} {% for collId, collDesc in baseInsc['CollsCGU'] %}
{{ base_id == sbasId |base_from_coll(collId) }} {% set base_id = sbasId |base_from_coll(collId) %}
<tr> <tr>
<td colspan="3" style="text-align: center;"><hr style="width: 80%"/></td> <td colspan="3" style="text-align: center;"><hr style="width: 80%"/></td>
</tr> </tr>

View File

@@ -48,8 +48,10 @@ $(document).ready(function() {
{% block content %} {% block content %}
{% if updateMsg is not none %} {% if updateMsg is not none %}
<div style="margin-top:100px;">{{ updateMsg }}</div> <div class="alert alert-info">
<div>{{ updateMsg }}</div>
<a href="/account/" target="_self">{% trans 'admin::compte-utilisateur retour a mon compte'%}</a> <a href="/account/" target="_self">{% trans 'admin::compte-utilisateur retour a mon compte'%}</a>
</div>
{% else %} {% else %}
{% if noticeMsg is not none %} {% if noticeMsg is not none %}

View File

@@ -56,7 +56,10 @@
{% block content %} {% block content %}
<form method="POST" action="/account/reset-password/" id="mainform" class="form-horizontal"> <form method="POST" action="/account/reset-password/" id="mainform" class="form-horizontal">
{% if passwordMsg is not none %} {% if passwordMsg is not none %}
<p class="form_alert help-block">{{ passwordMsg }}</p> <div class="alert alert-error">
<a class="close" data-dismiss="alert" href="#">×</a>
{{ passwordMsg }}
</div>
{% endif %} {% endif %}
<div class="control-group"> <div class="control-group">
<label class="form_label control-label" for="form_login">{% trans 'admin::compte-utilisateur identifiant' %}</label> <label class="form_label control-label" for="form_login">{% trans 'admin::compte-utilisateur identifiant' %}</label>

View File

@@ -95,7 +95,6 @@
<tr> <tr>
<td></td> <td></td>
<td><button class="app_submit" type="button">{% trans 'boutton::valider' %}</button</td> <td><button class="app_submit" type="button">{% trans 'boutton::valider' %}</button</td>
</tr> </tr>
</table> </table>
</form> </form>

View File

@@ -124,7 +124,10 @@
{% if not tokenize %} {% if not tokenize %}
<form name="send" action="/login/forgot-password/" method="POST" style="width: 600px; margin: 0 auto;"> <form name="send" action="/login/forgot-password/" method="POST" style="width: 600px; margin: 0 auto;">
{% if errorMsg is not none %} {% if errorMsg is not none %}
<div style="background:#00a8FF;">{{ errorMsg }}</div> <div class="alert alert-error">
<a class="close" data-dismiss="alert" href="#">×</a>
{{ errorMsg }}
</div>
{% endif %} {% endif %}
{% if sentMsg is not none %} {% if sentMsg is not none %}

View File

@@ -1,176 +0,0 @@
<html lang="{{ session.get_I18n() }}">
<head>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
<link type="text/css" rel="stylesheet" href="/skins/login/home.css" />
<title>{% trans 'admin::compte-utilisateur changer mon mot de passe' %}</title>
</head>
<body>
<div style="width: 950px;margin: 0 auto;">
<div style="margin-top: 70px;height: 35px;">
<table style="width: 100%;">
<tr style="height: 35px;">
<td style="width: auto;"><div style="font-size: 28px; color: #b1b1b1;"><?php echo $registry->get('GV_homeTitle') ?></div></td>
<td style="color: #b1b1b1; text-align: right;">
</td>
</tr>
</table>
</div>
<div style="height: 530px; background-color: #525252;">
<div id="id-main" class="tab-content" style="display: block;">
<!--<div style="width: 560px; float: left; height: 490px;">
<img src="/skins/icons/home.jpg" style="margin: 85px 10px; width: 540px;"/>
</div>-->
<div xstyle="width:360px;float:right;height:490px;">
<div style="margin: 40px 25px; float: left; width: 880px;">
{% if tokenize %}
<script type="text/javascript" language="javascript" src="/include/minify/f=include/jslibs/jquery-1.7.1.js"></script>
<script type="text/javascript" language="javascript" src="/include/minify/f=include/jslibs/jquery.validate.js"></script>
<script type="text/javascript" language="javascript" src="/include/minify/f=include/jslibs/jquery.validate.password.js"></script>
<script type="text/javascript" >
<?php
?>
$(document).ready(function() {
$.validator.passwordRating.messages = {
"similar-to-username": "{% trans 'forms::le mot de passe est trop similaire a l\'identifiant' %}",
"too-short": "{% trans 'forms::la valeur donnee est trop courte' %}",
"very-weak": "{% trans 'forms::le mot de passe est trop simple' %}",
"weak": "{% trans 'forms::le mot de passe est trop simple' %}",
"good": "{% trans 'forms::le mot de passe est bon' %}",
"strong": "{% trans 'forms::le mot de passe est tres bon' %}"
}
$("#password-reset").validate(
{
rules: {
<?php echo 'form_password_confirm:{required:true}' ?>
},
messages: {
<?php echo 'form_password_confirm : {equalTo:"' . {% trans 'forms::les mots de passe ne correspondent pas' %} . '"}' ?>
},
errorPlacement: function(error, element) {
error.prependTo( element.parent().parent().next().find('.form_alert') );
}
}
);
$('#form_password').rules("add",{password: "#form_login"});
$('#form_password_confirm').rules("add",{equalTo: "#form_password"});
$("#form_password").valid();
});
</script>
{% if parm['salt'] %}
<div class="notice" style="text-align: center; margin: 20px 40px; padding: 10px; font-weight: bold; font-size: 14px;">
{% trans 'Pour ameliorer la securite de l\'application, vous devez mettre a jour votre mot de passe.' %}<br/>
{% trans 'Cette tache ne pouvant etre automatisee, merci de bien vouloir la realiser.' %}
</div>
{% endif %}
<form name="send" action="forgotpwd.php" method="post" id="password-reset" style="width: 600px; margin: 0 auto;">
<table cellspacing="0" cellpadding="0" border="0">
<tr style="height: 30px;">
<td style="width: 33%;"><label for="form_password">{% trans 'admin::compte-utilisateur nouveau mot de passe' %} :</label></td>
<td style="width: 33%;">
<div class="form_input">
<input autocomplete="off" type="password" value="" id="form_password" name="form_password"/>
</div>
</td>
<td style="width: 33%;">
<div class="form_alert">
<?php echo isset($needed['form_password']) ? $needed['form_password'] : ''; ?>
<div class="password-meter">
<div class="password-meter-message">&nbsp;</div>
<div class="password-meter-bg">
<div class="password-meter-bar"></div>
</div>
</div>
</div>
</td>
</tr>
<tr style="height: 30px;">
<td>
<label for="form_password" >{% trans 'admin::compte-utilisateur confirmer le mot de passe' %} :</label></td>
<td>
<div class="form_input">
<input autocomplete="off" type="password" value="" id="form_password_confirm" name="form_password_confirm"/>
</div>
</td>
<td>
<div class="form_alert">
<?php echo isset($needed['form_password_confirm']) ? $needed['form_password_confirm'] : ''; ?>
</div>
</td>
</tr>
<tr style="height: 30px;">
<td></td>
<td>
<input type="hidden" value="<?php echo $parm['token']; ?>" name="token"/>
<input type="submit" value="valider"/>
</td>
<td>
<a class="link" href="index.php" target="_self">{% trans 'login:: Retour a l\'accueil' %}</a>
</td>
</tr>
</table>
</form>
{% endif %}
{% if tokenError %}
{% set parm = {'error': 'token'} %}
{% endif %}
{% if not tokenize and not tokenError %}
<form name="send" action="forgotpwd.php" method="post" style="width: 600px; margin: 0 auto;">
{% if not parm['error'] == null %}
switch ($parm['error']) {
case 'mailserver':
echo '<div style="background: #00a8FF;">{% trans 'phraseanet::erreur: Echec du serveur mail' %}</div>
break;
case 'noaccount':
echo '<div style="background: #00a8FF;">{% trans 'phraseanet::erreur: Le compte n\'a pas ete trouve' %}</div>
break;
case 'mail':
echo '<div style="background: #00a8FF;">{% trans 'phraseanet::erreur: Echec du serveur mail' %}</div>
break;
case 'token':
echo '<div style="background: #00a8FF;">{% trans 'phraseanet::erreur: l\'url n\'est plus valide' %}</div>
break;
}
{% endif %}
{% if not parm['sent'] == null %}
switch ($parm['sent']) {
case 'ok':
echo '<div style="background: #00a8FF;">{% trans 'phraseanet:: Un email vient de vous etre envoye' %}</div>
break;
}
{% endif %}
<div style="margin-top: 20px; font-size: 16px; font-weight: bold;">
{% trans 'login:: Forgot your password' %}
</div>
<div style="margin-top: 20px;">
{% trans 'login:: Entrez votre adresse email' %}
</div>
<div style="margin-top: 20px;">
<input name="mail" type="text" style="width:100%">
</div>
<div style="margin-top: 10px;">
<input type="submit" value="{% trans 'boutton::valider' %}"/>
<a style="margin-left: 120px;" class="link" href="index.php" target="_self">{% trans 'login:: Retour a l\'accueil' %}</a>
</div>
</form>
{% endif %}
</div>
</div>
</div>
<div style="text-align: right; position: relative; margin: 18px 10px 0 0; font-size: 10px; font-weight: normal;">
<span>&copy; Copyright Alchemy 2005-{{ "now"|date("Y") }}</span>
</div>
</div>
</div>
</body>
</html>

View File

@@ -4,6 +4,27 @@ require_once __DIR__ . '/../../../../PhraseanetWebTestCaseAuthenticatedAbstract.
class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
{ {
protected static $authorizedApp;
public static function setUpBeforeClass()
{
parent::setUpBeforeClass();
try {
self::$authorizedApp = \API_OAuth2_Application::create(\appbox::get_instance(\bootstrap::getCore()), self::$user, 'test API v1');
} catch (\Exception $e) {
}
}
public static function tearDownAfterClass()
{
if (self::$authorizedApp) {
self::$authorizedApp->delete();
}
parent::tearDownAfterClass();
}
public function setUp() public function setUp()
{ {
@@ -22,19 +43,53 @@ class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Account::displayAccount * @covers \Alchemy\Phrasea\Controller\Root\Account::displayAccount
* @covers \Alchemy\Phrasea\Controller\Root\Account::call
*/ */
public function testGetAccount() public function testGetAccount()
{ {
$this->client->request('GET', '/account/'); $crawler = $this->client->request('GET', '/account/');
$response = $this->client->getResponse(); $response = $this->client->getResponse();
$this->assertTrue($response->isOk()); $this->assertTrue($response->isOk());
$actionForm = $crawler->filter('form[name=account]')->attr('action');
$methodForm = $crawler->filter('form[name=account]')->attr('method');
$this->assertEquals('/account/', $actionForm);
$this->assertEquals('post', $methodForm);
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Account::accountAccess * @dataProvider msgProvider
*/
public function testGetAccountNotice($msg)
{
$crawler = $this->client->request('GET', '/account/', array(
'notice' => $msg
));
$response = $this->client->getResponse();
$this->assertTrue($response->isOk());
$this->assertEquals(1, $crawler->filter('.notice')->count());
}
public function msgProvider()
{
return array(
array('pass-ok'),
array('pass-ko'),
array('account-update-ok'),
array('account-update-bad'),
array('demand-ok'),
);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::accountAccess
*/ */
public function testGetAccountAccess() public function testGetAccountAccess()
{ {
@@ -46,19 +101,165 @@ class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Account::resetEmail * @covers \Alchemy\Phrasea\Controller\Root\Account::resetEmail
*/ */
public function testGetResetMail() public function testPostResetMailWithToken()
{ {
$this->client->request('GET', '/account/reset-email/'); $token = \random::getUrlToken(\random::TYPE_EMAIL, self::$user->get_id(), null, 'new_email@email.com');
$this->client->request('POST', '/account/reset-email/', array('token' => $token));
$response = $this->client->getResponse(); $response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/reset-email/?update=ok', $response->headers->get('location'));
$this->assertTrue($response->isOk()); $this->assertEquals('new_email@email.com', self::$user->get_email());
self::$user->set_email('noone@example.com');
try {
\random::helloToken($token);
$this->fail('TOken has not been removed');
} catch (\Exception_NotFound $e) {
}
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Account::accountSessionsAccess * @covers \Alchemy\Phrasea\Controller\Root\Account::resetEmail
*/
public function testPostResetMailWithBadToken()
{
$this->client->request('POST', '/account/reset-email/', array('token' => '134dT0k3n'));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/reset-email/?update=ko', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::resetEmail
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testPostResetMailBadRequest()
{
$this->client->request('POST', '/account/reset-email/');
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::resetEmail
*/
public function testPostResetMailBadPassword()
{
$this->client->request('POST', '/account/reset-email/', array(
'form_password' => 'changeme',
'form_email' => 'new@email.com',
'form_email_confirm' => 'new@email.com',
));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/reset-email/?notice=bad-password', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::resetEmail
*/
public function testPostResetMailBadEmail()
{
$password = \random::generatePassword();
self::$user->set_password($password);
$this->client->request('POST', '/account/reset-email/', array(
'form_password' => $password,
'form_email' => "invalid#!&&@@email.x",
'form_email_confirm' => 'invalid#!&&@@email.x',
));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/reset-email/?notice=mail-invalid', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::resetEmail
*/
public function testPostResetMailEmailNotIdentical()
{
$password = \random::generatePassword();
self::$user->set_password($password);
$this->client->request('POST', '/account/reset-email/', array(
'form_password' => $password,
'form_email' => 'email1@email.com',
'form_email_confirm' => 'email2@email.com',
));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/reset-email/?notice=mail-match', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::resetEmail
*/
public function testPostResetMailEmail()
{
$password = \random::generatePassword();
self::$user->set_password($password);
$this->client->request('POST', '/account/reset-email/', array(
'form_password' => $password,
'form_email' => 'email1@email.com',
'form_email_confirm' => 'email1@email.com',
));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/reset-email/?update=mail-send', $response->headers->get('location'));
}
/**
* @dataProvider noticeProvider
*/
public function testGetResetMailNotice($notice)
{
$crawler = $this->client->request('GET', '/account/reset-email/', array(
'notice' => $notice
));
$this->assertTrue($this->client->getResponse()->isOk());
$this->assertEquals(2, $crawler->filter('.notice')->count());
}
public function noticeProvider()
{
return array(
array('mail-server'),
array('mail-match'),
array('mail-invalid'),
array('bad-password'),
);
}
/**
* @dataProvider updateMsgProvider
*/
public function testGetResetMailUpdate($updateMessage)
{
$crawler = $this->client->request('GET', '/account/reset-email/', array(
'update' => $updateMessage
));
$this->assertTrue($this->client->getResponse()->isOk());
$this->assertEquals(1, $crawler->filter('.alert-info')->count());
}
public function updateMsgProvider()
{
return array(
array('ok'),
array('ko'),
array('mail-send'),
);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::accountSessionsAccess
*/ */
public function testGetAccountSecuritySessions() public function testGetAccountSecuritySessions()
{ {
@@ -70,7 +271,7 @@ class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Account::accountAuthorizedApps * @covers \Alchemy\Phrasea\Controller\Root\Account::accountAuthorizedApps
*/ */
public function testGetAccountSecurityApplications() public function testGetAccountSecurityApplications()
{ {
@@ -82,7 +283,7 @@ class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Account::resetPassword * @covers \Alchemy\Phrasea\Controller\Root\Account::resetPassword
*/ */
public function testGetResetPassword() public function testGetResetPassword()
{ {
@@ -94,15 +295,40 @@ class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Account::renewPassword * @dataProvider passwordMsgProvider
*/
public function testGetResetPasswordPassError($msg)
{
$crawler = $this->client->request('GET', '/account/reset-password/', array(
'pass-error' => $msg
));
$response = $this->client->getResponse();
$this->assertTrue($response->isOk());
$this->assertEquals(1, $crawler->filter('.alert-error')->count());
}
public function passwordMsgProvider()
{
return array(
array('pass-match'),
array('pass-short'),
array('pass-invalid'),
);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Account::updateAccount
*/ */
public function testUpdateAccount() public function testUpdateAccount()
{ {
$core = \bootstrap::getCore(); $evtMngr = \eventsmanager_broker::getInstance($this->app['phraseanet.appbox'], $this->app['phraseanet.core']);
$appbox = \appbox::get_instance($core); $register = new \appbox_register($this->app['phraseanet.appbox']);
$bases = $notifs = array();
$bases = array(); foreach ($this->app['phraseanet.appbox']->get_databoxes() as $databox) {
foreach ($appbox->get_databoxes() as $databox) {
foreach ($databox->get_collections() as $collection) { foreach ($databox->get_collections() as $collection) {
$bases[] = $collection->get_base_id(); $bases[] = $collection->get_base_id();
} }
@@ -112,6 +338,14 @@ class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
$this->markTestSkipped('No collections'); $this->markTestSkipped('No collections');
} }
foreach ($evtMngr->list_notifications_available($this->app['phraseanet.core']->getAUthenticatedUser()->get_id()) as $notifications) {
foreach ($notifications as $notification) {
$notifs[] = $notification['id'];
}
}
array_shift($notifs);
$this->client->request('POST', '/account/', array( $this->client->request('POST', '/account/', array(
'demand' => $bases, 'demand' => $bases,
'form_gender' => 'M', 'form_gender' => 'M',
@@ -130,14 +364,140 @@ class AccountTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
'form_pwdFTP' => '', 'form_pwdFTP' => '',
'form_destFTP' => '', 'form_destFTP' => '',
'form_prefixFTPfolder' => '', 'form_prefixFTPfolder' => '',
'notifications' => $notifs,
'form_defaultdataFTP' => array('document', 'preview', 'caption'), 'form_defaultdataFTP' => array('document', 'preview', 'caption'),
'mail_notifications' => '1' 'mail_notifications' => '1'
)); ));
$response = $this->client->getResponse(); $response = $this->client->getResponse();
$this->assertTrue($response->isRedirect()); $this->assertTrue($response->isRedirect());
$this->assertEquals('minet', $core->getAUthenticatedUser()->get_lastname()); $this->assertEquals('minet', $this->app['phraseanet.core']->getAUthenticatedUser()->get_lastname());
$ret = $register->get_collection_awaiting_for_user(self::$user);
$this->assertEquals(count($ret), count($bases));
} }
/**
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testAUthorizedAppGrantAccessBadRequest()
{
$this->client->request('GET', '/account/security/application/3/grant/');
}
public function testAUthorizedAppGrantAccessNotSuccessfull()
{
$this->client->request('GET', '/account/security/application/3/grant/', array(), array(), array('HTTP_ACCEPT' => 'application/json', 'HTTP_X-Requested-With' => 'XMLHttpRequest'));
$response = $this->client->getResponse();
$this->assertTrue($response->isOk());
$json = json_decode($response->getContent());
$this->assertInstanceOf('StdClass', $json);
$this->assertObjectHasAttribute('success', $json);
$this->assertFalse($json->success);
}
/**
* @dataProvider revokeProvider
*/
public function testAUthorizedAppGrantAccessSuccessfull($revoke, $expected)
{
if (null === self::$authorizedApp) {
$this->markTestSkipped('Application could not be created');
}
$this->client->request('GET', '/account/security/application/' . self::$authorizedApp->get_id() . '/grant/', array(
'revoke' => $revoke
), array(), array(
'HTTP_ACCEPT' => 'application/json',
'HTTP_X-Requested-With' => 'XMLHttpRequest'
));
$response = $this->client->getResponse();
$this->assertTrue($response->isOk());
$json = json_decode($response->getContent());
$this->assertInstanceOf('StdClass', $json);
$this->assertObjectHasAttribute('success', $json);
$this->assertTrue($json->success);
$account = \API_OAuth2_Account::load_with_user(
$this->app['phraseanet.appbox']
, self::$authorizedApp
, self::$user
);
$this->assertEquals($expected, $account->is_revoked());
}
public function revokeProvider()
{
return array(
array('1', true),
array('0', false),
array(null, false),
array('titi', true),
);
}
/**
* @dataProvider passwordProvider
*/
public function testPostRenewPasswordBadArguments($oldPassword, $password, $passwordConfirm, $redirect)
{
self::$user->set_password($oldPassword);
$this->client->request('POST', '/account/forgot-password/', array(
'form_password' => $password,
'form_password_confirm' => $passwordConfirm,
'form_old_password' => $oldPassword
));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals($redirect, $response->headers->get('location'));
}
public function testPostRenewPasswordBadOldPassword()
{
$this->client->request('POST', '/account/forgot-password/', array(
'form_password' => 'password',
'form_password_confirm' => 'password',
'form_old_password' => 'oulala'
));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/?notice=pass-ko', $response->headers->get('location'));
}
public function testPostRenewPassword()
{
$password = \random::generatePassword();
self::$user->set_password($password);
$this->client->request('POST', '/account/forgot-password/', array(
'form_password' => 'password',
'form_password_confirm' => 'password',
'form_old_password' => $password
));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/account/?notice=pass-ok', $response->headers->get('location'));
}
public function passwordProvider()
{
return array(
array(\random::generatePassword(), 'password', 'not_identical_password', '/account/reset-password/?pass-error=pass-match'),
array(\random::generatePassword(), 'min', 'min', '/account/reset-password/?pass-error=pass-short'),
array(\random::generatePassword(), 'invalid password \n', 'invalid password \n', '/account/reset-password/?pass-error=pass-invalid'),
);
}
} }

View File

@@ -0,0 +1,290 @@
<?php
require_once __DIR__ . '/../../../../PhraseanetWebTestCaseAuthenticatedAbstract.class.inc';
class DevelopersTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
{
public function setUp()
{
parent::setUp();
$this->client = $this->createClient();
}
public function tearDown()
{
parent::tearDown();
}
public function createApplication()
{
$app = require __DIR__ . '/../../../../../lib/Alchemy/Phrasea/Application/Root.php';
$app['debug'] = true;
unset($app['exception_handler']);
return $app;
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Developers::listApps
*/
public function testListApps()
{
$this->client->request('GET', '/developers/applications/');
$this->assertTrue($this->client->getResponse()->isOk());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Developers::displayFormApp
*/
public function testDisplayformApp()
{
$crawler = $this->client->request('GET', '/developers/application/new/');
$this->assertTrue($this->client->getResponse()->isOk());
$form = $crawler->selectButton(_('boutton::valider'))->form();
$this->assertEquals('/developers/application/', $form->getFormNode()->getAttribute('action'));
$this->assertEquals('POST', $form->getMethod());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Developers::newApp
*/
public function testPostNewAppInvalidArguments()
{
$crawler = $this->client->request('POST', '/developers/application/', array(
'type' => \API_OAuth2_Application::WEB_TYPE,
'name' => '',
'description' => 'okok',
'website' => 'my.website.com',
'callback' => 'my.callback.com',
'scheme-website' => 'http://',
'scheme-callback' => 'http://'
));
$this->assertTrue($this->client->getResponse()->isOk());
$form = $crawler->selectButton(_('boutton::valider'))->form();
$this->assertEquals('okok', $form['description']->getValue());
$this->assertEquals('my.website.com', $form['website']->getValue());
$this->assertEquals('my.callback.com', $form['callback']->getValue());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Developers::newApp
*/
public function testPostNewApp()
{
$apps = API_OAuth2_Application::load_dev_app_by_user($this->app['phraseanet.appbox'], self::$user);
$nbApp = count($apps);
$this->client->request('POST', '/developers/application/', array(
'type' => \API_OAuth2_Application::WEB_TYPE,
'name' => 'hello',
'description' => 'okok',
'website' => 'my.website.com',
'callback' => 'my.callback.com',
'scheme-website' => 'http://',
'scheme-callback' => 'http://'
));
$apps = API_OAuth2_Application::load_dev_app_by_user($this->app['phraseanet.appbox'], self::$user);
$this->assertTrue($this->client->getResponse()->isRedirect());
$this->assertGreaterThan($nbApp, count($apps));
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::getApp
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testGetUnknowApp()
{
$this->client->request('GET', '/developers/application/0/');
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::getApp
*/
public function testGetApp()
{
$oauthApp = \API_OAuth2_Application::create(\appbox::get_instance(\bootstrap::getCore()), self::$user, 'test app');
$this->client->request('GET', '/developers/application/' . $oauthApp->get_id() . '/');
$this->assertTrue($this->client->getResponse()->isOk());
$oauthApp->delete();
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::deleteApp
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testDeleteAppBadRequest()
{
$this->client->request('DELETE', '/developers/application/1/');
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::deleteApp
*/
public function testDeleteAppError()
{
$this->XMLHTTPRequest('DELETE', '/developers/application/0/');
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertFalse($content->success);
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::deleteApp
*/
public function testDeleteApp()
{
$oauthApp = \API_OAuth2_Application::create(\appbox::get_instance(\bootstrap::getCore()), self::$user, 'test app');
$this->XMLHTTPRequest('DELETE', '/developers/application/' . $oauthApp->get_id() . '/');
$this->assertTrue($this->client->getResponse()->isOk());
try {
new \API_OAuth2_Application($this->app['phraseanet.appbox'], $oauthApp->get_id());
$this->fail('Application not deleted');
} catch (\Exception_NotFound $e) {
}
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::renewAppCallback
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testRenewAppCallbackBadRequest()
{
$this->client->request('POST', '/developers/application/1/callback/');
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::renewAppCallback
*/
public function testRenewAppCallbackError()
{
$this->XMLHTTPRequest('POST', '/developers/application/0/callback/', array(
'callback' => 'my.callback.com'
));
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertFalse($content->success);
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::renewAppCallback
*/
public function testRenewAppCallbackError2()
{
$oauthApp = \API_OAuth2_Application::create(\appbox::get_instance(\bootstrap::getCore()), self::$user, 'test app');
$this->XMLHTTPRequest('POST', '/developers/application/'.$oauthApp->get_id().'/callback/');
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertFalse($content->success);
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::renewAppCallback
*/
public function testRenewAppCallback()
{
$oauthApp = \API_OAuth2_Application::create(\appbox::get_instance(\bootstrap::getCore()), self::$user, 'test app');
$this->XMLHTTPRequest('POST', '/developers/application/' . $oauthApp->get_id() . '/callback/', array(
'callback' => 'my.callback.com'
));
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertTrue($content->success);
$oauthApp = new \API_OAuth2_Application($this->app['phraseanet.appbox'], $oauthApp->get_id());
$this->assertEquals('my.callback.com', $oauthApp->get_redirect_uri());
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::renewAccessToken
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testRenewAccessTokenbadRequest()
{
$this->client->request('POST', '/developers/application/1/access_token/');
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::renewAccessToken
*/
public function testRenewAccessTokenError()
{
$this->XMLHTTPRequest('POST', '/developers/application/0/access_token/', array(
'callback' => 'my.callback.com'
));
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertFalse($content->success);
$this->assertNull($content->token);
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::renewAccessToken
*/
public function testRenewAccessToken()
{
$oauthApp = \API_OAuth2_Application::create(\appbox::get_instance(\bootstrap::getCore()), self::$user, 'test app');
$this->XMLHTTPRequest('POST', '/developers/application/' . $oauthApp->get_id() . '/access_token/');
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertTrue($content->success);
$this->assertNotNull($content->token);
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::authorizeGrantpassword
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testAuthorizeGrantpasswordBadRequest()
{
$this->client->request('POST', '/developers/application/1/authorize_grant_password/');
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::authorizeGrantpassword
*/
public function testAuthorizeGrantpasswordError()
{
$this->XMLHTTPRequest('POST', '/developers/application/0/authorize_grant_password/', array(
'callback' => 'my.callback.com'
));
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertFalse($content->success);
}
/**
* @cover \Alchemy\Phrasea\Controller\Root\Developers::authorizeGrantpassword
*/
public function testAuthorizeGrantpasswordToken()
{
$oauthApp = \API_OAuth2_Application::create(\appbox::get_instance(\bootstrap::getCore()), self::$user, 'test app');
$this->XMLHTTPRequest('POST', '/developers/application/' . $oauthApp->get_id() . '/authorize_grant_password/', array(
'grant' => '1'
));
$this->assertTrue($this->client->getResponse()->isOk());
$content = json_decode($this->client->getResponse()->getContent());
$this->assertTrue($content->success);
$oauthApp = new \API_OAuth2_Application($this->app['phraseanet.appbox'], $oauthApp->get_id());
$this->assertTrue($oauthApp->is_password_granted());
}
}

View File

@@ -22,64 +22,714 @@ class LoginTest extends \PhraseanetWebTestCaseAuthenticatedAbstract
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Login::sendConfirmMail * @covers \Alchemy\Phrasea\Controller\Root\Login::login
* @covers \Alchemy\Phrasea\Controller\Root\Login::connect
*/ */
public function testGetConfirMail() public function testLoginAlreadyAthenticated()
{ {
$this->markTestIncomplete(); $this->client->request('GET', '/login/');
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/prod/', $response->headers->get('location'));
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Login::registerConfirm * @covers \Alchemy\Phrasea\Controller\Root\Login::login
*/
public function testLoginRedirectPostLog()
{
$this->app['phraseanet.appbox']->get_session()->logout();
$this->client->request('GET', '/login/', array('postlog' => '1', 'redirect' => 'prod'));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/logout/?redirect=prod', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::login
* @dataProvider errorAndNoticeMsgProvider
*/
public function testLoginError($warning, $notice)
{
$this->app['phraseanet.appbox']->get_session()->logout();
$this->client->request('GET', '/login/', array(
'error' => $warning,
'notice' => $notice
));
$response = $this->client->getResponse();
$this->assertTrue($response->isOk());
}
public function errorAndNoticeMsgProvider()
{
return array(
array('auth', 'ok'),
array('maintenance', 'already'),
array('no-connection', 'mail-sent'),
array('captcha', 'register-ok'),
array('mail-not-confirmed', 'register-ok-wait'),
array('no-base', 'password-update-ok'),
array('session', 'no-register-available')
);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::registerConfirm
*/
public function testRegisterConfirmMailNoCode()
{
$this->client->request('GET', '/login/register-confirm/');
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?redirect=/prod&error=code-not-found', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::registerConfirm
*/
public function testRegisterConfirmMailWrongCode()
{
$this->client->request('GET', '/login/register-confirm/', array('code' => '34dT0k3n'));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?redirect=/prod&error=token-not-found', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::registerConfirm
*/
public function testRegisterConfirmMailUserNotFound()
{
$email = $this->generateEmail();
$token = \random::getUrlToken(\random::TYPE_EMAIL, 0, null, $email);
$this->client->request('GET', '/login/register-confirm/', array('code' => $token));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?redirect=/prod&error=user-not-found', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::registerConfirm
*/
public function testRegisterConfirmMailUnlocked()
{
$email = $this->generateEmail();
$token = \random::getUrlToken(\random::TYPE_EMAIL, self::$user->get_id(), null, $email);
self::$user->set_mail_locked(false);
$this->client->request('GET', '/login/register-confirm/', array('code' => $token));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?redirect=prod&notice=already', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::registerConfirm
*/ */
public function testRegisterConfirmMail() public function testRegisterConfirmMail()
{ {
$this->markTestIncomplete(); $email = $this->generateEmail();
$appboxRegister = new \appbox_register($this->app['phraseanet.appbox']);
$token = \random::getUrlToken(\random::TYPE_EMAIL, self::$user->get_id(), null, $email);
self::$user->set_mail_locked(true);
$this->deleteRequest();
$appboxRegister->add_request(self::$user, self::$collection);
$this->client->request('GET', '/login/register-confirm/', array('code' => $token));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?redirect=prod&notice=confirm-ok-wait', $response->headers->get('location'));
$this->assertFalse(self::$user->get_mail_locked());
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Login::renewPassword * @covers \Alchemy\Phrasea\Controller\Root\Login::registerConfirm
*/
public function testRegisterConfirmMailNoCollAwait()
{
$email = $this->generateEmail();
$token = \random::getUrlToken(\random::TYPE_EMAIL, self::$user->get_id(), null, $email);
self::$user->set_mail_locked(true);
$this->deleteRequest();
$this->client->request('GET', '/login/register-confirm/', array('code' => $token));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?redirect=prod&notice=confirm-ok', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::renewPassword
*/
public function testRenewPasswordInvalidEmail()
{
$this->client->request('POST', '/login/forgot-password/', array('mail' => 'invalid.email.com'));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/forgot-password/?error=invalidmail', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::renewPassword
*/
public function testRenewPasswordUnknowEmail()
{
$this->client->request('POST', '/login/forgot-password/', array('mail' => 'invalid_email@test.com'));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/forgot-password/?error=noaccount', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::renewPassword
*/
public function testRenewPasswordMail()
{
$this->client->request('POST', '/login/forgot-password/', array('mail' => self::$user->get_email()));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/forgot-password/?sent=ok', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::renewPassword
* @dataProvider passwordProvider
*/
public function testRenewPasswordBadArguments($password, $passwordConfirm, $redirect)
{
$this->client->request('POST', '/login/forgot-password/', array(
'token' => '1Cx6Z7',
'form_password' => $password,
'form_password_confirm' => $passwordConfirm
)
);
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals($redirect, $response->headers->get('location'));
}
public function testRenewPasswordBadToken()
{
$this->client->request('POST', '/login/forgot-password/', array(
'token' => 'badToken',
'form_password' => 'password',
'form_password_confirm' => 'password'
)
);
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/forgot-password/?error=token', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::renewPassword
* @dataProvider passwordProvider
*/ */
public function testRenewPassword() public function testRenewPassword()
{ {
$this->markTestIncomplete(); $token = \random::getUrlToken(\random::TYPE_PASSWORD, self::$user->get_id());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root/Login::displayForgotPasswordForm
*/
public function testGetForgotPassword()
{
$this->markTestSkipped('Update rewrite rules');
$this->client->request('GET', '/login/forgot-password/');
$this->client->request('POST', '/login/forgot-password/', array(
'token' => $token,
'form_password' => 'password',
'form_password_confirm' => 'password'
)
);
$response = $this->client->getResponse(); $response = $this->client->getResponse();
$this->assertTrue($response->isOk()); $this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?notice=password-update-ok', $response->headers->get('location'));
}
public function passwordProvider()
{
return array(
array('password', 'password_not_identical', '/login/forgot-password/?pass-error=pass-match'),
array('min', 'min', '/login/forgot-password/?pass-error=pass-short'),
array('in valid password', 'in valid password', '/login/forgot-password/?pass-error=pass-invalid'),
);
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Login::displayRegisterForm * @covers \Alchemy\Phrasea\Controller\Root\Login::displayForgotPasswordForm
*/ */
public function testGetRegister() public function testGetForgotPasswordSendMsg()
{ {
$this->markTestSkipped('Update rewrite rules'); $this->client->request('GET', '/login/forgot-password/', array(
'sent' => 'ok',
));
$this->client->request('GET', '/login/register/'); $this->assertTrue($this->client->getResponse()->isOk());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::displayForgotPasswordForm
*/
public function testGetForgotBadToken()
{
$crawler = $this->client->request('GET', '/login/forgot-password/', array(
'token' => 'one-token'
));
$this->assertTrue($this->client->getResponse()->isOk());
$this->assertEquals(1, $crawler->filter('.alert-error')->count());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::displayForgotPasswordForm
* @dataProvider errorMessageProvider
*/
public function testGetForgotPasswordErrorMsg($errorMsg)
{
$crawler = $this->client->request('GET', '/login/forgot-password/', array(
'error' => $errorMsg
));
$response = $this->client->getResponse(); $response = $this->client->getResponse();
$this->assertTrue($response->isOk()); $this->assertTrue($response->isOk());
$this->assertEquals(1, $crawler->filter('.alert-error')->count());
}
public function errorMessageProvider()
{
return array(
array('invalidmail'),
array('mailserver'),
array('noaccount'),
array('mail'),
array('token'),
);
} }
/** /**
* @covers \Alchemy\Phrasea\Controller\Root/Login::logout * @covers \Alchemy\Phrasea\Controller\Root\Login::displayForgotPasswordForm
* @dataProvider badPasswordMsgProvider
*/
public function testGetForgotPasswordBadPassword($msg)
{
$this->client->request('GET', '/login/forgot-password/', array(
'pass-error' => $msg,
));
$this->assertTrue($this->client->getResponse()->isOk());
}
public function badPasswordMsgProvider()
{
return array(
array('pass-match'),
array('pass-short'),
array('pass-invalid'),
);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::displayRegisterForm
* @covers \Alchemy\Phrasea\Controller\Root\Login::getRegisterFieldConfiguration
* @dataProvider fieldErrorProvider
*/
public function testGetRegister($error)
{
$this->client->request('GET', '/login/register/', array(
'needed' => array(
'field_name' => $error,
)
));
/**
* @todo change this
*/
if ( ! \login::register_enabled()) {
$this->assertTrue($this->client->getResponse()->isRedirect());
} else {
$this->assertTrue($this->client->getResponse()->isOk());
}
}
public function fieldErrorProvider()
{
return array(
array('required-field'),
array('pass-match'),
array('pass-short'),
array('pass-invalid'),
array('email-invalid'),
array('login-short'),
array('login-mail-exists'),
array('user-mail-exists'),
array('no-collections'),
);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::register
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testPostRegisterBadRequest()
{
$this->client->request('POST', '/login/register/');
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::register
* @dataProvider parametersProvider
*/
public function testPostRegisterbadArguments($parameters)
{
$this->client->request('POST', '/login/register/', $parameters);
$this->assertTrue($this->client->getResponse()->isRedirect());
}
public function parametersProvider()
{
return array(
array(array(//required field
"form_login" => '',
"form_password" => 'password',
"form_password_confirm" => 'password',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@email.com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
)),
array(array(//password mismatch
"form_login" => 'login',
"form_password" => 'password',
"form_password_confirm" => 'passwordmismatch',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@email.com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
)),
array(array(//password tooshort
"form_login" => 'login',
"form_password" => 'min',
"form_password_confirm" => 'min',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@email.com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
)),
array(array(//password invalid
"form_login" => 'login',
"form_password" => 'invalid pass word',
"form_password_confirm" => 'invalid pass word',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@email.com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
)),
array(array(//email invalid
"form_login" => 'login',
"form_password" => 'password',
"form_password_confirm" => 'password',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
)),
array(array(//login exists
"form_login" => 'test_phpunit',
"form_password" => 'invalid pass word',
"form_password_confirm" => 'invalid pass word',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@email.com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
)),
array(array(//mails exists
"form_login" => 'login',
"form_password" => 'invalid pass word',
"form_password_confirm" => 'noone@example.com',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@email.com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
)),
array(array(//no demands
"form_login" => 'login',
"form_password" => 'invalid pass word',
"form_password_confirm" => 'email@email.com',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => 'email@email.com',
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => array()
))
);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::register
*/
public function testPostRegister()
{
$bases = array();
foreach ($this->app['phraseanet.appbox']->get_databoxes() as $databox) {
foreach ($databox->get_collections() as $collection) {
$bases[] = $collection->get_base_id();
}
}
$login = \random::generatePassword();
$email = $login . '@google.com';
$this->client->request('POST', '/login/register/', array(
"form_login" => $login,
"form_password" => 'password',
"form_password_confirm" => 'password',
"form_gender" => 'M',
"form_lastname" => 'lastname',
"form_firstname" => 'firstname',
"form_email" => $email,
"form_job" => 'job',
"form_company" => 'company',
"form_activity" => 'activity',
"form_phone" => 'phone',
"form_fax" => 'fax',
"form_address" => 'adress',
"form_zip" => 'zip',
"form_geonameid" => 'geoname_id',
"demand" => $bases
));
if ( ! $userId = \User_Adapter::get_usr_id_from_login($login)) {
$this->fail('User not created');
}
$user = new User_Adapter((int) $userId, $this->app['phraseanet.appbox']);
$user->delete();
$this->assertTrue($this->client->getResponse()->isRedirect());
$this->assertEquals('/login/?notice=mail-sent', $this->client->getResponse()->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::logout
*/ */
public function testGetLogout() public function testGetLogout()
{ {
$this->markTestIncomplete(); $this->assertTrue($this->app['phraseanet.core']->isAuthenticated());
$this->client->request('GET', '/login/logout/', array('app' => 'prod'));
$this->assertFalse($this->app['phraseanet.core']->isAuthenticated());
$this->assertTrue($this->client->getResponse()->isRedirect());
} }
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::sendConfirmMail
* @expectedException Symfony\Component\HttpKernel\Exception\HttpException
*/
public function testSendConfirmMailBadRequest()
{
$this->client->request('GET', '/login/send-mail-confirm/');
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::sendConfirmMail
*/
public function testSendConfirmMail()
{
$this->client->request('GET', '/login/send-mail-confirm/', array('usr_id' => self::$user->get_id()));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?notice=mail-sent', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::sendConfirmMail
*/
public function testSendConfirmMailWrongUser()
{
$this->client->request('GET', '/login/send-mail-confirm/', array('usr_id' => 0));
$response = $this->client->getResponse();
$this->assertTrue($response->isRedirect());
$this->assertEquals('/login/?error=user-not-found', $response->headers->get('location'));
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::authenticate
*/
public function testAuthenticate()
{
$this->app['phraseanet.appbox']->get_session()->logout();
$password = \random::generatePassword();
self::$user->set_password($password);
$this->client->request('POST', '/login/authenticate/', array(
'login' => self::$user->get_login(),
'pwd' => $password
));
$this->assertTrue($this->client->getResponse()->isRedirect());
$this->assertTrue($this->app['phraseanet.core']->isAuthenticated());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::authenticate
*/
public function testBadAuthenticate()
{
$this->app['phraseanet.appbox']->get_session()->logout();
$this->client->request('POST', '/login/authenticate/', array(
'login' => self::$user->get_login(),
'pwd' => 'test'
));
$this->assertTrue($this->client->getResponse()->isRedirect());
$this->assertRegexp('/error=auth/', $this->client->getResponse()->headers->get('location'));
$this->assertFalse($this->app['phraseanet.core']->isAuthenticated());
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::authenticate
*/
public function testMailLockedAuthenticate()
{
$this->app['phraseanet.appbox']->get_session()->logout();
$password = \random::generatePassword();
self::$user->set_mail_locked(true);
$this->client->request('POST', '/login/authenticate/', array(
'login' => self::$user->get_login(),
'pwd' => $password
));
$this->assertTrue($this->client->getResponse()->isRedirect());
$this->assertRegexp('/error=mail-not-confirmed/', $this->client->getResponse()->headers->get('location'));
$this->assertFalse($this->app['phraseanet.core']->isAuthenticated());
self::$user->set_mail_locked(false);
}
/**
* @covers \Alchemy\Phrasea\Controller\Root\Login::authenticate
*/
public function testAuthenticateUnavailable()
{
$this->app['phraseanet.appbox']->get_session()->logout();
$password = \random::generatePassword();
$this->app['phraseanet.core']['Registry']->set('GV_maintenance', true , \registry::TYPE_BOOLEAN);
$this->client->request('POST', '/login/authenticate/', array(
'login' => self::$user->get_login(),
'pwd' => $password
));
$this->app['phraseanet.core']['Registry']->set('GV_maintenance', false, \registry::TYPE_BOOLEAN);
$this->assertTrue($this->client->getResponse()->isRedirect());
$this->assertRegexp('/error=maintenance/', $this->client->getResponse()->headers->get('location'));
$this->assertFalse($this->app['phraseanet.core']->isAuthenticated());
} }
/**
* Delete inscription demand made by the current authenticathed user
* @return void
*/
private function deleteRequest()
{
$sql = "DELETE FROM demand WHERE usr_id = :usr_id";
$stmt = $this->app['phraseanet.appbox']->get_connection()->prepare($sql);
$stmt->execute(array(':usr_id' => self::$user->get_id()));
$stmt->closeCursor();
}
/**
* Generate a new valid email adress
* @return string
*/
private function generateEmail()
{
return \random::generatePassword() . '_email@email.com';
}
}

View File

@@ -4,6 +4,8 @@ require_once __DIR__ . "/PhraseanetPHPUnitListener.class.inc";
use Silex\WebTestCase; use Silex\WebTestCase;
use Doctrine\Common\DataFixtures\Loader; use Doctrine\Common\DataFixtures\Loader;
use Symfony\Component\HttpKernel\Client;
use Symfony\Component\DomCrawler\Crawler;
abstract class PhraseanetPHPUnitAbstract extends WebTestCase abstract class PhraseanetPHPUnitAbstract extends WebTestCase
{ {
@@ -83,6 +85,16 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
self::$time_start = microtime(true); self::$time_start = microtime(true);
} }
//check if app is set up
if ( ! setup::is_installed()) {
exit("\033[0;31mPhraseanet is not set up\033[0;37m\r\n");
}
//init core
if (null === self::$core) {
self::$core = \bootstrap::getCore();
}
self::updateTablesSchema(); self::updateTablesSchema();
self::createSetOfUserTests(); self::createSetOfUserTests();
@@ -102,26 +114,6 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
parent::tearDownAfterClass(); parent::tearDownAfterClass();
} }
/**
* Delete temporay sqlite database
* Create schema using $this->classesMetatdas
* Load DoctrineTestServices
*
* @return
*/
public function __construct()
{
//check if app is set up
if ( ! setup::is_installed()) {
exit("\033[0;31mPhraseanet is not set up\033[0;37m\r\n");
}
//init core
if (null === self::$core) {
self::$core = \bootstrap::getCore();
}
}
/** /**
* Delete all ressources created during the test * Delete all ressources created during the test
*/ */
@@ -495,6 +487,28 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
return; return;
} }
/**
* Calls a URI as XMLHTTP request.
*
* @param string $method The request method
* @param string $uri The URI to fetch
* @param array $parameters The Request parameters
* @param array $httpAccept Contents of the Accept header
*
* @return Crawler
*/
protected function XMLHTTPRequest($method, $uri, array $parameters = array(), $httpAccept = 'application/json')
{
if ( ! $this->client instanceof Client) {
throw new \Exception('Not client seems intitialized');
}
return $this->client->request($method, $uri, $parameters, array(), array(
'HTTP_ACCEPT' => $httpAccept,
'HTTP_X-Requested-With' => 'XMLHttpRequest',
));
}
/** /**
* Update the sql tables with the current schema * Update the sql tables with the current schema
* @return void * @return void
@@ -618,6 +632,7 @@ abstract class PhraseanetPHPUnitAbstract extends WebTestCase
foreach ($databox->get_collections() as $collection) { foreach ($databox->get_collections() as $collection) {
$base_id = $collection->get_base_id(); $base_id = $collection->get_base_id();
$user->ACL()->give_access_to_base(array($base_id)); $user->ACL()->give_access_to_base(array($base_id));
set_exportorder::set_order_admins(array($user->get_id()), $base_id); set_exportorder::set_order_admins(array($user->get_id()), $base_id);

View File

@@ -87,7 +87,7 @@ function login(what)
{ {
EcrireCookie('last_act',what,null,'/'); EcrireCookie('last_act',what,null,'/');
} }
self.location.replace('/login/index.php?postlog=1'); self.location.replace('/login/?postlog=1');
} }
return false; return false;
} }