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();
Auth::provider('multidb', function ($app, array $config) {
return new MultiDatabaseUserProvider($this->app['db']->connection(), $this->app['hash']);
Auth::provider('users', function ($app, array $config) {
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;
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\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
{
/**
* The active database connection.
*
* @var \Illuminate\Database\ConnectionInterface
*/
protected $conn;
/**
* The hasher implementation.
*
@ -31,153 +18,195 @@ class MultiDatabaseUserProvider implements UserProvider
protected $hasher;
/**
* The table containing the users.
* The Eloquent user model.
*
* @var string
*/
protected $table;
protected $model;
/**
* Create a new database user provider.
*
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param string $table
*
* @param \Illuminate\Contracts\Hashing\Hasher $hasher
* @param string $model
* @return void
*/
public function __construct(ConnectionInterface $conn, HasherContract $hasher, $table = 'users')
public function __construct(HasherContract $hasher, $model)
{
$this->conn = $conn;
$this->table = $table;
$this->model = $model;
$this->hasher = $hasher;
}
/**
* Retrieve a user by their unique identifier.
*
* @param mixed $identifier
*
* @param mixed $identifier
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveById($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.
*
* @param mixed $identifier
* @param string $token
*
* @param mixed $identifier
* @param string $token
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByToken($identifier, $token)
{
$this->setDefaultDatabase($identifier, false, $token);
$this->setDefaultDatabase($identifier, $token);
$user = $this->conn->table($this->table)
->where('id', $identifier)
->where('remember_token', $token)
->first();
$model = $this->createModel();
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.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param string $token
*
* @param \Illuminate\Contracts\Auth\Authenticatable|\Illuminate\Database\Eloquent\Model $user
* @param string $token
* @return void
*/
public function updateRememberToken(UserContract $user, $token)
{
$this->conn->table($this->table)
->where('id', $user->getAuthIdentifier())
->update(['remember_token' => $token]);
$user->setRememberToken($token);
$timestamps = $user->timestamps;
$user->timestamps = false;
$user->save();
$user->timestamps = $timestamps;
}
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
/*
* We use the email address to determine which serveer to link up.
*/
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'email')) {
$this->setDefaultDatabase(false, $value, false);
}
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
/**
* | Build query.
*/
$query = $this->conn->table($this->table);
$this->setDefaultDatabase(false, $credentials['email'], false);
// First we will add each credential element to the query as a where clause.
// 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) {
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);
}
}
// Now we are ready to execute the query to see if we have an user matching
// 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);
}
return $query->first();
}
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials
*
* @param \Illuminate\Contracts\Auth\Authenticatable $user
* @param array $credentials
* @return bool
*/
public function validateCredentials(UserContract $user, array $credentials)
{
return $this->hasher->check(
$credentials['password'], $user->getAuthPassword()
);
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
/**
* @param (int) $id
* @param string $username
* @param string $token
* Create a new instance of the model.
*
* @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'];
@ -194,15 +223,12 @@ class MultiDatabaseUserProvider implements UserProvider
$query->where('token', '=', $token);
}
if ($username) {
$query->where('email', '=', $username);
if ($email) {
$query->where('email', '=', $email);
}
$user = $query->get();
// Log::error(print_r($user,1));
// Log::error($database);
if (count($user) >= 1) {
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));
}
}

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

View File

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