multiple authentications on laravel - php

I have built in laravel an authentication system on user table.
I have to make two login pages for admin and normal user on same users table.
I have use spatie roles and permission but it does not stop admin login from normal user login page and vice versa.
I have add checkmaster middleware just for accepting my question on stackoverflow.
namespace App\Http\Middleware;
use Closure;
class CheckMaster
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::user()->hasRole('master')) {
return $next($request);
}
return redirect('home');
return $next($request);
}
}

The middleware is working only when user try to go in certain route.
Therefore, the middleware CheckMaster only takes place when logon user tried to go in certain route.
If you are implementing with Auth\LoginController.php, you can override the function authenticated when user is authenticated, example code:
protected function authenticated(Request $request, $user)
{
if ($user->hasRole('master')) {
return redirect('master-home');
}
return redirect('home');
}

Related

middleware keeps directing me to the login page

I'm working on a website where I have designed an authentication system. The client logs in through email and password. If it is correct it should proceed to the dashboard and should not be able to go back to the login page as long as he/she is logged in. However, middleware keeps directing to the login page saying that 'you have to login first'. Both middleware are registered properly in kernel.php
Kernel.php
protected $routeMiddleware = [
'alreadyLoggedIn' => \App\Http\Middleware\AlreadyLoggedIn::class,
'isLoggedIn' => \App\Http\Middleware\AuthCheck::class ];
Web.php
Route::post('/signin', [customAuthController::class,'loginClient']);
Route::get('/client',[customAuthController::class,'dashboard'])->middleware('isLoggedIn');
Route::get('/signin', [customAuthController::class, 'login'])->middleware('alreadyLoggedIn');
Route::get('/sign_up',[customAuthController::class,'registration'])>middleware('alreadyLoggedIn');
AlreadyLoggedIn (1st Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AlreadyLoggedIn
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId')&& (url('signin')==$request->url()|| url('sign_up')==$request->url()))
return $next($request);
return back();
}
}
IsloggedIn (2nd Middleware)
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class AuthCheck
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* #return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Session()->has('loginId'))
return redirect('signin')->with('fail','You have to login first');
return $next($request);
}
}
customAuthCheck Controller
class customAuthController extends Controller
{
public function dashboard(){
$data = array();
if(Session::has('loginId')){
$data = client::where('id','=',Session::get('loginId'))->first();
}
return view('auth.client', compact('data'));
}
public function logout(){
if(Session::has('loginId')){
Session::pull('loginId');
return redirect('signin');
}
}
}
https://github.com/faaiz99/web-tech-project
In your AuthCheck class (as you named it isLoggedIn in your kernel) first condition is not what you really want to check .
you want to redict user to login if hes not already logged in .
so condition should be something like :
if(!Session()->has('loginId'))
{
return redirect('signin')->with('fail','You have to login first');
}
addition : Its really better if you use laravel auth .
i strongly suggest you to see laravel auth docs
with laravel authentication you can simply use auth facade in your middleware and that would be something like :
if(!auth()->check())
{
return redirect('signin')->with('fail','You have to login first');
}
Hope that helps .

I get redirected to login page every time i try to access the admin dashboard page

When I'm logged as Admin( I'm setting a column which has utype="ADM" to verify me as admin in a session).And when I try to access the admin dashboard page I get redirected to login page and so on without accessing the dashboard eventually.
This is my AuthAdmin.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class AuthAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
if(session('utype') === 'ADM') {
return $next($request);
}else{
session()->flush();
return redirect()->route('login');
}
return $next($request);
}
}
This is my web.php:
Route::middleware(['auth:sanctum', 'verified', 'authadmin'])->group(function() {
Route::get('/admin/dashboard',AdminDashboardComponent::class)->name('admin.dashboard');
I think the issue is mainly focused on the 'authadmin' argument in the route , please provide some tips and help .Thank you

Laravel redirect based on role - spatie/laravel-permission

I am using this package spatie/laravel-permission and what I want to do is:
super-admin, admin, members have the same login and after logged in it redirect to different routes.
The super-admin and admin have the same redirect. So I put this code.
//app\Http\Controllers\Auth\LoginController.php
protected function authenticated(Request $request, $user)
{
if ( $user->hasAnyRole(['super-admin', 'admin']) ) {// do your margic here
return redirect()->route('admin.dashboard');
}
return redirect('/home');
}
and then this is my routes
//routes/web.php
Auth::routes();
Route::group(['middleware' => ['role:member']], function () {
Route::get('/', 'HomeController#index')->name('home');
});
Route::group(['middleware' => ['role:super-admin|admin'], 'prefix' => 'admin'], function () {
Route::get('/', 'Admin\HomeController#dashboard')->name('admin.dashboard');
});
After login, what I want to do is when a super-admin/admin visit the site.com/* it should redirect to site.com/admin/ cause he is not authorize cause he is not a member and also when a member visit the site.com/admin/*, he redirect to site.com/ cause he is not admin/super-admin, the rest will go to login page when not authenticated.
It displays like this,
It should redirect based on their role homepage instead display 403 error.
Well, based on the package's middleware, there's no redirection logic involved. It is just checking if it has the correct permissions and throwing an unauthorized exception if the user does not.
You would need to write your own custom middleware, where you will check whether the user has the appropriate roles and to redirect to the appropriate url. A very simplistic example would be something like this (in the case of an admin).
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class CheckIfAdmin
{
/**
* 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)
{
if ( $user->hasAnyRole(['super-admin', 'admin']) ) {
return $next($request);
}
return redirect('/');
}
}
You would then attach this middleware instead of the other one.

Laravel 5.5 Multi-Auth not redirecting when authenticated

I'm creating a multi auth system in laravel where there is two types of users: Admins(created by me) and Users(using the native laravel auth system).
If I login as a User, when I try to access the login page when I'm already logged in, it redirects me back to the dashboard but If I login as an Admin, when I access to the Admin login page again, it let's me login again despite being already logged in as an Admin.
Here is my code for the class RedirectIfAuthenticated:
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 'admin':
if(Auth::guard($guard)->check())
{
return redirect()->route('admin.dashboard');
}
break;
default:
if(Auth::guard($guard)->check())
{
return redirect('/home');
}
break;
}
/*
if (Auth::guard($guard)->check())
{
return redirect('/home');
}
*/
return $next($request);
}
}
Can someone explain me what is happening?
Can you show the routes you've registered that are meant to be protected for admins? By default when you use the auth middleware it's going to use the default auth guard - not your admin one.
When you register routes you want to protect with the admin guard you will need to do it slightly differently. Either by using a route group or the middleware method in a controller.
// Cover a block of routes...
Route::group(['middleware' => 'auth:admin'], function () {
//
});
// Or do it in your controller...
class PageController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
}

laravel how to make middleware redirect

I have create form for user to comment in my post but I want need check Auth has Login before submit the form. How can i do that ?
For me I have use middleware to protect it, But If use not login it redirect to Login Form when user has been login it is not redirect back to posts route/show-posts/{post},It redirect to back to route/comments . How can i solve this ?
URL Show Single Post
Route::get( '/show-post/{post}', 'HomePageController#single_show')
->name('home.post.show' );
URL form Comments form
Route::resource('/comments', 'CommentsController');
CommentsController
public function __construct() {
$this->middleware( 'auth')->except(['index', 'show']);
}
You can create a middleware class and redirect like so:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectToComments
{
/**
* 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)
{
if (Auth::check()) {
return redirect()->route('comments');
}
return $next($request);
}
}
That is the general form of redirection through middleware, simply modify which route to redirect to or add more conditional logic as needed.

Categories