Skip to content

Commit

Permalink
remove connection between session lifetime and php gc, allow to login…
Browse files Browse the repository at this point in the history
… on frontend with username, cover /auth with symfony firewall
  • Loading branch information
ahilles107 committed Jan 19, 2016
1 parent cf9c52e commit 6967786
Show file tree
Hide file tree
Showing 14 changed files with 106 additions and 97 deletions.
12 changes: 6 additions & 6 deletions newscoop/application/configs/symfony/security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ security:
backend_db:
entity: { class: Newscoop\Entity\User, property: username }
frontend_db:
entity: { class: Newscoop\Entity\User, property: email }
entity: { class: Newscoop\Entity\User }

firewalls:
dev:
Expand Down Expand Up @@ -70,8 +70,8 @@ security:
remember_me:
key: "changeme"
lifetime: 31536000
path: /
domain: ~
path: /
domain: ~
logout:
path: admin_logout
target: /admin
Expand All @@ -83,15 +83,15 @@ security:
provider: frontend_db
form_login:
login_path: /auth
check_path: /auth/login_check
check_path: /auth
username_parameter: email
password_parameter: password
success_handler: newscoop_newscoop.security.authentication.frontend.success_handler
remember_me:
key: "changeme"
lifetime: 31536000
path: /
domain: ~
path: /
domain: ~
logout:
path: /auth/logout
target: /
Expand Down
45 changes: 20 additions & 25 deletions newscoop/application/controllers/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* @license http://www.gnu.org/licenses/gpl-3.0.txt
*/

/**
*/
use Symfony\Component\Security\Core\SecurityContext;

class AuthController extends Zend_Controller_Action
{
/** @var Zend_Auth */
Expand All @@ -25,37 +25,32 @@ public function indexAction()
}

$translator = Zend_Registry::get('container')->getService('translator');

$form = new Application_Form_Login();

$request = $this->getRequest();
if ($request->isPost() && $form->isValid($request->getPost())) {
$values = $form->getValues();
$adapter = $this->_helper->service('auth.adapter');
$adapter->setEmail($values['email'])->setPassword($values['password']);
$result = $this->auth->authenticate($adapter);

if ($result->getCode() == Zend_Auth_Result::SUCCESS) {
$expire = null;
if (!empty($values['remember_me'])) {
// set expire to 10 years in the future
$expire = time() + (10 * 365 * 24 * 60 * 60);
}

setcookie('NO_CACHE', '1', $expire, '/', '.'.$this->extractDomain($_SERVER['HTTP_HOST']));
if (isset($values['_target_path'])) {
$this->_helper->redirector->gotoUrl($values['_target_path']);
}

$this->_helper->redirector('index', 'dashboard');
} else {
$form->addError($translator->trans("Invalid credentials"));
}
if ($authenticationException = $this->getLastAuthenticationError()) {
$form->addError($translator->trans($authenticationException->getMessage()));
}

$this->view->form = $form;
}

private function getLastAuthenticationError()
{
$request = \Zend_Registry::get('container')->getService('request');
$session = $request->getSession();
$authenticationException = null;

if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
$authenticationException = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
} elseif ($session !== null && $session->has(SecurityContext::AUTHENTICATION_ERROR)) {
$authenticationException = $session->get(SecurityContext::AUTHENTICATION_ERROR);
$session->remove(SecurityContext::AUTHENTICATION_ERROR);
}

return $authenticationException;
}

public function logoutAction()
{
if ($this->auth->hasIdentity()) {
Expand Down
22 changes: 11 additions & 11 deletions newscoop/application/controllers/DashboardController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@

use Newscoop\Entity\User;
use Newscoop\Topic\SaveUserTopicsCommand;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Filesystem\Filesystem;
use Newscoop\Exception\AuthenticationException;

/**
* User dashboard controller
*/
class DashboardController extends Zend_Controller_Action
{
/** @var Newscoop\Services\UserService */
private $service;
private $userService;

/** @var Newscoop\Entity\User */
private $user;
Expand All @@ -24,9 +24,13 @@ public function init()
{
$GLOBALS['controller'] = $this;
$this->_helper->layout->disableLayout();
$this->userService = $this->_helper->service('user');

$this->service = $this->_helper->service('user');
$this->user = $this->service->getCurrentUser();
try {
$this->user = $this->userService->getCurrentUser();
} catch (AuthenticationException $e) {
$this->_helper->redirector('index', 'auth');
}

$this->_helper->contextSwitch()
->addActionContext('update-topics', 'json')
Expand All @@ -35,10 +39,6 @@ public function init()

public function preDispatch()
{
if (empty($this->user)) {
$this->_helper->redirector('index', 'auth');
}

if ($this->user->isPending()) {
$this->_helper->redirector('confirm', 'register');
}
Expand All @@ -62,8 +62,8 @@ public function indexAction()
$imageInfo = array_pop($form->image->getFileInfo());
$values['image'] = $this->_helper->service('image')->save($imageInfo);
}
//TODO add event to subscribe for newsletter
$this->service->save($values, $this->user);

$this->userService->save($values, $this->user);
$this->_helper->flashMessenger->addMessage($translator->trans('Profile saved.', array(), 'users'));
$this->_helper->redirector('index');
} catch (\InvalidArgumentException $e) {
Expand Down
12 changes: 6 additions & 6 deletions newscoop/application/controllers/RegisterController.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,12 @@ public function confirmAction()
$translator = \Zend_Registry::get('container')->getService('translator');
$session = \Zend_Registry::get('container')->getService('session');
$user = $this->getAuthUser();
$social = $this->_getParam('social');
$form = $this->_helper->form('confirm');
$form->setMethod('POST');
$form->setDefaults(array(
'first_name' => $user->getFirstName(),
'last_name' => $user->getLastName(),
'username' => $this->_helper->service('user')
->generateUsername($user->getFirstName(), $user->getLastName()),
'username' => $this->_helper->service('user')->generateUsername($user->getFirstName(), $user->getLastName()),
));

if ($this->auth->hasIdentity()) {
Expand All @@ -102,21 +100,23 @@ public function confirmAction()
$request = $this->getRequest();
if ($request->isPost() && $form->isValid($request->getPost())) {
$values = $form->getValues();

try {
if (!empty($values['image'])) {
$imageInfo = array_pop($form->image->getFileInfo());
$values['image'] = $this->_helper->service('image')->save($imageInfo);
}

$this->_helper->service('user')->savePending($values, $user);
$this->_helper->service('dispatcher')->dispatch('user.register', new GenericEvent($this, array(
'user' => $user,
)));
$this->_helper->service('user.token')->invalidateTokens($user, 'email.confirm');

$auth = \Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$this->_helper->flashMessenger('User registered successfully.');
if (isset($values['_target_path']) && !empty($values['_target_path'])) {
$this->_helper->redirector->gotoUrl($values['_target_path']);
}
$this->_helper->redirector(null, null, 'default');
} else {
$adapter = $this->_helper->service('auth.adapter');
Expand All @@ -138,7 +138,7 @@ public function confirmAction()

$this->view->form = $form;
$this->view->user = new \MetaUser($user);
$this->view->social = $social ?: false;
$this->view->social = $this->_getParam('social') ?: false;
}

public function generateUsernameAction()
Expand Down
19 changes: 2 additions & 17 deletions newscoop/application/plugins/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,23 +70,8 @@ public function preDispatch(Zend_Controller_Request_Abstract $request)
*/
private function setSessionLifetime()
{
$auth = Zend_Auth::getInstance();
$session = new Zend_Session_Namespace($auth->getStorage()->getNamespace());
$session = new Zend_Session_Namespace(Zend_Auth::getInstance()->getStorage()->getNamespace());
$preferencesService = \Zend_Registry::get('container')->getService('system_preferences_service');
$seconds = $preferencesService->SiteSessionLifeTime;

$gc_works = ini_get('session.gc_probability');
if (!empty($gc_works)) {
$max_seconds = 0 + ini_get('session.gc_maxlifetime');
if (!empty($max_seconds)) {
if ($seconds > $max_seconds) {
$seconds = $max_seconds;
}
}
}

if ($seconds > 0) {
$session->setExpirationSeconds($seconds);
}
$session->setExpirationSeconds($preferencesService->SiteSessionLifeTime);
}
}
52 changes: 51 additions & 1 deletion newscoop/library/Newscoop/Entity/Repository/UserRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,16 @@
use Newscoop\User\UserCriteria;
use Newscoop\ListResult;
use Newscoop\Search\RepositoryInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Doctrine\ORM\NoResultException;

/**
* User repository
*/
class UserRepository extends EntityRepository implements RepositoryInterface
class UserRepository extends EntityRepository implements RepositoryInterface, UserProviderInterface
{
/** @var array */
protected $setters = array(
Expand Down Expand Up @@ -544,6 +549,7 @@ public function delete(User $user)
$user->setEmail(null);
$user->setFirstName(null);
$user->setLastName(null);
$user->setUsername($user->getUsername().'__deleted__'.date('his'));
$this->removeAttributes($user);
}

Expand Down Expand Up @@ -789,6 +795,50 @@ public function getListByCriteria(UserCriteria $criteria, $results = true)
return $list;
}

public function loadUserByUsername($usernameOrEmail)
{
$qb = $this->createQueryBuilder('u');
$qb->andWhere($qb->expr()->orX("(u.username = :usernameOrEmail)", "(u.email = :usernameOrEmail)"))
->setParameter('usernameOrEmail', $usernameOrEmail);

try {
// The Query::getSingleResult() method throws an exception if there is no record matching the criteria.
$user = $qb->getQuery()->getSingleResult();
} catch (NoResultException $e) {
ladybug_dump_die($e);
$message = sprintf('Unable to find an user identified by "%s".', $usernameOrEmail);

throw new UsernameNotFoundException($message, 0, $e);
}

return $user;
}

/**
* [refreshUser description]
* @param UserInterface $user [description]
* @return [type] [description]
*/
public function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.',
$class
)
);
}

return $this->find($user->getId());
}

public function supportsClass($class)
{
return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
}

/**
* Add name first letter where condition to query builder
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public function findByCriteria(ListCriteria $criteria)
return $this->getRepository()->getListByCriteria($criteria);
}


/**
* Count by given criteria
*
Expand All @@ -80,4 +80,4 @@ protected function getRepository()
{
return $this->em->getRepository('Newscoop\CommunityTickerBundle\Entity\CommunityTickerEvent');
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class SecurityController extends Controller
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,17 +65,6 @@ public function indexAction(Request $request)
$translator = $this->get('translator');

$sp_session_lifetime = 0 + $preferencesService->SiteSessionLifeTime;
$php_ini_max_seconds = 0;
$php_ini_gc_works = ini_get('session.gc_probability');

if (!empty($php_ini_gc_works)) {
$php_ini_max_seconds = 0 + ini_get('session.gc_maxlifetime');
if (!empty($php_ini_max_seconds)) {
if ($sp_session_lifetime > $php_ini_max_seconds) {
$sp_session_lifetime = $php_ini_max_seconds;
}
}
}

$upload_min_filesize = $this->formatBytes(
min(
Expand Down Expand Up @@ -295,7 +284,6 @@ public function indexAction(Request $request)

return array(
'form' => $form->createView(),
'php_ini_max_seconds' => $php_ini_max_seconds,
'upload_min_filesize' => $upload_min_filesize,
'hasManagePermission' => $hasManagePermission,
'mysql_client_command_path' => $mysql_client_command_path,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ newscoop:
allowrecovery: null
secretkey: null
sessionlifetime: null
sessionlifetimemsg: null
separator: null
captcha: null
maxupload: null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,6 @@ table.cron-jobs td:nth-child(2) {
</dt>
<dd>
{{ form_row(form.session_lifetime, {'attr' : {'class' : 'input_text'}}) }}
{% if php_ini_max_seconds %}
<span style="margin-top:8px;"><= {{ php_ini_max_seconds }}, {{ 'newscoop.preferences.label.sessionlifetimemsg'|trans }}
</span>
{% endif %}
</dd>
<dt>
<label>{{ 'newscoop.preferences.label.separator'|trans }} <small id="separator">(?)</small></label>
Expand Down
Loading

0 comments on commit 6967786

Please sign in to comment.