Set A Role To User Programmatically

Hi, how to set a custom role for user on UserIdentity class?

I want to set a role when "authenticate" function authedicate the user.

I have write in function the $this->setState(‘roles’, ‘admin’);

and in accessRules() of Controller the ‘roles’=>‘myauth’ but not work

Any suggestion?


I found out that $this->setState(‘roles’, ‘admin’) is not appropriate method to set a role to user

So, how can I set a role to the current user?

Why do you wish to do it dynamically? You must already be using some sort of hard coded logic to determine which user gets which roles.

Hi Keith, thank you for responsing :)

In my system I have two type of users ‘editor’ and ‘author’.

So I want to check if a user has the permissions for each controller/action using in accessRules the ‘role’=>‘editor’ or ‘role’=>‘author’.

I dont want to use AR for users because there are only few users stored in php file as array

So how can I set a simple role for the user like $user->addRole(‘author’) ?

Thank you

If you want to avoid using the database, you could consider CPhpAuthManager, which will persist your role assignments to the file system. I don’t think there’s a built in way to persist to just the user’s session, which is what you seem to be suggesting.

I’d suggest configuring your auth file using the class above and let it handle the RBAC thereafter, rather than trying to do it all dynamically.


Useful article.

Ok Keith, I will try it in this way

Thanks :)