Yii2 stop user being logged out when browser is closed - php

I am having some issues with users being logged out when they close the browser. I tried to set enableAutoLogin to true but then the user never seems to get logged out even when setting authTimeout and absoluteAuthTimeout. Does anyone know how to make it so it doesnt log them out when they close the browser but logs them out after 10 hours?
'user' => [
'class' => \common\models\WebUser::class,
'identityClass' => 'common\models\User',
'authTimeout' => 36000,
//'enableAutoLogin' => true,
'absoluteAuthTimeout' => 36000,
'enableSession' =>true,
],
'session' => [
'class' => 'yii\web\Session',
'timeout' => 36000, // 2 weeks=
'useCookies' => true,
],

For anyone else who has this issue, the solution when using enableAutoLogin is true is to set the duration which is the second parameter when calling the login funciton
public function login()
{
if ($this->validate())
{
return Yii::$app->user->login($this->getUser(), 36000);
}
return false;
}

Related

Yii2 login not working properly on remote server

I have a login problem on the remote server. I followed the error and discovered that the user is logged in
this returns true in the LoginForm and at this level, I have the user
Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0)
However, at the controller when the login action receives true and redirects to the profile page, the latter shows null for
var_dump(\Yii::$app->user->identity);
I tried using DbSession, but the table also has null for the user_id.
Can anyone please help me to solve this issue, I have been working on it for the past 3 days.
Here are some samples of my code
public function actionLogin() {
$login = new LoginForm('app');
if ($login->load(Yii::$app->request->post()) && $login->login()) {
$this->redirect(['/profile']);
}
return $this->render('login', [
'login' => $login,
]);
}
profile controller
public function actionIndex() {
var_dump(\Yii::$app->user->identity); // here i get null
die();
$dashboard = new Dashboard();
return $this->render('index', [
'dashboard' => $dashboard,
]);
}
common main conf
'session' =>
[
'class' => 'yii\web\DbSession',
],
frontend conf
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
],
'session' => [
'name' => 'app-frontend',
],

yii2 redirect any page to login page after session timeout

i wanna ask about redirect any page to login page after session timeout in yii2, i try to do this
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
'returnUrl' => 'index.php?r=site/login',
'identityCookie' => [
'name' => '_backendIdentity',
],
],
'session' => [
'name' => 'BACKENDSESSID',
'savePath' => __DIR__ . '/../runtime',
],
but it return to login page when i'm at index.php page, if i go to another action and the session timeout it will return
PHP Notice – yii\base\ErrorException
Trying to get property of non-object
1. in /var/www/html/spmoa/backend/controllers/StaffController.php at line 174
165166167168169170171172173174175176177178179180181182183
public function actionMyProfile() {
error here -> $id = Yii::$app->user->identity->staff->id;
$model = $this->findModel($id);
Please help me
Try with behaviors
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['youraction'],
'allow' => true,
'roles' => ['#'], // you can use matchCallback to create more powerful check
],
],
],
];`enter code here`
}
Please use session and timeout as below in your config/main.php file:
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'authTimeout' => 3600*4, // auth expire 4 hours
],
'session' => [
'class' => 'yii\web\Session',
'cookieParams' => ['httponly' => true, 'lifetime' => 3600*4],
'timeout' => 3600*4, //session expire 4 hours
'useCookies' => true,
],
],
//and in this beforeRequest give actions that can be accessed by guest user.
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'allow' => true,
'actions' => ['login', 'error', 'forgotpassword', 'resetpassword'],
],
[
'allow' => true,
'roles' => ['#'],
],
],
],
You can check condition Before action : If user is logged in or not :
public function beforeAction($action){
if (Yii::$app->user->isGuest){
return $this->redirect(['site/login'])->send(); // login path
}
}

How to redirect "Access denied" to login page in Silex

This is my firewall code
$app['security.firewalls']=[
'secured'=>[
'pattern' => '/',
'anonymous' => true,
'http'=>true,
'form' => array('login_path' => '/login', 'check_path' => '/secured/login_check'),
'logout' => array('logout_path' => '/secured/logout', 'invalidate_session' => true),
'users'=>$users
]
];
$app['security.access_rules']=[
["^/admin", "ROLE_ADMIN"]
];
When users access admin page without role admin, how to redirect them to login page?
I have test with no access rules in admin controller code:
if($app['security.authorization_checker']->isGranted('ROLE_ADMIN')){
// ...
// ...
// ...
}
else return $app->redirect($app->url('login'));
But the problem when I use this method is that it will redirect to homepage instead of previous page. How can I make login page to redirect to previous page instead of homepage after successful login check?
Try to add always_use_default_target_path and use_referer parameters to security config:
$app['security.firewalls']=[
'secured'=>[
...
'form' => array(
'login_path' => '/login',
'check_path' => '/secured/login_check',
'always_use_default_target_path' => false,
'use_referer' => true
),
...
]
];
Why do you use 2 entry points for login? http and form?

I can't save user identity in yii2

I created a module in yii2 under api/modules/v1 folder, the problem is when I request:
Yii::$app->user->login($user, 3600);
The identity got saved temporary until I refresh the page or I request another url, When I reviewed the log file, I found this :
User '1' logged in from ::1. Session not enabled.
Also I tried to add :
'enableAutoLogin' => true,
'enableSession' => true,
user component configuration :
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => true,
'enableSession' => true,
'identityCookie' => [
'name' => '_APIUser', // unique for backend
'path' => '/api/web/v1' // correct path for the backend app.
]
],
'session' => [
'name' => '_apiSessionId', // unique for frontend
'savePath' => __DIR__ . '/../runtime', // a temporary folder on frontend
],
But the same problem occurred.
Have you model common\models\User implements "login" method? If so, login with this code
Yii::$app->user->identity->login($user, 3600);
it seems like you are configuring 'common\config\main' as you have indicated frontend and backend session details in the same config.
Leave the common\config\main blank and you have to configure your backend\config\main and frontend\config\main separately. Your login code should work.

Auto logout in yii

How to do auto logout after some minute if the user is idle
I am using yii framework.
I can set logout time under user component in main.php
but the question is how to check the user is idle?
if(isset(Yii::app()->request->cookies['lastpageview']) && (time()-(int)Yii::app()->request->cookies['lastpageview']->value > 3600))
{
//logout
}
else
{
Yii::app()->request->cookies['lastpageview'] = new CHttpCookie('lastpageview', time());
}
where 3600 is the max number or seconds allowed
For Yii 1.xx CWebUser has property authTimeout.
From off documentation:
authTimeout - timeout in seconds after which user is logged out if
inactive.
Set it propety into main config:
...
'components' => array(
....
'user' => array(
'authTimeout' => 60*60*5,
),
....
),
...
You can use CDbHttpSession component to make it work:
'components' => array(
'session' => array(
'class' => 'CDbHttpSession',
'timeout' => 1,
),
),
'user' => [
'identityClass' => 'app\models\User',
//'enableAutoLogin' => true,
'enableSession' => true,
'authTimeout' => 900,
],
its working fine to me!(YII 2.0)
time out session after 15 min if request is come after 15 min then auto redirect to site/login page.

Categories