Session expire redirection on Ajax request in yii2 - yii2

I want to redirect or send ajax response about the session expired in YII2.
Currently i am getting Forbidden(402) Login Required message as ajax response

you have an action that ajax request sent to it ,
you have to change accessControll to public for that action , to Anonymous access . (input this function in your controller )
use yii\filters\AccessControl;
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['view','you-action-name-for-ajax'],
'allow' => true,
// 'roles' => ['?'],
],
],
],
];
}
be sure to remove to Roles line .. I comment it .

Related

Display a page after user click on link no login required in yii2 application

You click on link which is shared by admin through email. after clicking on this link you should view this page and no login process required for this. how it can be done?
I created this functionality and user easily redirects to this page but after few seconds the application redirects and login page is displayed.
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['deal'],
'allow' => true,
'roles' => ['?'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'deal' => ['post'],
],
],
];
}
You can check authorization on action
public function actionDeal() {
if (\Yii::$app->user->isGuest && !\Yii::$app->session->has('adminshared')) {
return $this->redirect(['site/login']);
}
// To do
}
and you can share link to another action, when user enter to this action you should set variable on session
public function actionSharedFromAdmin() {
// To Do
\Yii::$app->session->set('adminshared', true);
return $this->redirect(['yourcontroller/deal']);
}

Yii2 - Rate limit skipped: user not logged in

I try to enable RateLimiter and follow documentation for Yii2 https://www.yiiframework.com/doc/guide/2.0/en/rest-rate-limiting
I test it with logged user and in info log I have:
2020-04-21 16:50:35 [172.18.0.1][5][-][info][yii\filters\RateLimiter::beforeAction] Rate limit skipped: user not logged in.
2020-04-21 16:50:35 [172.18.0.1][5][-][info][yii\web\User::login] User '5' logged in from 172.18.0.1. Session not enabled.
So RateLimiter check user before it logged in? Any suggestions?
UPDATE - behaviors()
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => CompositeAuth::className(),
'authMethods' => [
HttpBearerAuth::className(),
],
];
$behaviors['verbs'] = [
'class' => \yii\filters\VerbFilter::className(),
'actions' => [
'index' => ['get'],
'view' => ['get'],
'create' => ['post'],
'update' => ['put'],
'delete' => ['delete'],
],
];
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
],
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = [
'options',
];
$behaviors['access'] = [
'class' => AccessControl::className(),
'rules' => [
....
],
];
return $behaviors;
}
Event handlers are triggered in the order they are registered. In case of behaviors that means that the order in which you are defining the behaviors will decide the order in which they are executed.
The behaviors defined in the yii\rest\Controller looks like this:
public function behaviors()
{
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
'verbFilter' => [
'class' => VerbFilter::className(),
'actions' => $this->verbs(),
],
'authenticator' => [
'class' => CompositeAuth::className(),
],
'rateLimiter' => [
'class' => RateLimiter::className(),
],
];
}
That means that the authenticator behavior should be executed before the rateLimiter.
But in your code you are unsetting the authenticator definition and then adding it back after you add some other behaviors. That moves authenticator behind the rateLimiter and causes that the rateLimiter is executed first.
You need to do same thing with rateLimiter as you are doing with the authenticator.
public function behaviors()
{
$behaviors = parent::behaviors();
$rateLimiter = $behaviors['rateLimiter'];
unset($behaviors['rateLimiter']);
// ... other code ...
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// re-add rate limiter
$behaviors['rateLimiter'] = $rateLimiter;
// ... the rest of code
}

Logout automatically use after session expire in yii2

How and where can i write code to redirect to login page after the session expires in Yii2.0 ?
// if (!Yii::$app->controller->id == 'site') {
// $session = Yii::$app->session;
// if (!$session->isActive) {
// $model = new LoginForm();
// return $this->goHome();
// }
// }
i tried to do this in the base controller.
you never know when user session is expire , but you can force users to login before using some actions :
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['youraction'],
'allow' => true,
'roles' => ['#'], // you can use matchCallback to create more powerful check
],
],
],
];
}
dont forget to add use yii\filters\AccessControl;

What is function behaviors in SiteController.php?

I am starting up with yii2
I dont have any idea of previous version of YII
But I have good knowledge of codeigniter and have been working in codeigniter from last 3 years.
MY Question is as below :
There is a function name behaviors() in SiteController.php file.
It has below code. I want to know what does it do?
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
In the sample you privided there are two part
'access'
and
'verbs'
the access section configure the Access Control Filter rules
http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html
one of the authorization method implemented by Yii2 ( best used by applications that only need some simple access control)
and http://www.yiiframework.com/doc-2.0/yii-filters-verbfilter.html
that define the allowed HTTP request methods for each action. VerbFilter checks if the HTTP request methods are allowed by the requested actions. If not allowed, it will throw an HTTP 405 exception.
In your case set that the action logout must performed by a post method
for a brief guide you can see
http://www.yiiframework.com/doc-2.0/guide-structure-filters.html

Yii2 restricting access to RBAC Module itself

How I can restrict access to RBAC Module itself?
I'm using yii\rbac\DbManager and I have created a module(Authorization) in backend for permission assignment,create auth items, now I want to make sure only admin can access this module!
In controller I have used something this and it's working fine.
use yii\filters\AccessControl;
class MyController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create', 'update', 'delete'], //only be applied to
'rules' => [
[
'allow' => true,
'actions' => ['index', 'view', 'create', 'update','delete'],
'roles' => ['admin'],
],
],
],
.........
I have put this in Authorization.php init function but nothing happen, all auth controllers are accessable.
public function init()
{
if(\Yii::$app->user->can('admin'))
parent::init();
// custom initialization code goes here
}
Update
backend/config/main.php
'modules' => [
'authorization' => [
'class' => 'backend\modules\authorization\Authorization',
],
],
In your module class you can add this method
public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
if (!\Yii::$app->user->can('admin')) {
throw new \yii\web\ForbiddenHttpException('You are not allowed to access this page.');
}
return true;
}