Tom K
Tom K

Reputation: 135

How to add a role to user when having basic User model in Yii2

Building a lightweight app using basic installation of Yii2. I need to assign a role for a user but don't want to have users and user roles stored in database. How can I set a role for users defined in User->users class?

Default User model and default user definition look like this:

class User extends \yii\base\BaseObject implements \yii\web\IdentityInterface
{
    public $id;
    public $username;
    public $password;
    public $authKey;
    public $accessToken;

    private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'admin',
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ],

Upvotes: 1

Views: 238

Answers (1)

Bizley
Bizley

Reputation: 18021

You can use RBAC PhpManager for that that will store all roles info in files instead.

First configure your AuthManager component in config/web.php:

// ...
'components' => [
    // ...
    'authManager' => [
        'class' => 'yii\rbac\PhpManager',
    ],
    // ...
],

By default it uses 3 files to keep the data:

  • @app/rbac/items.php
  • @app/rbac/assignments.php
  • @app/rbac/rules.php

So make sure there is folder rbac in your application's root and that it's write-able by the www process. If you want to place the files somewhere else (or rename them) you can provide the new path in the configuration like:

'authManager' => [
    'class' => 'yii\rbac\PhpManager',
    'itemFile' => // new path here for items,
    'assignmentFile' => // new path here for assignments,
    'ruleFile' => // new path here for rules,
],

The rest now is just like in the Authorization Guide.

  1. Prepare roles and permissions (example in console command - by running this command once you set all roles; remember that if you want to run it in console you need also configure console.php with the same component).
  2. Assign role to a user (example - here it's done during the signup but you can do it also in the above command).

Now you can control access with direct check or behavior configuration.

Upvotes: 3

Related Questions