Role based identity

I’m developing a site with different classes of users (Retailer, Buyer and Publisher) All of them inherit from User class that extends ActiveRecord and implements IdentityInterface. User table just has login information and each “role” table has specific information (name and surname for Buyer, company name and id for Retailer, etc…) A User can have different roles at the same time (I can be a Buyer and a Retailer). User table has a field that I use to know “last role” of a User. When User log in, I “assign” this Role and user can change its current role whenever he wants (I then change “last role” field in database).

When users log in I want to have a Retailer, Buyer or Publisher as current identity. What should I do to get this?

In few words:

make a User indentity class

Make the 3 role class extending the User class and adding the fields you need.

When the user login::

[list=1][]do password validation against user class[]if pass, verify which was the last role[]init the corresponding class role[]initialize the user session with this user/role identity[/list]When the user switch role:

[list=1][]eventually verify if the user own this role[]initialize the user session with this user/role identity[/list]If you use a module/extension to manage user login, extend the class and change a bit login procedure.

I saw some extension having login procedure in controllers some other in model, search for the following code




This is creating the user session, the first parameter is the user identity, pass the role identity the user is currently on.

to simply switch identity/role use switchIdentity


Thank you for your answer. When I wrote the PO everything was working but the role initialization. Sorry if it looked as I needed more help than that.

I’ve created a RoleProxy class that implements IdentityInterface and extends ActiveRecord using user table (I’ve also a User class). I use this class as identity class so when someone tries to login, RoleProxy is the one who verifies access. findIdentity method looks this way:

    public static function findIdentity($id){

        $result = null;

        $user   = User::findOne(['id' => $id, 'status' => User::STATUS_ACTIVE]);


            $className = self::getRoleClassName($user->current_role_id);

            $result    = $className::findOne(['id' => $id]);


        return $result;


So when someone tries to login, I look for a User. If User exists, I take last active role for that user and I look for its corresponding class (Retailer, Buyer or Publisher). This way, Yii::$app->user->identity is not a User bue a Retailer/Buyer/Publisher.

I also use RoleProxy class to get available roles, check if a User is actually working as a certain role, etc…