Laravel 5.6 multi auth keeps on authenticating on default model - php

I have a two table login: examinee and company. company is my default auth,
every time i try to attempt auth in examinee it keeps on using the default table which is the company.
I've seen several problems that are similar to mine but it doesn't seem to work for me or I might have overlooked something that maybe some of you might be able to see.
What am I doing wrong?
Auth.php:
'defaults' => [
'guard' => 'web',
'passwords' => 'companies',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'companies',
],
'api' => [
'driver' => 'token',
'provider' => 'companies',
],
'examinees' => [
'driver' => 'session',
'provider' => 'examinees',
],
],
'providers' => [
'companies' => [
'driver' => 'eloquent',
'model' => App\Company::class,
],
'examinees' => [
'driver' => 'eloquent',
'model' => App\Examinee::class,
],
],
'passwords' => [
'companies' => [
'provider' => 'companies',
'table' => 'password_resets',
'expire' => 60,
],
'examinees' => [
'provider' => 'examinees',
'table' => 'password_resets',
'expire' => 60,
],
],
LoginController:
public function showLoginForm()
{
return view('examinee.auth.login');
}
protected function guard()
{
return Auth::guard('examinees');
}
public function login(Request $request) {
$user = Examinee::where('email', $request->get('email'))->first();
if (Auth::attempt(['id' => $user->id, 'password' => $request->get('password')])) {
// prints data from Company table instead of Examinee...
echo "AUTH USER:<pre>";
print_r(Auth::user());
echo "</pre>";
// return redirect('/home');
}
}
Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Examinee extends Authenticatable
{
use Notifiable;
protected $table = 'examinees';
protected $fillable = ['email', 'password'];
protected $hidden = ['password', 'remember_token'];
public $timestamps = false;
}

How ive done this in the past is to add the guard to your auth
Change
Auth::attempt(['id' => $user->id, 'password' => $request->get('password')
to
Auth::guard('examinees')->attempt(['id' => $user->id, 'password' => $request->get('password')

Related

laravel 8 - auth()->factory() { same refresh() and attemp() } is undefind in JWT AuthController

I use JWT for API authentication in Laravel 8.
When I use auth()-> in my controller , for factory() or attemp() or anything, Laravel does not know it and says:
Undefined method 'attempt'.intelephense(1013)
I don't know what I forgot to include
my AuthController :
namespace App\Http\Controllers\Api\Admin;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
class AuthController extends Controller
{
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->createNewToken($token);
}
.
.
.
.
.
and my config/auth.php file :
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// Following array is newly added to config
'otp-user' => [
'driver' => 'otp-based-auth-provider'
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
Intelephense has some trouble dealing with some methods in Laravel. You can either ignore it, as it should work or you can call it by:
JWTAuth::attempt($validator->validated)
It should make the error go away.

Laravel 7. Attempt method return false

I hope my english is good enough to explain my problem. I'm working with laravel 7, and I'm trying to implement my own AuthController, because I can't use migrations and I can't use a table 'users' because I have a db implemented. I've read all the documentation of laravel about authentication and spent days reading a lot of posts with this problem, and I tried everything but still does not work. The problem is with the attempt method. My register method is working fine, but I can't login, actually I tried to put manually the data(that's why credentials are commented) to find the problem but I don't know why is not working
My Regsiter method.
public function storeUser(Request $request)
{
//dd($request);
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:administradores,ADMIN_Correo',
'password' => 'required|string|min:8|confirmed',
'password_confirmation' => 'required',
]);
Administrador::create([
'ADMIN_Nombre' => $request->name,
'ADMIN_Correo' => $request->email,
'ADMIN_Contrasena' => Hash::make($request->password),
]);
//return redirect('home');
}
My Login method.
public function authenticate(Request $request)
{
/*$request->validate([
'ADMIN_Correo' => 'required|string|email',
'ADMIN_Contrasena' => 'required|string',
]);*/
//$credentials = $request->only('ADMIN_Correo', 'ADMIN_Contrasena');
if (Auth::guard('admin')->attempt(['ADMIN_Correo' => 'edwin2#gmail.com
','ADMIN_Contrasena' => '12345678'])) {
return redirect()->intended('home');
}else{
echo 'error';
}
//return redirect('login')->with('error', 'Oppes! You have entered invalid credentials');
}
My config/auth.php file
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
]
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Administrador::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Administrador::class,
],
],
My Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Administrador extends Authenticatable
{
use Notifiable;
protected $table = 'administradores';
protected $primaryKey = 'ADMIN_Id';
public $timestamps = false;
public $incrementing = true;
protected $fillable = ['ADMIN_Nombre','ADMIN_Correo','ADMIN_Contrasena'];
protected $guard = 'admin';
public function getAuthPassword()
{
return $this->ADMIN_Contrasena;
}
}
NOTES The field for password:(ADMIN_Contrasena) is varchar 255

Laravel - Getting wrong guard model when I try to use multi authentication

I'm having some problems with Laravel 5.7 multi-auth implementation.
I have created a new table for backend login: "AdminUsers".
So, I modified auth.php file:
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Ecommerce\User::class,
],
'admins' => [
'driver' => 'eloquent',
'table' => Ecommerce\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Then, I create the AdminLoginController class:
<?php
namespace Ecommerce\Http\Controllers\Admin\Auth;
use Illuminate\Http\Request;
use Ecommerce\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class AdminLoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/index';
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function showLoginForm()
{
return view('admin.auth.login');
}
protected function attemptLogin(Request $request)
{
return $this->guard('admin')->attempt(
$this->credentials($request), $request->filled('remember')
);
}
protected function authenticated(Request $request, $user)
{
dd('authenticated!');
}
public function username()
{
return 'username';
}
}
I setted this routes in routes file:
Route::get ('/login', ['uses'=>'Auth\AdminLoginController#showLoginForm'])->name('login_page');
Route::post('/login', ['uses'=>'Auth\AdminLoginController#login' ])->name('do_login' );
The problem is, that when I do login, Laravel tries to use "users" guard instead of the defined "admin" guard. So that throw a SQL error (because I have not created the "Users" table in the DB).
Even if I do var_dump($this->guard('admin')) inside AdminLoginController::attemptLogin method, the response gives me a SessionGuard object with "Ecommerce\User" instead of "Ecommerce\AdminUser" that is the one defined as "admin" in auth.php guard array.
Anyone knows where else can I look to solve this?
Thanks!
The problem lies in your auth.php providers section.
'table' => Ecommerce\AdminUser::class
'table' should be replaced with 'model'.

Why is Auth::attempt always returns false in Laravel 5.3?

I'm new in Laravel. I try to use Multiple Auth in Laravel 5.3 and my auth.php file is:
<?php
return [
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'courier' => [
'driver' => 'session',
'provider' => 'couriers',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
]
],
'providers' => [
'couriers' => [
'driver' => 'eloquent',
'model' => App\Courier::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
]
],
'passwords' => [
'couriers' => [
'provider' => 'couriers',
'table' => 'password_resets',
'expire' => 60,
],
'clients' => [
'provider' => 'clients',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Then, when I store Clients or Couriers in the DB, I use bcrypt for password (Bring also use the function Hash::make() for passwords). For example, my model Courier is:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Courier extends Authenticatable
{
[..]
public function setPasswordAttribute($pass){
$this->attributes['password'] = bcrypt($pass);
}
[..]
}
And when update a courier, in my controller I have:
public function update(Request $request, $id) {
$fieldsCourier = $request->all();
$courier = Courier::find($id);
if( isset($fieldsCourier['password']) )
$fieldsCourier['password'] = bcrypt($fieldsCourier['password']);
if( $courier->update($fieldsCourier) )
$courier = Courier::find($id);
}
I have a method called authenticate but the method attempt always return false (invalid_credentials). Even so send valid credentials.. This is my code:
public function authenticate(Request $request) {
$credentials = $request->only('email', 'password');
try {
if ( auth()->guard('courier')->attempt($credentials) ){
$user = Auth::guard('courier')->user();
} else {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('user'));
}
I not know what I'm doing wrong. Anything am I doing wrong?
you have encrypt the password twice, on your model and controller.
just remove one of them
e.g: don't use bcrypt on your controller, because you have already use bcrypt on your model.

Multi auth laravel 5.2, autentication not working

I am developing an app which has two types of users, users and admins on laravel 5.2. My problem is that the autenticacion is never successful.
I changed config/auth to:
return [
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
'passwords' => [
'user' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admins',
'username' => 'auth.username.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Model Admin (The User model is the same except for the table, 'users'):
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
public $timestamps = False;
protected $table = 'admins';
protected $fillable = [
'name', 'username', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
Controller admin:
public function auth(Request $request) {
$credentials = $request->except('_token'); // "username" => "ewfer" "password" => "fwerfwegf"
if(!Auth::guard('admin')->attempt($credentials)) { // always enters here, even with the right details
Session::flash('flash_error', 'Something went wrong with your login');
return redirect(url('/admin/login'));
}
return redirect('/admin');
}
Default of my admins table:
Schema::create('admins', function (Blueprint $table) {
$table->increments('username');
$table->string('password');
$table->rememberToken();
});
DB::table('admins')->insert([
'username' => 'miguel',
'password' => Hash::make('password'),
]);
Note that for the Admin login we need the username, instead of the email which is used for the users login.
Well i discovered the problem, it was a very stupid one, sorry about that. The problem was this line $table->increments('username'); and i didn't notice what were being stored in BD, it was an int (1) instead of "miguel". Apart from that everything worked perfectly

Categories