Redirect user to previous page after auth (yii2) - yii2

I have the main controller from which the others are inherited. Code is something like this
public function init()
{
$this->on('beforeAction', function ($event) {
...
if (Yii::$app->getUser()->isGuest) {
$request = Yii::$app->getRequest();
// dont remember login page or ajax-request
if (!($request->getIsAjax() || strpos($request->getUrl(), 'login') !== false)) {
Yii::$app->getUser()->setReturnUrl($request->getUrl());
}
}
}
...
});
}
It works perfectly for all pages, except the page with captcha. All the pages with captcha are redirected to something like this - /captcha/?v=xxxxxxxxxxxxxx
If the object is logged Yii::$app->getRequest() then I see that for pages with captcha it is used twice. For the first time the object is corect, and the second time I see the object with captcha.
How can I solve this problem with yii? Is there a chance not to track the request for captcha?

The default (generated) controller uses something like this:
public function actions()
{
return [
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
],
];
}
Does your controller contain something like this?
This means that there is an action "captcha" that is used for displaying captchas (it returns the image). When you have a page displaying a captcha the image is called after the page you want to return to. Therefore that latest page visited is the one with the captcha.
I think you have to filter out this action.
Another possibility could be to use the default $controller->goBack() method. I think this handles registering of the returnUrl by default.
Reference: Class yii\web\Controller

Guid security authorization
Use Access Control Filter(ACF) in your controller.
use yii\web\Controller;
use yii\filters\AccessControl;
class SiteController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['login', 'logout', 'signup'],
'rules' => [
[
'allow' => true,
'actions' => ['login', 'signup'],
'roles' => ['?'],
],
[
'allow' => true,
'actions' => ['logout'],
'roles' => ['#'],
],
],
],
];
}
// ...
}

Related

Yii2 : ajax post request always redirect to login page

I'm trying to send data using ajax POST request but I'm always redirected to login page even if I authorize the method to anonymous users (['actions' => ['update', 'test'], 'allow' => true]). When I test with a GET request there is no problem.
My controller :
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
['actions' => ['update', 'test'], 'allow' => true],
],
],
];
}
public function actionTest() {
Yii::$app->request->enableCsrfValidation = false;
echo 'ok';
}
I use Postman to test requests
The solution you used is not a solution actually, its like if you cant open the lock with a key just remove the lock.
Mostly you get the 400 Bad Request if you are making an Ajax Post request without sending the CSRF parameters, I never faced the problem like being redirected to the login page.
But if your problem is resolved by disabling the CSRF Validation then you should follow this method while making any ajax requests.
In your config, you define the csrf parameter name using csrfParamin the request component like this
'request' => [
'csrfParam' => '_csrf-app',
],
This can be different for you if it is already defined.
You have to send this param _csrf-app with the csrf value in the ajax request along with your post data. and for retrieving the value for the csrf you can use javascript yii.getCsrfToken() method, or Yii::$app->request->csrfToken if in view via php.
See this example call you can hardcode the name of the param _csrf-app or use Yii::$app->request->csrfParam if your script is inside the view file.
$.ajax({
url:'/add',
data:{'_csrf-app':yii.getCsrfToken()}
success:function(data){}
});
Hope this solves your problem.
lubosdz's suggestion solved the problem
Modified controller :
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
['actions' => ['update', 'test'], 'allow' => true],
],
],
];
}
public function beforeAction($action) {
if ($action->id == 'test') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
public function actionTest() {
echo 'ok';
}
I found a solution that looks a bit like yours Muhammad Omer Aslam : by serializing the form in JavaScript I can send directly all the fields and the csrf token generated by the ActiveForm.
$.ajax({
url: ...,
type: 'POST',
data: $('#myForm').serialize(),
success: (response) => { ... }
})

redirect in before action is running infinitely in yii2

i have added access filter to web.php and in login action consists following code
public function actionLogin() {
return $this->render('loginform', ['model' => $model, 'iv' => $iv, 'key' => $key]);
}
In Yii2 you don't have to do workarounds like that to achieve checking if user is logged in. Yii2 has own Access Controll behaviours, which will do all for you.
To use it, add in your controller this behaviour:
public function behaviors()
{
return [
'access' => [
'class' => yii\filters\AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['#']
],
],
],
];
}
It will check if user whos trying access all actions in this controller is logged in. For more options you should look here: YIi2 - Access Control Filter

Override Yii2 Swiftmailer Recipient

I need to override the recipient email for every instance of Swiftmailer's send() function throughout my Yii2 application. This is for the purpose of load testing.
Is there an easy way to do this? Or at least a way to do it without editing Swiftmailer's vendor files?
If this is for test only why not set useFileTransport so emails will be saved in the folder of your choice instead of being sent. To do so configure it like this:
'components' => [
// ...
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'useFileTransport' => true,
],
],
This will save all emails in the #runtime/mail folder, If you want different one set:
'mailer' => [
// ...
'fileTransportPath' => '#runtime/mail', // path or alias here
],
If you want to still send emails and override recipients you can for example extend yii\swiftmailer\Mailer class.
class MyMailer extends \yii\swiftmailer\Mailer
{
public $testmode = false;
public $testemail = 'test#test.com';
public function beforeSend($message)
{
if (parent::beforeSend($message)) {
if ($this->testmode) {
$message->setTo($this->testemail);
}
return true;
}
return false;
}
}
Configure it:
'components' => [
// ...
'mailer' => [
'class' => 'namespace\of\your\class\MyMailer',
// the rest is the same like in your normal config
],
],
And you can use it in the same way you use mailer component all the time. When it's time to switch to test mode modify the configuration:
'mailer' => [
'class' => 'namespace\of\your\class\MyMailer',
'testmode' => true,
'testemail' => 'test222#test.com', // optional if you want to send all to address different than default test#test.com
// the rest is the same like in your normal config
],
With this, every email will be overridden with your recipient address.

Yii2 Yii::$app->user->identity->id returns an error instead of redirecting to login page

in my behaviours I have specified that actionList can only be viewed by authenticated users.
$behaviors [ 'access' ] = [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => [ 'list' ],
'allow' => ['#'],
]
],
];
In actionList I'm getting the user_id:
public function actionList() {
$user_id = \Yii::$app->user->identity->id;
return $this->render( 'list' );
}
All good, but if you go to this action when not logged in, you get an error:
PHP Notice – yii\base\ErrorException
Trying to get property of non-object
Makes sense, I'm not logged in so I don't have a user id, but why does the code go that far? If I comment the $user_id = \Yii::$app->user->identity->id; out, I get redirected to the login page, which is the expected behaviour. I don't think I should have to do yet another check to see if someone is logged in in the action itself, shouldn't that be handled by the behaviours['access'] beforehand?
Try this changing the allow and roles attributes:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['list'],
'allow' => true,
'roles' => ['#'],
],
], // rules
], // access
];
}
More info here.
Here is my cent to the already good answers above
Add following code to the main controller file in your project (not the base controller) but some controller above this which is base for every other controller
/**
* Check if user is logged in and not logged out
*
* #param type $action
* #return type
*/
public function beforeAction($action) {
$this->enableCsrfValidation = false;
if(!empty($action) && $action->actionMethod == 'actionLogin') {
return true;
}
/* Check User's Login Status */
if (is_null(Yii::$app->user->identity)) {
$this->redirect(Url::to(['../site/login']));
Yii::$app->end();
}
return true;
}

Yii2: Method not allowed arror while logout action from different controller

When i am executing logging out action from
....index.php?r=teams/dashboard
it is throwing me #405 method not allowed error. DO i have to implement logout method other than site controller.. i.e in teams controller????
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
this action does not accept Get method, you should send it as Post OR remove it from VerbFilter.
<?= Html::a('Logout', ['/user/logout'], ['data-method'=>'post']) ?>