Mixing ACF and RBAC

ACF contains a property named role that is usually filled with ? to indicate that access is available for all users, and @ to indicate that access is restricted to authenticated ones. But there is a third option that refers its content to the role name of the RBAC system.

For each controller, therefore, it is enough to overwrite behaviors() by specifying the roles that can access the actions inside the controller and then to associate users to the role, in order to allow or deny access.

Example – managing users' roles to access rooms, reservations, and customers

In this example, we will show you how to manage the access to the controller actions using ACF and RBAC.

We will use the foo user to simulate an authenticated user for RoomsController. The first thing to do is to extend the behaviors() method of RoomsController in basic/controller/RoomsController.php with this content:

Use yiifiltersAccessControl;

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['create'],
                        'roles' => ['operator'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['index'],
                    ],                    
                ],
                
            ],
        ];
    }

With this code, we will guarantee access to the create action only to users with the operator role, while the index action access is given to all users and all other actions are denied to everyone.

So, if we try to browse to http://hostname/basic/web/rooms/create, we should see an error page with a forbidden error. This is because we are trying to access a page with insufficient permissions.

Now, we can execute the authentication simply by going to http://hostname/basic/web/my-authentication/login and typing foo as the username and foopassword as the password, since we already created a user with these credentials in the database in the previous chapter. We should see a successfully logged in page.

The last thing to do is to assign the operator role to the foo user. We can use the authorization manager just created in http://hostname/basic/web/authorization-manager/index. Now, click on the cell referring to the foo user and the operator role. In this way, we have assigned the operator role to the foo user.

Finally, we can refresh the rooms creation page at http://hostname/basic/web/rooms/create. We can see now the create action page of the rooms controller.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.90.141