I am creating an web application in Yii . I was trying to do a sessiontimeout, if a user is idle for 30 minutes.After that he should login again.. but this is not working. I am using CHttpSession. However if i give CDbHttpSession instead of CHttpSession this is working fine.
this is my code
'user' => array(
'class' => 'WebUser',
'loginUrl' => array('site/loginaccount'),
'allowAutoLogin' => true,
),
// uncomment the following to enable URLs in path-format
'session' => array(
'class'=>'CHttpSession',
'timeout'=>$params['session_timeout'],
'autoStart'=>true,
),
Is there anything else to make this work for CHttpSession ? Due to some reasons i cannot use CDbHttpSession in my web application .
If you want that the user is sign out automatically after 30 minutes try:
'user' => array(
'class' => 'WebUser',
'loginUrl' => array('site/loginaccount'),
'allowAutoLogin' => true,
'authTimeout' => 1800
),
protected/config/main.php : (define the session timeout)
$sessionTimeout = 5; // 5 secondes
return array(
'params'=>array(
'session_timeout'=> $sessionTimeout,
);
'components'=>array(
'session' => array(
'class' => 'CDbHttpSession',
'timeout' => $sessionTimeout,
),
),
);
protected/views/layout/main.php : (define the refresh)
<html>
<head>
<?php if (!Yii::app()->user->isGuest) {?>
<meta http-equiv="refresh" content="<?php echo Yii::app()->params['session_timeout'];?>;"/>
<?php }?>
</head>
<body>
…
</body>
</html>
I've read the source code of the CHttpSession. It is a wrap of the PHP Session. So, the mechanism of CHttpSession is the same with the PHP Session.
public function setTimeout($value)
{
ini_set('session.gc_maxlifetime',$value);
}
the above is the code of timeout setter. it is just the setting of ini settings of the PHP. And according to the PHP documentation of session, after the maxlifetime, the session is just "potentially cleaned up", not for sure.
And the probability of it can be set by session.gc_probability. the default value is 1, which means 1%. So, you can set it to 100, make the garbage collection process run every time the script is run.
change your setting to
'session' => array(
'class'=>'CHttpSession',
'timeout'=>$params['session_timeout'],
'autoStart'=>true,
'gCProbability' => 100,
),
hope it helps.
return array('components'=>array(
'session'=>array(
'timeout' => 1800
),
),
);
Related
Using Yii2 framework:
The code below creates an endless loop.
Can anyone please explain how I make the session data persist on redirect ?
I have checked and there is not data being transferred, but the session data is set inside searchuser correctly.
public function actionSearchUser()
{
$session = \Yii::$app->session;
$session->open();
$session->set('admin.currentuser.id', "This worked out ok");
return $this->redirect(['site/modify-user']);
}
public function actionModifyUser()
{
$session = \Yii::$app->session;
$session->open();
if( !($session->has('admin.currentuser.id')) )
{
return $this->redirect(['site/search-user']);
}
else return $this->render('modifyUser');
}
And here is where I setup my session:
'session'=>array(
'class' => 'yii\web\Session',
'name' => 'SESSIONNAME',
'timeout' => 86400,
'savePath' => '/path/to/sessions',
'useCookies' => true,
'cookieParams' => array(
'lifetime' => 86400,
'path' => '/',
'domain' => 'localhost',
),
),
My problem was the domain (I know, I'm stupid).
I have a custom domain (n099y.local) so I needed to change the cookie domain from localhost to n099y.local and everything was fine.
It was showing all the correct session data on the page until I went to another page when the data was again missing because the cookie domain did not match the domain I was on.
I have enabled CSRF Validation in Yii:
'enableCsrfValidation' => true,
Everything works as expected however I'd like for the session cookie to have the secure flag turned on.
With other cookies you can set the secure flag in the config:
'session'=>array(
'cookieParams' => array(
'httponly'=>true,
'secure' => true,
),
),
How do you do this for the YII_CSRF_TOKEN?
Add the following to your config:
'components' => array(
'request' => array(
'csrfCookie'=>array(
'secure'=>true,
),
),
),
You can't do that with the built in CHttpRequest component. You will need to derive from it and override the createCsrfCookie() to create a secure cookie as follows:
class CustomHttpRequest extends CHttpRequest {
protected function createCsrfCookie()
{
$cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
$cookie->secure = true; //Here is where you make your cookie secure
if(is_array($this->csrfCookie))
{
foreach($this->csrfCookie as $name=>$value)
$cookie->$name=$value;
}
return $cookie;
}
}
In your components configuration, specify your custom implementation:
'components'=>array(
....,
'request' => array(
'class' => 'CustomHttpRequest',
'enableCsrfValidation' => true,
),
IMPORTANT: For a new CSRF token to be generated, you will need to start a new browser session. Also, you will need to use HTTPS for a secure cookie to be in effect.
Delete all cookies for your development URI, or start a private session (in Chrome or Firefox) to start a new session.
I got problem with Zend 2 session
When I 'quickly' double click 'Enter' in _POST form ( twice submit form before first respond) session is destroyed. When I submit 'in normal speed' all is OK.
My session configuration is exact copy of this http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
only difference is
'session' => array(
'config' => array(
'class' => 'Zend\Session\Config\SessionConfig',
'options' => array(
'name' => 'myapp',
'remember_me_seconds' => 3600, //60 min session
'use_cookies' => true,
// 'cookie_httponly' => true, -> not working with Zfc-user subdomain
'cookie_domain'=>'domain.com',
),
),
'storage' => 'Zend\Session\Storage\SessionArrayStorage',
'validators' => array(
'Zend\Session\Validator\RemoteAddr',
'Zend\Session\Validator\HttpUserAgent',
),
),
In controler I have:
const NAMESPACE_REGORG = 'initialized';
protected $_sessionRegContainer;
public function packageAction() {
//check if user login and redirect
if ($this->zfcUserAuthentication()->hasIdentity()) {
//some staff here
}
//save value to session
$package = $this->getEvent()->getRouteMatch()->getParam('id');
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
$this->_sessionRegContainer->package = $package;
return $this->redirect()->toRoute(static::ROUTE_LOGIN);
}
public function loginAction() {
//restore session
$this->_sessionRegContainer = new Container(static::NAMESPACE_REGORG);
//create form staff.. if submited by double click session is loosing
//value of $this->_sessionRegContainer->package
}
Page use Doctrine 2 ORM , Zfc-user module for authentication and sub-domain for all Zend 2 related content - main domain.com is static html.
It is worth to mention that when I use simple new Container() session with out all setup from Zend page - session work fine with 'double click' but zfc-user stop to work :(
Any idea why session is destroyed? Any help will be appreciated
I sorted it by removing
$session->start();
$session->rememberMe();
from Zend 2 exmple setup -> http://framework.zend.com/manual/2.1/en/modules/zend.session.manager.html
Double click session destroy ended (fixed).
ps. It look like they already remove rememberMe() from exmple.
Thanks for all help!
Explanation:
Attempting to use this OAuth2 Plugin for CakePHP:
https://github.com/thomseddon/cakephp-oauth-server
Have followed the instructions, and am now going to this URL:
http://mysite/oauth/login?response_type=code&client_id=NGYcZDRjODcxYzFkY2Rk&
redirect_url=http%3A%2F%2Fwww.return_url.com
(We had made a client in the database with the same info he used in the example)
It brings up a log-in box for Email and Password, but fails authentication every time. I believe it's failing because by the time it gets to Cake's FormAuthenticate->authenticate() method, the settings have reverted to 'username'=>'username' and 'passwordHasher'=>'Simple'.
If we add these lines to the FormAuthenticate (above $fields = ...):
$this->settings['fields']['username'] = 'email';
$this->settings['passwordHasher'] = 'Blowfish';
Then the log-in works successfully.
Things We've tried:
Putting this in our AppController, the OAuthAppController, the OAuthController (all in beforeFilter):
$this->OAuth->authenticate = array(
'userModel' => 'Members',
'fields' => array(
'username' => 'email'
)
);
We've tried changing it to the new format like 2.3 in all of those places, as well as in the initial $components array in my AppModel:
$this->OAuth->authenticate = array(
'Form' => array(
'passwordHasher' => 'Blowfish',
'fields' => array('username'=>'email', 'password'=>'password'),
)
);
Closing:
At this point, I'm looking for any way (other than modifying the actual CakePHP core) to get it to be able to log-in with email instead of username (and hopefully that will solve the same issue with having it revert from Blowfish to Simple as well.
We've already tried heavily modifying the OAuth Plugin (to no avail) and aren't opposed to trying that again, but we can't figure out what to change.
Instead of using this in the OAuthController:
$this->OAuth->authenticate = array(
'Form' => array(
'passwordHasher' => 'Blowfish',
'fields' => array('username'=>'email', 'password'=>'password'),
)
);
Change it to this (notice removal of the "O" so it calls the regular "Auth"):
$this->Auth->authenticate = array(
'Form' => array(
'passwordHasher' => 'Blowfish',
'fields' => array('username'=>'email', 'password'=>'password'),
)
);
Or, take it a step further, and set your $this->OAuth->authenticate array in your own AppController, then, in the OAuthController do this (instead of the above):
$this->Auth->authenticate = $this->OAuth->authenticate;
I have a site developed in cakephp. I want to cache a query. I have read the documentation and I have in my bootstrap.php this:
Cache::config('default', array('engine' => 'File'));
Cache::config('short', array(
'engine' => 'File',
'duration' => '+1 hours',
'path' => CACHE,
'prefix' => 'cake_short_'
));
// long
Cache::config('long', array(
'engine' => 'File',
'duration' => '+1 week',
'probability' => 100,
'path' => CACHE . 'long' . DS,
));
My controller to store the query is this:
public function test_view () {
$product_general = Cache::read('product_general_query', 'longterm');
if (!$product_general) {
echo("test");
$product_general = $this->Product->query('SELECT DISTINCT * FROM products');
Cache::write('product_general_query', $product_general, 'longterm');
}
$this->set('product_general', $product_general);
}
Everytime that I enter into the page it print me "test" because doesn't find the query into the cache. Where is the problem? Have I miss something?
You named your cache configuration 'long' inside your core.php but using configuration 'longterm' inside your action
Also, If you have enabled debugging (e.g. debug set to 1 or 2 in your core.conf), the cache duration may be set to 10 seconds automatically. Not sure if this will apply to your own cache definitions as well though