Laravel 5 Add another parameter to check on login - laravel

I'm using Laravel 5.3 and I used the make:auth to scaffold the registration/login system. I was wondering how do I add another parameter to check on the login, besides checking if the username and password correspond to the matching DB row?
EDIT: I tried looking online and I found I could change it in the Auth::Attempt line but those are all for Laravel 5.2 and below. The LoginController has this:
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
From what I understand, that redirects to the middleware RedirectIfAuthenticated, but then that middleware is like this:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
I'm almost sure I have to add a custom guard, but even at the docs I looked online, it was kinda confusing.. Anybody have a link that explains this really well? Or maybe a sample code?

Yes, you could do it by overriding a AuthenticatesUsers's credentials() method in your LoginController.php
use Illuminate\Http\Request;
protected function credentials(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$credentials['active'] = 1;
return $returnArray;
}
This example is of most common use case where user can login only if his account is active.
If you want to use other table instead of users, you need to customize guard
Add one in config/auth.php
'guards' => [
'user' => [
...
],
'customer' => [
'driver' => 'session',
'provider' => 'customers',
],
],
...
'providers' => [
'users' => [
...
],
'customers' => [
'driver' => 'eloquent',
'model' => App\Customer::class,
],
],
And then, add this in your LoginController.php
use Illuminate\Support\Facades\Auth;
protected function guard()
{
return Auth::guard('customer');
}
As specified in docs, you can use the same in RegisterController and ResetPasswordController as well.

Related

custom auth of two different users using two tables. i don't want to use make:auth

The first auth system works very fine its code is below and needed to have to different users using two different tables am using laravel 5.5
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;
class StudentController extends Controller
{
public function Register(Request $request)
{
$firstname = $request['firstname'];
$othername = $request['othername'];
$email = $request['email'];
$password = $request['password'];
$user = new User();
$user->firstname = $firstname;
$user->othername = $othername;
$user->email = $email;
$user->password = $password;
$user->save();
Auth::login($user);
return redirect()->route('studentDashboard');
}
public function Login(Request $request)
{
if(Auth::attempt(['email'=> $request['email'], 'password'=>
$request['password']]))
{
return redirect()->route('studentDashboard');
}
return redirect()->back();
}
}
i duplicated the above to create auth for a different user.The registration works but the login does not work even if the login data is right it returns the redirect back after the if statement
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Employer;
use Illuminate\Support\Facades\Auth;
class EmployerController extends Controller
{
public function createEmployerAccount(Request $request)
{
$companyName = $request['companyname'];
$companyEmail = $request['email'];
$companyPasword = $request['password'];
$Employer = new Employer();
$Employer->companyname = $companyName;
$Employer->email = $companyEmail;
$Employer->password = $companyPasword;
$Employer->save();
Auth::login($Employer);
return redirect()->route('employersDashboard');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
when i try to change the 'email' to 'emails' an error is shown->the select query is from the users table not employers table that i need to get data from and also when i change 'password' to 'passwords' an error "undefined index password" is shown
this is the route file content
Route::get('/',function(){
return view('pages.index');
})->name('home');
Route::post('/signup',[
'uses'=>'StudentController#Register',
'as'=> 'signup'
]);
Route::post('/signin',[
'uses'=>'StudentController#Login',
'as'=>'signin'
]);
Route::get('/employers',[
'uses'=>'PageController#employersPage',
'as'=>'employers'
]);
Route::get('/studentDashboard',[
'uses'=>'PageController#getStudentDashboard',
'as'=> 'studentDashboard'
]);
Route::post('/createcompany',[
'uses'=>'EmployerController#createEmployerAccount',
'as'=>'createcompany'
]);
Route::post('/signInEmployer',[
'uses'=>'EmployerController#signInEmployer',
'as'=>'signInEmployer'
]);
Route::get('/employersDashboard',[
'uses'=>'PageController#getEmployersDashboard',
'as'=> 'employersDashboard',
'middleware'=>'auth:employer'
]);
Route::post('/createPost',[
'uses'=>'PostController#postCreatePost',
'as'=> 'createPost'
]);
You need to tell Auth to use different Guard for authentication at time of Employer login. To define guards for Employer change like this in your config/auth.php.
Look for guards section in auth.php and add your new guard
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'employer' => [
'driver' => 'session',
'provider' => 'employers',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
Now in the same file there is a providers section. You need to add employers provider
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
//Employer provider
'employers' => [
'driver' => 'eloquent',
'model' => App\Employer::class,
],
],
Create a custom Auth middleware
namespace App\Http\Middleware;
use Closure;
use Auth;
class AuthenticateEmployer
{
public function handle($request, Closure $next)
{
//If request does not comes from logged in employer
//then he shall be redirected to employer Login page
if (!Auth::guard('employer')->check()) {
return redirect('/signInEmployer');
}
return $next($request);
}
}
Register custom auth middleware in Kernal.php in routeMiddleware
'employerAuth' => \App\Http\Middleware\AuthenticateEmployer::class,
Now we have setup our custom guard and custom middleware employerAuth
EmployerController
class EmployerController extends Controller
{
//either you have to define this or you can use `Auth::guard('employer')->attempt($credentials)` in login
protected function guard()
{
return Auth::guard('employer');
}
public function signInEmployer(Request $request)
{
if(Auth::attempt(['email'=>$request['email'],
'password'=>$request['password']]))
{
return redirect()->route('employersDashboard');
}
return redirect()->back();
}
}
For all the routes protected by Employer auth, you either need to add middleware employerAuth in routes or add employerAuth in each controller construct like this
public function __construct()
{
$this->middleware('employerAuth');
}
Hope it may help you. For details you can check this https://laravel.com/docs/5.6/authentication#authenticating-users
Check this nice sample app for multi auth application https://github.com/yskoverride/Various2.0/tree/master/app

How to create multi auth in laravel 5.6?

I used to be for laravel 5.5 and earlier than https://github.com/Hesto/multi-auth .
But this repository don't update for laravel 5.6.
How to create multi auth in Laravel 5.6?
After lots of digging and lots of questions & answers I have finally managed to work Laravel 5.6 Multi Auth with two table, So I'm writing Answer of my own Question.
How to implement Multi Auth in Larvel
As Mentioned above.
Two table admin and users
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
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'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');
}
}
That's all needed to make it working and also to get json of authenticated admin use
Auth::guard('admin')->user()
We can access authenticated user directly using
Auth::user()
but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()

RequestGuard::attempt does not exist

I am trying multiguard authentication for api when i login for admin i am getting
following error
BadMethodCallException
Method Illuminate\Auth\Req
uestGuard::attempt does not exist.
here is my login method in controller
public function login(Request $request){
if(Auth::guard('admin-api')->attempt(['email' => request('email'), 'password' => request('password')]))
{
// if successful, then redirect to their intended location
$user = Auth::guard('admin-api');
$success['token'] = $user->createToken('admin')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
my api.php
Route::prefix('admin')->group(function () {
Route::post('login', 'API\Admin\AdminController#login')->name('admin.login');
Route::post('register', 'API\Admin\AdminController#register')->name('admin.register');
Route::group(['middleware' => 'auth:admin-api'], function(){
Route::post('get-details', 'API\Admin\AdminController#getDetails');
});
});
my admin model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class Admin extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $table = 'admin';
protected $guard = 'admin-api';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
please tell me any other inputs you want
A better hack is this
$credentials = ['email' => $request->username, 'password' => $request->password];
//Since we are not using guard web in API request, we have to add it here (
// guard('web') ) to access the Auth::attempt function,
// the Auth::attempt needs web guard and crsf token, but using it here bypasses
// the post with crsf.
if (Auth::guard('web')->attempt($credentials, false, false)) {
dd('user is OK');
}else{
dd('user is NOT OK');
}
Unfortunately the Laravel Facade for Auth does not expect you to use it for the api guard since sessions and cookies will be set, Thus does not support ->attempt() function. But the API middle-ware disables session and cookies since it is stateless. So here is the hack.
Get to your confi\auth and create a similar web instance for your api guards thus
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'drivers-web' => [
'driver' => 'session',
'provider' => 'drivers',
],
'api' => [
'driver' => 'passport',//previously "token"
'provider' => 'users',//This will be switched regularly from the middleware between drivers and users
],
'drivers-api' => [
'driver' => 'passport',//previously "token"
'provider' => 'drivers',
],
],
Never the less, You can use passport to generate your client access tokens which are stateless sessions. And also serve well for authentication.
you cannot use Auth::guard('admin-api')->attempt with a guard with driver value is token or passport so you can repeat the guard and make one with session driver and the second one with passport then you can use the session one to make difference between earch other you can see a reference and source code from here https://web-brackets.com/discussion/103/method-illuminate-auth-requestguard-attempt-does-not-exist-
To me, I changed drivers for the web from passport to session. Laravel's cache had to be cleared to be able to go back to the session driver
php artisan cache:clear

creating a custom authentication system in laravel

How can I build an authentication system for customer?
I have used laravel built in authentication system for my admin panel where built in user model and users table already used.
Now I want to build another authentication system for my customer where customer model and customers table will be used.
How can I do this in laravel 5.2 ?
How to implement Multi Auth in Larvel 5.2
As Mentioned above. Two table admin and users
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
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'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');
}
}
That's all needed to make it working and also to get json of authenticated admin use
Auth::guard('admin')->user()
Edit - 1
We can access authenticated user directly using
Auth::user() but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()

How to Create Multi Auth in Laravel 5.2

I have made multi auth but i have problem with final code. I have code like this
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
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'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');
}
}
And what does this code mean Auth::guard('admin')->user() ? And where must i type that code?
And what does this code mean Auth::guard('admin')->user() ?
In simple word, Auth::guard('admin')->user() is used when you need to get details of logged in user. But, in multi auth system, there can be two logged in users (admin/client). So you need to specify that which user you want to get. So by guard('admin'), you tell to get user from admin table.
Where must i type that code?
As from answer, you can understand that where must you use it. But still I can explain with example. Suppose there are multiple admins. Each can approve users request (like post/comments etc). So when an admin approve any request, then to insert id of that admin into approved_by column of post, you must use this line.

Resources