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

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;
}

Related

How to set home page in Yii2

public function actionIndex() {
$this->layout = 'landing';
$loginForm = new LoginForm();
if (\Yii::$app->request->getIsPost()) {
$loginForm->load(\Yii::$app->request->post());
if ($loginForm->validate()) {
$user = $loginForm->getUser();
\Yii::$app->user->login($user);
return $this->goHome();
}
}
}
method goHome() sends to the home page. I have added '' => 'site/index' to the URL Manager earlier to send people to the SiteController and Index action, but Yii2 does not do anything. How to set up a correct home page rule?
You should write homeUrl parameter on config/main.php. For example:
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'homeUrl' => ['some/home-url-example'],
'modules' => [
...
],
...
]

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

Prevent show data from another user

How to prevent all detailView show data from another user ??
For example, this happens when you type an product ID of another user in the URL. The detailView shows the details of the product normally, however belongs to another User, and may even change it and delete it.
You can do something like this in the controller if you don't want to use RBAC :
protected function findModel($id)
{
//Check if the author is the current user
if (($model = Product::findOne($id)) !== null && $model->author_id==Yii::$app->user->id) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Like this users which are not the author can't view, update or delete the product.
http://www.yiiframework.com/forum/index.php/topic/61915-prevent-show-data-from-another-user/page__view__findpost__p__274644
Several options:
1) simplest one, in the controller before showing the view check that the current user can see the product. If he cannot redirect him (by throwing an error) to a 404 page (or whatever error you want to show).
2) use RBAC to set up roles and what those roles can do. This is the most professional option
3) you may be able to modify the accessfilter to do this too too
If you need to ask how to do this go with option 1.
If you want option 2 or 3 start by reading this http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
An example to what Mihai have suggested.
public function behaviors()
{
return [
'accessControl' => [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
'actions' => ['view'],
'allow' => true,
'matchCallback' => function () {
$request = \Yii::$app->request;
$user = \Yii::$app->user->identity;
$product = Product::findOne($request->get('id'));
if ($user && $product->owner_id == $user->id) {
return true;
}
return false;
}
],
[
'allow' => false,
'roles' => ['*'],
],
],
]
];
}

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']) ?>

Redirect user to previous page after auth (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' => ['#'],
],
],
],
];
}
// ...
}