How to implement login functionality using different tables in yii2

I am using Yii 2 basic application template. I have a employee table with username and password field. RBAC is also implemented very well along with user application component for authentication. Now there is a requirement of creating different tables such as pastor, teacher, admin. There are certain fields different from that in employee table so we need to create additional extra tables.

Now how to implement user Authentication (user application component with identity classes) for multiple tables (employee, pastor, teacher, admin) using same login form.

And can we implement RBAC if there are many such tables, because in RBAC there is auth_assignment table where user_id field is assigned to be employee table’s empid as foreign key. Now there are three more tables.

So in RBAC, for auth_assignment, do we need to specify employee, pastors, teacher and admin table’s primary key as foreign key.?

How to implement this in detail?

  1. Implement IdentityInterface for each entity you want to authenticate with. Don’t forget that getId() should return unique identifier such as employee-1, pastor-2.
  2. Tweak your form too look into each identity type one by one.
  3. RBAC is fine as long as ids are unique.

Can you explain in detail the steps I need to perform?
Suppose I have table fieldofficer and pastor. Then I need to create CRUD for both of them?
In config file, is this code sufficient for pastor and fieldofficer.

‘identityClass’ => ‘app\models\Pastor’,
‘enableSession’ => true,

‘identityClass’ => ‘app\models\FieldOfficer’,
‘enableSession’ => true,

What code should I write in LoginForm model as well as in actionLogin in Site controller so that while logging a user the entered username and password should be checked from both table and on that basis if the username and password match from one of the two tables, then either pastor or fieldofficer will login.?

Here I put together a wiki article expanding what I wrote above:

1 Like