Laravel Authentication for multiple users - php

I have 4 types of users in my application and details are stored in 4 different tables, so how can I implement Laravel's Authentication?
Route::post('/adlogin', 'mainController#adminlogin');
Route::get('/sellerlogin', function () {
return view('seller.pages.login');
});
Route::post('/sellerlog_in', 'mainController#sellerlogin');

Use this as your controller
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//Use Dependencies
use Auth;
class AdminLoginController extends Controller
{
Middleware used here is admin which you have to create in config/auth.php
public function __construct()
{
$this->middleware('guest:admin', ['except'=>'logout']);
}
Create a view for your admin Login
public function showLoginForm()
{
return view('auth.admin_login');
}
public function login(Request $request)
{
//Validate the Form Data
$this->validate($request, [
'email'=>'required|email',
'password'=>'required|min:5'
]);
//Attempt to log the Admin In
$email= $request->email;
$password= $request->password;
$remember= $request->remember;
After Successfully login where you want to redirect like here I am redirecting
toadmin.dashboard
//If Successful redirect to intended location
if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password], $remember)) {
return redirect()->intended(route('admin.dashboard'));
}
//If Unsuccessful redirect back to login form with form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
/**
* Log the Admin out of the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function logout()
{
Auth::guard('admin')->logout();
return redirect()->route('admin.login');
}
}
After logout redirect back to login page
Make sure you are using right guard for right User. Create same functionality for more user types as you want create guards for them.
In config/app.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
],
As admin and admin-api created here create for your user types
Add providers
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
],
At last for resetting passwords use this.
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 10,
],
],
In http/middleware/redirectIfAuthenticated.php add this to your handle function
//Check for admin login guard
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
break;
}
You can add more cases for your user types.
This is all you want to create multi auth. As you created different table for different roles you have to follow this process.
Create LoginController for all user types or use your logic to log them in.
Add your guards for every user type in auth.php
Add your cases to RedirectIfAuthenticated

You can use the laravel-permission package.This package allows you to manage user permissions and roles in a database.

Related

Auth::Attempt(username,password) doesn't work

I am really new to laravel but had experience using PHP, I have this problem with the Auth::attempt() method. It seems that even thought $request->get() gets the value the attempt method doesn't work. I tried checking my Database Table using Schema::hasTable and yes it exists. I am not using the email and password instead I am using a username and password for the login.
LoginController.php
class LoginController extends Controller
{
public function login(){
return view('pages.login');
}
public function dashboard(){
return view('pages.dashboard');
}
public function checklogin(Request $request)
{
$rules = array(
'Username' => 'required|string|min:5',
'Password' => 'required|min:6'
);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return Redirect::to('/login')
->withErrors($validator) // send back all errors to the login form
->withInput($request->except('Password')); // send back the input (not the password) so that we can repopulate the form
}else{
$userdata = array(
'Password' => $request->get('Password'),
'Username' => $request->get('Username')
);
if (Auth::attempt($userdata,true)) {
// validation successful!
echo 'SUCCESS!';
echo Auth::user()->FirstName;
} else {
// validation not successful, send back to form
echo "ERROR!";
}
}
//Just checking if the value was really been posted
echo $request->get('username').$request->get('password');
}
public function logout()
{
Auth::logout();
return redirect('/');
}
}
Here is the model I created
UsersInfo.php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Auth\Authenticatable as AuthAuthenticatable;
class UsersInfo extends Model implements Authenticatable
{
use AuthAuthenticatable;
protected $table = 'UsersInfo';
public $primaryKey = 'id';
protected $fillable = [
'Username','Password','MobileNum','AccountNum','FirstName','LastName','Address'
];
public function getAuthPassword(){
return $this->Password;
}
}
auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'UsersInfo',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'UsersInfo',
],
'api' => [
'driver' => 'token',
'provider' => 'UsersInfo',
'hash' => false,
],
],
'providers' => [
'Users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'UsersInfo' => [
'driver' => 'eloquent',
'model' => App\UsersInfo::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'UsersInfo' => [
'provider' => 'UsersInfo',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
'password_timeout' => 10800,
];
When passing the credentials to attempt the field holding the password must be named password (in this exact case). This is how the user provider knows what field in the credentials is supposed to be the password. The password is something that is checked after a record is found and is not part of the query.
$userdata = [
'password' => $request->input('Password'),
'Username' => $request->input('Username'),
];
Passwords are hashed, you can not directly compare this to the database value, the password field is not part of the query to find the user. Every thing else in the credentials array is a where condition.

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

How to perform multi auth in laravel?

I am trying to perform multi auth in my Laravel project. Initially I put it for user, then token is generated and its working fine. When I add employee too, then token is not generated for employee. When I remove for users and now employee is working but combinly both are not working.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
//'provider' => 'employees'
],
'api' => [
'driver' => 'token',
'provider' => 'users',
//'provider' => 'employees'
],
'employees' => [
'driver' => 'session',
'provider' => 'employees',
],
],
Can anyone please provide me help.Thanks.
In your auth.php file add providers in providers array for defined guards.
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
//'provider' => 'employees'
],
'api' => [
'driver' => 'token',
'provider' => 'users',
//'provider' => 'employees'
],
'employees' => [
'driver' => 'session',
'provider' => 'employees',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'employees' => [
'driver' => 'eloquent',
'model' => App\Employees::class,
],
],
If your as using 2 different model for authentication do like above. If you are using the same model to authenticate based on user role give the same model for employees and user.
create Route for employees login.
Route::get('/employee/login','Auth\EmployeeLoginController#showLoginForm')->name('employee.login');
Route::post('/employee/login','Auth\EmployeeLoginController#login')->name('employee.login.submit');
create EmployeeLoginController
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
class EmployeeLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:employee');
}
public function showLoginForm()
{
return view('auth.employee-login');
}
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('employee')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(route('employee.Product.list'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email'));
}
}
if you are using the 2 different model do like above. If you are using the same model to authenticate based on role just add the following check by role in the attempt method
attempt(['email' => $request->email, 'password' => $request->password, 'role' => 'employee'], $request->remember))
then in your app\Exception folder add the modify the unauthenticated methode in handler.php file
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = array_get($exception->guards(),0);
switch ($guard) {
case 'admin':
$login = 'admin.login';
break;
case 'employee':
$login = 'employee.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}
here actually you are $login variable is being used to redirect to the url you want if the user is not authenticated.
and last in your app\middleware\RedirectIfAuthenticated.php file remove the handle methode and add the following.
public function handle($request, Closure $next, $guard = null)
{
switch ($guard) {
case 'admin':
if (Auth::guard($guard)->check()) {
return redirect()->route('admin.index');
}
break;
case 'employee':
if (Auth::guard($guard)->check()) {
return redirect()->route('employee.dashboard');
}
break;
default:
if (Auth::guard($guard)->check()) {
return redirect('/');
}
break;
}
return $next($request);
}
Here you are redirecting the user if they are authenticated.
for better understanding check this video.This works in both 5.3 and 5.4 It will help you to understand how all these works.
Youtube link

Laravel 5.3 admin guard not working

I am trying to login from two different model using same login form. I have defined admin guard in config/Auth.php. But when I define admin guard in Foundation/AuthenticateUsers it checks the database table to validate the user but redirects back to same login form.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
Foundation/AuthenticatUsers
protected function guard()
{
return Auth::guard('admin');
}
public function login(Request $request)
{
$credentials = $this->credentials($request);
if (Auth::guard('web')->attempt($credentials, $request- >has('remember'))) {
return $this->sendLoginResponse($request);
}
elseif(Auth::guard('admin')->attempt($credentials, $request->has('remember')))
{
return $this->sendLoginResponse($request);
}
}
Admin guard redirects to login page because of middleware auth, i think you need to do something like this
public function __construct()
{
$this->middleware('auth:admin');
}
Read this Protecting Routes, part "Specifying A Guard"

How to use multi Auth in laravel 5.2 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Does anyone know how to use multi authenticate in laravel 5.2 ! I want to use It but I don't know how ?
does anyone has a tutorial or project setting up multi authentication?
You need two tables users and admins
Run command following command to create built in auth
php artisan make:auth
Two models Users(Already exist) and Admin
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
}
Now open config/auth.php and make the following changes
'guards' => [
'web' => [
'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' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
Create a new Middleware RedirectIfNotAdmin
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
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('/admin/login');
}
return $next($request);
}
}
Changes in Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
//\Illuminate\Session\Middleware\StartSession::class,
//\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
Create a new folder Http/Controller/Adminauth and copy the files from Http/Controller/Auth folder
Open the file Http/Controller/Adminauth/AuthController.php and make the following changes
<?php
namespace App\Http\Controllers\Adminauth;
use App\Admin;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (Auth::guard('admin')->check())
{
return redirect('/admin');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
public function resetPassword()
{
return view('admin.auth.passwords.email');
}
public function logout(){
Auth::guard('admin')->logout();
return redirect('/admin/login');
}
}
Create new folder Http/Controller/admin, copy Controller.php file in the folder from Http/Controller/
create new file Http/Controller/admin/employee.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Auth;
use App\Admin;
class Employee extends Controller
{
public function __construct(){
$this->middleware('admin');
}
public function index(){
return view('admin.home');
}
}
move to resources/views create new folder resources/views/admin
copy
resources/views/auth, resources/views/layouts & resources/views/home.blade.php
and post into resources/views/admin and open the each file in admin folder and add admin before each path, Now the path should look like
#extends('admin.layouts.app')
and your Http/routes.php look like
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin/login','Adminauth\AuthController#showLoginForm');
Route::post('/admin/login','Adminauth\AuthController#login');
Route::get('/admin/password/reset','Adminauth\PasswordController#resetPassword');
Route::group(['middleware' => ['admin']], function () {
//Login Routes...
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', 'Admin\Employee#index');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController#index');
});
Thats it open your site in browser and check
and for admin yoursiteurl/admin
Enjoy....
First, we create two models: user and admin
Then, we update the config/auth.php file:
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,
]
]
];
Now, modify the app/Http/kernel.php file:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class
];
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class
],
'api' => [
'throttle:60,1',
],
];
Create LoginController and set the following code in it.
Note: You have to create login pages for 'user' as well as 'admin'. You then have to submit login form requests to the appropriate controller function i.e. userLogin() or adminLogin().
namespace App\Http\Controllers;
use Auth, Input;
use App\User;
use App\Admin;
class LoginController extends Controller
{
public function userLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('user');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('user.login');
}
}
public function adminLogin(){
$input = Input::all();
if(count($input) > 0){
$auth = auth()->guard('admin');
$credentials = [
'email' => $input['email'],
'password' => $input['password'],
];
if ($auth->attempt($credentials)) {
return redirect()->action('LoginController#profile');
} else {
echo 'Error';
}
} else {
return view('admin.login');
}
}
public function profile(){
if(auth()->guard('admin')->check()){
pr(auth()->guard('admin')->user()->toArray());
}
if(auth()->guard('user')->check()){
pr(auth()->guard('user')->user()->toArray());
}
}
}
In most cases I just add a field to the user table called usertype and pass appropriate values like 0=admin, 1=user etc.
This approach helps in avoiding the unnecessary headache of creating different user roles or types.
Though this may not sound ideal, but helps in saving lots of time.

Categories