Auth for multiple users tables

Viewed 164

I have a problem with Laravel auth module.

I am rewriting old tool to laravel but have to keep old system DB structure.

System use multiple DBs (separated per department) and recognize which DB should be used by url, ex.

www.example.com/foo    //use foo DB for foo department
www.example.com/bar    //use bar DB for bar department

Foo and Bar DB have their own users table. There are some accounts that exist in both DBs but have different id, username is the same. Example:

//foo DB users table
ID   username
1    xyz
2    abc

//bar DB users table
ID   username
1    qwe
2    xyz

Let's say that I am logged in into system using foo deparment (and DB) as a user xyz (id 1).

I am switching now to bar department (and bar DB).

As a result I am logged in into bar department (and DB) as a user qwe because system keep using id (1) on which I've logged in into the system.

How to change that behaviour and force system to use username instead of id as a key to indetify user among DBs?

I know that i can use username as a primary key in users model but then I will have to change all relations connected with user model and also other things like Auth::id() etc.

Is there any easier way?

1 Answers

Auth guards refer to the user id field in this manner: $user->getAuthIdentifier())

So you could do this in your User model:

class User extends Model {
...

  public function getAuthIdentifier() {
    return $this->username;
  }
}

If you're afraid of Auth::id() changes, have a look at it's implementation for session guard:

public function id()
{
    if ($this->user()) {
        return $this->user()->getAuthIdentifier();
    }
}

Update:

But your best way to solve any custom authorization trouble is to use your own users provider and auth guard.

It may sound difficult, but it's as easy as implementing two interfaces. Check out the official documentation here here and here. As an example you can use vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php (have a good look on it's helper trait GuardHelpers by the way) and vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php

Related