Closed evansbusobozi closed 5 years ago
Hi answer is here
` use Illuminate\Contracts\Hashing\Hasher; use Illuminate\Foundation\Auth\User as Authenticatable;
class AuthenticateExample { protected $model;
protected $hasher;
public function __construct(Authenticatable $model, Hasher $hasher)
{
$this->model = $model;
$this->hasher = $hasher;
}
public function getEntityByCredentials($username, $password)
{
if (method_exists($this->model, 'findForPassport')) {
$user = (new $this->model)->findForPassport($username);
} else {
$user = (new $this->model)->where('email', $username)->first();
}
if (! $user) {
return;
} elseif (method_exists($user, 'validateForPassportPasswordGrant')) {
if (! $user->validateForPassportPasswordGrant($password)) {
return;
}
} elseif (! $this->hasher->check($password, $user->getAuthPassword())) {
return;
}
return $user;
}
}
`
`
$entity = $this->authExample->getEntityByCredentials($username, $password);
if (! $entity) {
throw OAuthServerException::invalidCredentials();
}
$accessToken = $entity->createToken($name);
`
So @aytaceminoglu, how do I use this code in my project?
@Evanzsnr instead of use Auth::attempt()
you will check the user credentials like on examples. If all is correct you can create a personal access token using the method createToken()
from entity logged.
Hi @Evanzsnr
My MultiAuth Controller:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Hash;
class MultiAuth
{
protected $models;
public function __construct($models)
{
$this->models = $models;
}
public function getEntityByCredentials($username, $password)
{
foreach ($this->models as $model) {
if (method_exists($model, 'findForPassport')) {
$user = (new $model)->findForPassport($username);
} else {
$user = (new $model)->where('username', $username)->first();
}
if($user) break;
}
//dd($user);
if (! $user) {
return;
} elseif (method_exists($user, 'validateForPassportPasswordGrant')) {
if (! $user->validateForPassportPasswordGrant($password)) {
return;
}
} elseif (! Hash::check($password, $user->getAuthPassword())) {
return;
}
return $user;
}
}
And im calling like that in another controller:
$multiAuth = new MultiAuth([StudentParent::class, Teacher::class]);
$user = $multiAuth->getEntityByCredentials($username, $password);
@Evanzsnr here has good example how to implements it too
Thanks @sfelix-martins, let me try it out.
Hello, the auth::attempt() function is not working for me even when the user already exists in the database.
Here is my login function.
`public function login(Request $request) { $request->validate([ 'email' => 'required|string|email', 'password' => 'required|string', 'remember_me' => 'boolean' ]);
Whenever I attempt to login a user, I get a message saying unauthorized.