I'm trying to configure the laravel's auth to fit with my db.
But whatever I do, override properties like protected $table='my_table'; or public function username() { return 'email_user'} in LoginController, it ignore everything.
Does anyone know how to parameter the auth of laravel with different database ?
Here is what I changed in LoginController:
public function username()
{
return 'email_user';
}
And in the User model :
protected $table = "pays";
protected $primaryKey = "id_user";
public function getAuthPassword() {
return $this->password_user;
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name_user', 'surname_user', 'email_user', 'password_user', 'sex_user', 'birth_user', 'address_user',
'city_user', 'pc_user', 'phone_user', 'pic_user', 'status_user', 'license_user', 'urssaf_user',
'remember_token', 'created_at', 'updated_at',
];
EDIT : config/auth.php :
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
LoginController :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
public function username()
{
return 'email_user';
}
}
In your login form keep password field with name=password:
<input type="text" name="email_user">
<input type="password" name="password">
Related
i am trying to create a multiple authentication in Laravel 7 with custom guards and when i try to login am getting this error "SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'where clause' (SQL: select * from admins where email = mukamba#gmail.com and 0 is null limit 1)"
My auth.php in config
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
My adminLoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use auth;
class AdminLoginController extends
Controlle
r
{
public function __construct()
{
$this->middleware('guest:admin');
}
public function showLoginForm()
{
return view('auth.admin-login');
}
public function login(Request $request)
{
// validate the data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// attempt user to login
if(auth::guard('admin')->attempt(['email' => $request->email, 'password'=> $request->password, $request->remember])){
//if susscefull redirect to the intended location
return redirect()->intended(route('admin.dashboard'));
}
// if unsuccesfull return to the page they were
}
}
My Admin model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'job_title',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
LoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
The problem is somewhere in your password when you are passing it.
select * from admins where email = mukamba#gmail.com and 0 is null limit 1) I gues that you are getting this error when trying to log in. Check out Login controller and see the parameters that you are passing. Or drop the controller here so we can provide more info.
The attempt function was supposed to be like this
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->get('remember'))) { return redirect()->intended(route('admin.dashboard'));
}
I want to Multi Auth with single table in laravel 5.2.
I tried this way. But frontend login working.
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
return [
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'database',
'table' => 'user',
'model' => App\User::class,
],
'admin' => [
'driver' => 'database',
'table' => 'user',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController
e.g.,
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class AdminController extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
In your AdminAuth/AuthController.php.
public function guard()
{
return auth()->guard('admin');
}
and instead of give table name inside providers put protected $table = 'users' in your Admin model.
You can see this for further more details: https://scotch.io/#sukelali/how-to-create-multi-table-authentication-in-laravel
You don't need to use a guard here, Instead; you can use middleware here. Add a user type column here in user table and then create middleware for that.
I'm trying to create multi login in laravel 5.6 and this error appeared, can anyone help me?
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Type error: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must be an instance of Illuminate\Contracts\Auth\UserProvider, null given, called in C:\wamp64\www\Laravel\Sistema\oficial\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 123
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Route;
use Illuminate\Support\Facades\Auth;
class EmployeeLoginController extends Controller
{
public function __construct()
{
$this->middleware('auth:employee');
}
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (Auth::guard('employee')->attempt($credentials)) {
return redirect()->intended(route('admin.dashboard'));
}
return redirect()->back()->withInput($request->only('email', 'remember'));
}
}
guard:
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'employee' => [
'driver' => 'session',
'provider' => 'employees',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'employee' => [
'driver' => 'eloquent',
'model' => App\Employee::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
ReditectIfAuthenticated
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'employee':
if (Auth::guard($guard)->check()) {
return redirect('/dashboardemployee');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
break;
}
return $next($request);
}
}
model:
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Employee extends Authenticatable
{
protected $guard = 'employee';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'photo',
'status',
'connect_email',
'connect_senha',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
The provider is named wrong:
'employee' => [
'driver' => 'eloquent',
'model' => App\Employee::class,
],
should be
'employees' => [
'driver' => 'eloquent',
'model' => App\Employee::class,
],
I am learning laravel and i decided to make a custom authentication in laravel . I could register my users but when i try to login i get this error ?
Type error: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given,
These are my resources
My AdminUser Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable as AuthenticableTrait;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
class AdminUser extends Eloquent implements AuthenticatableContract,AuthorizableContract
{
public $table = "admin_users";
use Notifiable;
use AuthenticableTrait;
use Authorizable;
protected $fillable = [
'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My AdminUserController
<?php
namespace App\Http\Controllers;
use App\AdminUser;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Requests\LoginRequest;
use App\Http\Requests\RegisterRequest;
use Auth;
use Response;
class AdminUserController extends Controller {
use AuthenticatesUsers;
/**
* the model instance
* #var AdminUser
*/
protected $user;
/**
* The Guard implementation.
*
* #var Authenticator
*/
protected $admin;
/**
* Create a new authentication controller instance.
*
* #param Authenticator $admin
* #return void
*/
public function __construct(Guard $admin, AdminUser $user)
{
$user = AdminUser::first();
Auth::login($user);
$this->middleware('admin', ['except' => ['getLogout']]);
}
/**
* Show the application registration form.
*
* #return Response
*/
public function getRegister()
{
return view('admin/admin_users/register');
}
/**
* Handle a registration request for the application.
*
* #param RegisterRequest $request
* #return Response
*/
public function postRegister(RegisterRequest $request)
{
AdminUser::create([
'email' => $request->email,
'password' => bcrypt($request->password),
]);
return redirect('backend-admin/dashboard');
}
/**
* Show the application login form.
*
* #return Response
*/
public function getLogin()
{
return view('admin/admin_users/login');
}
/**
* Handle a login request to the application.
*
* #param LoginRequest $request
* #return Response
*/
public function postLogin(LoginRequest $request)
{
if (Auth::guard('admin')->attempt($request->only('email', 'password')))
{
return redirect()->intended('/backend-admin/dashboard');
}
return redirect('/backend-admin')->withErrors([
'email' => 'The credentials you entered did not match our records. Try again?',
]);
}
/**
* Log the user out of the application.
*
* #return Response
*/
public function getLogout()
{
Auth::guard('admin')->logout();
return redirect('/backend-admin');
}
protected function guard()
{
return Auth::guard();
}
}
My VerifyAdmin Middleware
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Auth;
class VerifyAdmin
{
/**
* The Guard implementation.
*
* #var Guard
*/
protected $admin;
/**
* Create a new filter instance.
*
* #param Guard $auth
* #return void
*/
public function __construct(Guard $auth)
{
// dd($auth);
$this->admin = $auth;
}
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if ($this->admin->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('backend-admin');
}
}
return $next($request);
}
}
I also defined guards in auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Also defined middleware in kernel.php
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\VerifyAdmin::class,
Feel free to correct me if i am wrong anywhere or if i have missed anything .
I found what was bugging my program , i did defined guard function in my controller but forget to add the guard in function , i fixed it by defining guard.
I think the problem are those 2 lines:
$user = AdminUser::first();
Auth::login($user);
What's the point of running it? First of all, I see you have here login action and it seems you automatically login admin when on login page - it doesn't make much sense.
Also those 2 lines won't do anything that should be done I think - because when admin logs in, well you log him in so there's no point to login him in each request assuming you are using sessions.
You need to change the admin provider name from admin to admins.
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [ // ***this is the change that should be made***
'driver' => 'eloquent',
'model' => App\AdminUser::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
],
];
I'm trying to set up two authentication guards: internal (for normal browser requests) and api for AJAX requests. api is the default guard, but I'm focusing on getting the internal-guard to work, for now.
This is my config/auth.php:
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'clients',
],
'guards' => [
'internal' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'clients',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
This is my routes.php:
<?php
Route::group([
'domain' => 'internal.example.com',
'middleware' => ['web', 'auth:internal']
], function () {
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', 'HomeController#index');
});
Route::group([
'domain' => 'internal.example.com',
'middleware' => [ 'web']
], function () {
Route::match(['get', 'post'], '/login', 'InternalAuth\InternalAuthController#login');
Route::get('/logout', 'InternalAuth\InternalAuthController#logout');
});
This is InternalAuthController:
<?php
namespace App\Http\Controllers\InternalAuth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class InternalAuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $guard = 'internal';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Seems fine to me. But when I go to /, /home or /login in my browser, I end up in a redirect loop.
I'm missing something... Any ideas?
/login points to InternalAuth\InternalAuthController#login. login() is a method of Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers (used by InternalAuth), but it is not responsible for returning the view or responding to post requests. This is a job for getLogin and postLogin.
So, I needed to change this in the routes.php:
Route::match(['get', 'post'], '/login', 'InternalAuth\InternalAuthController#login');
To this:
Route::get('/login', 'InternalAuth\InternalAuthController#getLogin');
Route::post('/login', 'InternalAuth\InternalAuthController#postLogin');