Yii2 Global Filter/Behavior to Force User to Authenticate First

Yii2 global filter/behavior to force user to authenticate first

Ok, so I had to add the following code below 'components' => [...]

 'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[

'allow' => true,
'roles' => ['@'],
],
],
],

Read more about the format: http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#configuration-format

Using access control in yii2

add 'actions' => [ 'display'],

like below

'rules' => [
// allow authenticated users
[
'actions' => [ 'display'],
'allow' => true,
'roles' => ['@'],
'matchCallback' => function ($rule, $action) {

return $this->redirect(Yii::$app->request->baseUrl.'/site/login');
}],

],

normally it work for me

Attach behavior globally for all models in application config (without inheritance)

In case you don't want to use inheritance I can suggest the following method.

The basic idea behind it is using events of ActiveRecord:

use yii\base\Event;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

...

$events = [ActiveRecord::EVENT_BEFORE_INSERT, ActiveRecord::EVENT_BEFORE_UPDATE];

foreach ($events as $eventName) {
Event::on(ActiveRecord::className(), $eventName, function ($event) {
$model = $event->sender;

if ($model->hasAttribute('created_at') && $model->hasAttribute('updated_at')) {
$model->attachBehavior('timestamp', [
'class' => TimestampBehavior::className(),
'value' => function () {
return date('Y-m-d H:i:s');
},
]);
}
});
}

This code will dynamically attach TimestampBehavior to all models which are inherited from yii\db\ActiveRecord before saving it to database.

You can also omit createdAtAttribute and updatedAtAttribute because they already have these names by default (since it's most common).

As you can see behavior is attached only when both created_at and updated_at attributes exist, no need to create extended behavior for that.

To avoid inheritance and copy / paste this code should run on every application bootstrap.

You can add this to entry script (before application run) right away and it will work, but it's not good practice to place it here, also these files are generated automatically and in git ignored files list.

So you need to create just one separate component containing that logic and include it in the config. No need to extend classes etc.

Let's say it's called common\components\EventBootstrap. It must implement BootstrapInterface in order to work properly.

namespace common\components;

// Other namespaces from previous code

use yii\base\BootstrapInterface;

class EventBootstrap implements BootstrapInterface
{
public function bootstrap($app)
{
// Put the code above here
}
}

Then you need to include it in config in bootstrap section:

return [
'bootstrap' => [
'common\components\EventBootstrap',
],
];

Official documentation:

  • Event::on()
  • BootstrapInterface

Additional notes: I also tried to specify it through the application config only, but with no success.

I didn't find a way to specify ActiveRecord there.

You can see this question, but behavior there is attached to the whole application which is possible through config.

Yii2 Behavior method in model

According to the DOCS

Because this class is a behavior when it is attached to a component,
that component will then also have the properties and methods defined
in the behavior.

So if your function fields() is inside your User model then you can call the function via $this

public function fields(){
return $this->getLastflight();
}

how to limit access url view on yii2 by id

A simple way for controlling access and avoid to guest user (not authenticated) to access is use filter for access control

<?php
namespace yourapp\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\models\LoginForm;
use yii\filters\VerbFilter;

/**
* Site controller
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'actions' => ['logout', 'index'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}

In this sample you can see that you can configure the action you can access ofr all and for authenticated @
You can find useful this guide http://www.yiiframework.com/doc-2.0/guide-security-authorization.html and this reference http://www.yiiframework.com/doc-2.0/yii-filters-accesscontrol.html

In Yii2 you can also use a RBAC authrization component for define class of user and grant to this class specific accessing rules ..

and you can also check programmaticaly the RABC Auth for specific need eg:

   if (!Yii::$app->user->isGuest) { // if the user is authenticated (not guest)
if ( Yii::$app->User->can('admin') ){ // if the role is admin

.....
you app code


Related Topics



Leave a reply



Submit