yii2 - Keep user logged in when website is idle - yii2

The user appears to be automatically logged out if the website has been idle for about an hour. Is it possible that they are not logged out for at least a month.
I've tried changing the parameters.
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
'authTimeout' => 3600*24*30,
],
'session'=>[
'class' => 'yii\web\Session',
'timeout' => 3600*24*30,
],
I've tried session php.ini parameters:
And I've tried setting the login parameters:
Yii::$app->user->login($this->getUserById($userId), 3600*24*30);

Related

YII2 - In test, send email nowhere

I have a test and live environment. In test, I don't ever want to send the mailer mails. I have the mailer setup as a component in web.php like this
'mailer' => [
'class' => 'nickcv\mandrill\Mailer',
'apikey' => 'xxxxxxxxxxxxxxxxxxxx',
'useMandrillTemplates' => true,
'templateLanguage' => nickcv\mandrill\Mailer::LANGUAGE_HANDLEBARS,
],
Is there a way to set up the mailer component so it sends nowhere?
Thanks in advance.
Because mailer you are using extends yii\mail\BaseMailer you can simply set its $useFileTransport to true and the mail will be saved in file instead.
'mailer' => [
'class' => 'nickcv\mandrill\Mailer',
'apikey' => 'xxxxxxxxxxxxxxxxxxxx',
'useMandrillTemplates' => true,
'templateLanguage' => nickcv\mandrill\Mailer::LANGUAGE_HANDLEBARS,
'useFileTransport' => true,
],
Another option is creating a mock of mailer and using it instead of real mailer.
If you use codeception framework and its Yii2 module, the mailer component should be replaced automatically if you have email part enabled in codeception configs.
======== Configure Apache to send the emails from localhost code ========
Changes for C:\xampp\php\php.ini file:
search for [mail function]:
[mail function]
SMTP=localhost to SMTP=smtp.gmail.com
smtp_port=587
sendmail_from=me#example.com to sendmail_from=your email address
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
mail.add_x_header=Off
mail.log = syslog
Changes for C:\xampp\sendmail\sendmail.ini:
search for [sendmail]:
smtp_server=smtp.gmail.com
smtp_port=587
smtp_ssl=auto
error_logfile=error.log
debug_logfile=debug.log
auth_username=same as "sendmail_from" in php.ini file
auth_password=generated password for the email account
force_sender= same as "auth_username" in this file
=========== mailer component in Yii application ===============
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'smtp.gmail.com',
'username' => 'your email address (for testing on localhost use same as in ini files)',
'password' => 'generated password',
'port' => 587,
'encryption' => 'tls',
],
], //end of mailer
Actually, I think it would be nice to receive somewhere your test emails for debugging and QA.
Personally, in dev environment, I would recommend setting up and configuring mailhog
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '#common/mail',
'transport' => [
'class' => 'Swift_SmtpTransport',
'host' => 'localhost',
'port' => '1025',
],
],
It is straightforward to install following the steps described here: https://github.com/mailhog/MailHog
You can then go to http://localhost:8025 and see your inbox

Yii2 Read Write splitting couldn't connect slave server in master slave configuration

Have done Master Slave configuration as per official Yii2 documentation. Below is actual configuration look like,
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=1.1.1.1;dbname=master_db',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'enableSchemaCache' => true,
'schemaCacheDuration' => 10,
'schemaCache' => 'cache',
'slaveConfig' => [
'username' => 'slave_user',
'password' => 'slave_password',
'charset' => 'utf8',
'attributes' => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
],
'enableSchemaCache' => true,
'schemaCacheDuration' => 10,
'schemaCache' => 'cache',
],
'slaves' => [
['dsn' => 'mysql:host=2.2.2.2;dbname=slave_db']
],
],
It always connect master database even if slave server is up and reachable.
Surprisingly replacing current master config with slave one works, moreover if try to connect slave database from command line it get connected in a moment but unable to achieve same with above configuration.
Wondering if there is any parameters missing in configuration or any other way to get things working like ideal read write splitting?
issue was resolved by adding connection class in the slaveConfig,
'class' => 'yii\db\Connection'

How do I solve it this error HTTP 400 - Unable to verify your data submission in Yii2?

My Yii 2 application was progressing well until I received an unusual error bout a bad HTTP request.
HTTP 400 Unable to verify your data Submission.
I have looked it up and much of the literature indicates the cause being due to a CSRF issue. However, the CSRF components are all in place within the HTML head section and the hidden field is submitting the correct token.
Additional Info
Yii version = 2.0.12 App Basic
PHP version = 5.6
OS = Ubuntu
I have disabled all the security firmware of the host but I still get the error. Please help the site is in Prod already and I can not find how to solve this many thanks in advance.
web/config/main.php
$config = [
'components' => [
'session' => ['class' => 'yii\web\DbSession'],
'request' => [
'cookieValidationKey' => 'AAOSL2no3kbkJwRA4CNwDuB5g5T5_58t',
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => ['errorAction' => 'site/error'],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
],
'params' => $params,
];
if (YII_ENV_DEV) {
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
//'allowedIPs' => ['127.0.0.1', '::1'],
];
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}
return $config;
As per Change Logs, BugFix and Enhancement related to CSRF cookie.
2.0.13 November 03, 2017 updates include
Bug #14542: Ensured only ASCII characters are in CSRF cookie value since binary data causes issues with ModSecurity and some browsers (samdark)
Enh #14087: Added yii\web\View::registerCsrfMetaTags() method that registers CSRF tags dynamically ensuring that caching doesn't interfere (RobinKamps).
2.0.14 February 18, 2018 updates include
Bug #15317: Regenerate CSRF token if an empty value is given
Enh #15496: (CVE-2018-6009): CSRF token is now regenerated on changing identity (samdark, rhertogh)(sammousa)
So update your framework to the latest version 2.0.14 use composer update via terminal inside your project root, once updated make sure you have the
<?= Html::csrfMetaTags () ?>
inside the <head> tag of the layout file you are using either main.php or any other custom name.
If still persist you can disable it for the specific action inside the beforeAction
public function beforeAction($action)
{
if ($action->id == 'action-name') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
or for a specific controller by adding
public $enableCsrfValidation = false;
Add <?= Html::csrfMetaTags() ?> in your view, or add in layout(main.php)

Add multiple tables for login in web.config

I developing a site with two different registrations, and I have 2 different table, One is user and 2nd is admin.In the web.config how to I can set both tables in the components section. For this I am tried this my code is that :-
'user' => [
'identityClass' => 'app\models\Users',
'enableAutoLogin' => true,
],
'admin' => [
//'class' => 'yii\web\User'
'identityClass' => 'app\models\adminUser',
'enableAutoLogin' => true,
],
But when run run my application its showing error message erro message is that :-
Invalid Configuration – yii\base\InvalidConfigException
I also tried this multiple user identity in config Yii2 when I add class its showing blank page.
Thank you

Yii 2 - Exception error with message 'Login Required'

An Error occurred while handling another error:
exception 'yii\web\ForbiddenHttpException' with message 'Login
Required' in
C:\wamp\www\k\kometonline\vendor\yiisoft\yii2\web\User.php:431
Am getting this error after installing RBAC in backend admin login page (site.com/backend/web/site/login). Whats the main cause of this problem. I don't know what code to post. Please comment below If you need any code. Thanks in advance.
I encountered the same error while installing RBAC in backend admin login page while following this tutorial:
RBAC Super Simple with Admin and User
You may try doing the changes you made at the frontend login SiteController and see if works. The difference between these two SiteControllers is that the frontend already uses access rules in its behavior method.
From there you can compare the SiteControllers at backend and frontend and see what makes it work. In my case I simply added one line
'only' => ['logout'],
just below
'class' => AccessControl::className(),
and it worked!
While I know the solution worked for the OP and is a few years old, I wanted to post how I solved this for myself, in the hope of offering an alternate solution.
In my case, I specified the following actions
'rules' => [
[
'actions' => ['logout', 'index',],
'allow' => true,
'roles' => ['#'],
],
This specified that the index and logout was protected by a password, The
*"'roles' => ['#']"*
say that only authenticated users can invoke these actions.
Therefore, when my application restarted, it tried to direct to the login action and error presented. I solved this by specifying a rule for non logged in users (a.k.a guests) by specifying the role
*"'roles' => ['?']"*
My behavior method therefore changed to
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['logout', 'index',],
'allow' => true,
'roles' => ['#'],
],
[
'actions' => ['login'],
'allow' => true,
'roles' => ['?'],
],
],
],
];
}