Switch Multi-DB to Eloquent driver (#37) (#2443)

Switch Multi-DB to Eloquent driver
This commit is contained in:
David Bomba 2018-10-15 20:06:57 +11:00 committed by GitHub
parent 4076a00dae
commit 275be96d4f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 140 additions and 98 deletions

View File

@ -0,0 +1,10 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserAccount extends Model
{
//
}

View File

@ -26,8 +26,13 @@ class AuthServiceProvider extends ServiceProvider
{ {
$this->registerPolicies(); $this->registerPolicies();
Auth::provider('multidb', function ($app, array $config) { Auth::provider('users', function ($app, array $config) {
return new MultiDatabaseUserProvider($this->app['db']->connection(), $this->app['hash']); return new MultiDatabaseUserProvider($this->app['hash'], $config['model']);
});
Auth::provider('contacts', function ($app, array $config) {
return new MultiDatabaseUserProvider($this->app['hash'], $config['model']);
}); });
} }
} }

View File

@ -2,27 +2,14 @@
namespace App\Providers; namespace App\Providers;
use App\Models\User;
use Illuminate\Auth\GenericUser;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
class MultiDatabaseUserProvider implements UserProvider class MultiDatabaseUserProvider implements UserProvider
{ {
/**
* The active database connection.
*
* @var \Illuminate\Database\ConnectionInterface
*/
protected $conn;
/** /**
* The hasher implementation. * The hasher implementation.
* *
@ -31,153 +18,195 @@ class MultiDatabaseUserProvider implements UserProvider
protected $hasher; protected $hasher;
/** /**
* The table containing the users. * The Eloquent user model.
* *
* @var string * @var string
*/ */
protected $table; protected $model;
/** /**
* Create a new database user provider. * Create a new database user provider.
* *
* @param \Illuminate\Contracts\Hashing\Hasher $hasher * @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param string $table * @param string $model
*
* @return void * @return void
*/ */
public function __construct(ConnectionInterface $conn, HasherContract $hasher, $table = 'users') public function __construct(HasherContract $hasher, $model)
{ {
$this->conn = $conn; $this->model = $model;
$this->table = $table;
$this->hasher = $hasher; $this->hasher = $hasher;
} }
/** /**
* Retrieve a user by their unique identifier. * Retrieve a user by their unique identifier.
* *
* @param mixed $identifier * @param mixed $identifier
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null * @return \Illuminate\Contracts\Auth\Authenticatable|null
*/ */
public function retrieveById($identifier) public function retrieveById($identifier)
{ {
$this->setDefaultDatabase($identifier); $this->setDefaultDatabase($identifier);
$user = $this->conn->table($this->table)->find($identifier); $model = $this->createModel();
return $this->getGenericUser($user); return $model->newQuery()
->where($model->getAuthIdentifierName(), $identifier)
->first();
} }
/** /**
* Retrieve a user by their unique identifier and "remember me" token. * Retrieve a user by their unique identifier and "remember me" token.
* *
* @param mixed $identifier * @param mixed $identifier
* @param string $token * @param string $token
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null * @return \Illuminate\Contracts\Auth\Authenticatable|null
*/ */
public function retrieveByToken($identifier, $token) public function retrieveByToken($identifier, $token)
{ {
$this->setDefaultDatabase($identifier, false, $token); $this->setDefaultDatabase($identifier, $token);
$user = $this->conn->table($this->table) $model = $this->createModel();
->where('id', $identifier)
->where('remember_token', $token)
->first();
return $this->getGenericUser($user); $model = $model->where($model->getAuthIdentifierName(), $identifier)->first();
if (! $model) {
return null;
}
$rememberToken = $model->getRememberToken();
return $rememberToken && hash_equals($rememberToken, $token) ? $model : null;
} }
/** /**
* Update the "remember me" token for the given user in storage. * Update the "remember me" token for the given user in storage.
* *
* @param \Illuminate\Contracts\Auth\Authenticatable $user * @param \Illuminate\Contracts\Auth\Authenticatable|\Illuminate\Database\Eloquent\Model $user
* @param string $token * @param string $token
*
* @return void * @return void
*/ */
public function updateRememberToken(UserContract $user, $token) public function updateRememberToken(UserContract $user, $token)
{ {
$this->conn->table($this->table) $user->setRememberToken($token);
->where('id', $user->getAuthIdentifier())
->update(['remember_token' => $token]); $timestamps = $user->timestamps;
$user->timestamps = false;
$user->save();
$user->timestamps = $timestamps;
} }
/** /**
* Retrieve a user by the given credentials. * Retrieve a user by the given credentials.
* *
* @param array $credentials * @param array $credentials
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null * @return \Illuminate\Contracts\Auth\Authenticatable|null
*/ */
public function retrieveByCredentials(array $credentials) public function retrieveByCredentials(array $credentials)
{ {
/* if (empty($credentials) ||
* We use the email address to determine which serveer to link up. (count($credentials) === 1 &&
*/ array_key_exists('password', $credentials))) {
return;
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'email')) {
$this->setDefaultDatabase(false, $value, false);
}
} }
/** $this->setDefaultDatabase(false, $credentials['email'], false);
* | Build query.
*/ // First we will add each credential element to the query as a where clause.
$query = $this->conn->table($this->table); // Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) { foreach ($credentials as $key => $value) {
if (!Str::contains($key, 'password')) { if (Str::contains($key, 'password')) {
continue;
}
if (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value); $query->where($key, $value);
} }
} }
// Now we are ready to execute the query to see if we have an user matching return $query->first();
// the given credentials. If not, we will just return nulls and indicate
// that there are no matching users for these given credential arrays.
$user = $query->first();
return $this->getGenericUser($user);
}
/**
* Get the generic user.
*
* @param mixed $user
*
* @return \Illuminate\Auth\GenericUser|null
*/
protected function getGenericUser($user)
{
if (!is_null($user)) {
return new GenericUser((array) $user);
}
} }
/** /**
* Validate a user against the given credentials. * Validate a user against the given credentials.
* *
* @param \Illuminate\Contracts\Auth\Authenticatable $user * @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials * @param array $credentials
*
* @return bool * @return bool
*/ */
public function validateCredentials(UserContract $user, array $credentials) public function validateCredentials(UserContract $user, array $credentials)
{ {
return $this->hasher->check( $plain = $credentials['password'];
$credentials['password'], $user->getAuthPassword()
); return $this->hasher->check($plain, $user->getAuthPassword());
} }
/** /**
* @param (int) $id * Create a new instance of the model.
* @param string $username
* @param string $token
* *
* @return void * @return \Illuminate\Database\Eloquent\Model
*/ */
private function setDefaultDatabase($id = false, $username = false, $token = false) : void public function createModel()
{
$class = '\\'.ltrim($this->model, '\\');
return new $class;
}
/**
* Gets the hasher implementation.
*
* @return \Illuminate\Contracts\Hashing\Hasher
*/
public function getHasher()
{
return $this->hasher;
}
/**
* Sets the hasher implementation.
*
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @return $this
*/
public function setHasher(HasherContract $hasher)
{
$this->hasher = $hasher;
return $this;
}
/**
* Gets the name of the Eloquent user model.
*
* @return string
*/
public function getModel()
{
return $this->model;
}
/**
* Sets the name of the Eloquent user model.
*
* @param string $model
* @return $this
*/
public function setModel($model)
{
$this->model = $model;
return $this;
}
private function setDefaultDatabase($id = false, $email = false, $token = false) : void
{ {
$databases = ['db-ninja-1', 'db-ninja-2']; $databases = ['db-ninja-1', 'db-ninja-2'];
@ -194,15 +223,12 @@ class MultiDatabaseUserProvider implements UserProvider
$query->where('token', '=', $token); $query->where('token', '=', $token);
} }
if ($username) { if ($email) {
$query->where('email', '=', $username); $query->where('email', '=', $email);
} }
$user = $query->get(); $user = $query->get();
// Log::error(print_r($user,1));
// Log::error($database);
if (count($user) >= 1) { if (count($user) >= 1) {
break; break;
} }
@ -222,4 +248,5 @@ class MultiDatabaseUserProvider implements UserProvider
//$this->conn = app('db')->connection(config("database.connections.database." . $database . "." . $db_name)); //$this->conn = app('db')->connection(config("database.connections.database." . $database . "." . $db_name));
$this->conn = app('db')->connection(config('database.connections.database.'.$database)); $this->conn = app('db')->connection(config('database.connections.database.'.$database));
} }
} }

0
bootstrap/app.php Normal file → Executable file
View File

View File

@ -26,7 +26,7 @@ class UsersTableSeeder extends Seeder
$faker = Faker\Factory::create(); $faker = Faker\Factory::create();
$account = Account::create([ $account = Account::create([
'name' => $faker->name, 'name' => $faker->name(),
]); ]);
$user = User::create([ $user = User::create([