Multi auth laravel 5.2, autentication not working - php

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

Related

Laravel Can't login the user after register

Laravel Can't log in the user after register
When I register a new User, it returns successful, but when I try to log in it just returns 'login email id or password invalid'. I can't figure out what's wrong. It's working on the first created account, and it does not work for newly created accounts
class CustomerController extends Controller
{
public function login(Request $request){
$user =new Customer;
$user->email =$request->email;
$user->password =Hash::make($request->password);
$credentials = $request->only('email', 'password');
if(Auth::attempt($credentials)) {
$user = Auth::user();
$data['token'] = $user->createToken('kla')->accessToken;
return response()->json([
'status' => true,
'data' => $data,
'message' => ''
]);
}
else
{
return response()->json([
'status' => false,
'data' => [],
'message' => 'login email id or password invalid'
]);
}
}
public function register(Request $request){
$user =new Customer;
$user->firstname =$request->firstname;
$user->lastname =$request->lastname;
$user->email =$request->email;
$user->password =Hash::make($request->password);
$user->country =$request->country;
$user->mobile =$request->mobile;
if($user->save()){
return response()->json([
'status' => true,
'data' => [],
'message' => 'User Registation Successfully'
]);
}
else{
return response()->json([
'status' => false,
'data' => [],
'message' => 'User Registation Faild'
]);
}
}
}
this is customer model
class Customer extends Authenticatable
{
use HasFactory, Notifiable ,HasApiTokens;
protected $fillable = [
'firstname',
'lastname',
'email',
'password',
'country',
'mobile',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
this is my Config/auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'Customers' => [
'driver' => 'eloquent',
'model' => App\Models\Customer::class,
'table' => 'customers',
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
None of your guards are setup to use this Customer model as none of them are using your Customers provider setup; which will be renamed to the lowercase version customers from here out. The 'provider' key for the guard would need to be customers in this case.
'guards' => [
...
'api' => [
'driver' => 'passport',
'provider' => 'customers',
'hash' => false,
],
],
'providers' => [
...
'customers' => [
'driver' => 'eloquent',
'model' => App\Models\Customer::class,
],
],
Also when making calls to the authentication system it will use the default guard unless told otherwise. So without specifying you are currently using the web guard. If you wanted to use the 'passport' driver, that the api guard is set to use, you would have to adjust the default or specify this:
Auth::guard('api')->....
In your config file you should define provider
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'customers',
],
'api' => [
'driver' => 'passport',
'provider' => 'customers',
'hash' => false,
],

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'.

Laravel 5.6 multi auth keeps on authenticating on default model

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')

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.

Laravel 5.2 need an example which implements default Authentication Drivers / "Multi-Auth". which needs lots of works right now as [duplicate]

This question already has answers here:
Can Anyone Explain Laravel 5.2 Multi Auth with Example
(3 answers)
Closed 3 years ago.
Authentication Drivers / "Multi-Auth"
as prior to release of laravel 5.2 it is stated that multi auth suppots out of the box. but there is no any example codes showing how to authenticate using different drivers with routes. So I need help setting up the multi-auth using default laravel 5.2
Create two new models: App\Admin and App\User. Update config/auth.php:
return [
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => 'App\User',
],
'admin' => [
'driver' => 'eloquent',
'model' => 'App\Admin',
],
],
'passwords' => [
'user' => [
'provider' => 'user',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
]
]
];
In kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
and in Route.php set below code and test
Route::get('/login', function() {
$auth = auth()->guard('admin');
$credentials = [
'email' => 'admin#gmail.com',
'password' => 'password',
];
if ($auth->attempt($credentials)) {
return redirect('/profile');
}
});
Route::get('/profile', function() {
if(auth()->guard('admin')->check()){
print_r(auth()->guard('admin')->user()->toArray());
}
if(auth()->guard('user')->check()){
print_r(auth()->guard('user')->user()->toArray());
}
});
Using the rajpurohit-dinesh example, we just need to finnish first step:
1:
Create an App\Admin model (on our app folder). Here is how should be your Authenticatable class.
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
Class Admin extends Authenticatable
{
//
}
2: Update config/auth.php.
return [
// This is the default guard used, not need to declare
// another guard here
'defaults' => [
'guard' => 'user',
'passwords' => 'user',
],
// Here we must to declare the guards, if we created the App\Admin
// class as first step, we don't need to create a custom guard
'guards' => [
'user' => [
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
// In this example we are using only 'eloquent' driver
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => 'App\User',
],
'admin' => [
'driver' => 'eloquent',
'model' => 'App\Admin',
],
],
'passwords' => [
'user' => [
'provider' => 'user',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
]
]
];
3: To test it, we can use our app\Http\Route.php file:
Route::get('/login', function() {
$auth = auth()->guard('admin');
$credentials = [
'email' => 'admin#gmail.com',
'password' => 'password',
];
if ($auth->attempt($credentials)) {
return 'Success';
} else {
return 'Not Success';
});
Thanks for answer HoLiC, it's working right now but can you try to implement it with classes what Laravel's bring on start? You just have to add routes:
Route::controller('/auth', 'Auth\AuthController');
Route::controller('/password', 'Auth\PasswordController');
and create form in resources/views/auth/login.blade.php from my post above. After this you can use routes laravel.dev/auth/login and laravel.dev/auth/logout
Starter auth mechanism doesn't working good and its not compatibile with multi auth. If you check you can login via laravel.dev/auth/login but only user(theres no any way to setup in AuthController or anyplace to use admins) and logout action not working. If you check this trait Illuminate\Foundation\Auth\AuthenticatesUsers you will see that this mechanims is unuseful right now for example logout method not defines anywhere provider admin:
Auth::logout(); // not working logout should be smth like Auth::guard($provider)->logout();

Categories