Laravel 5.5 abort error when trying to authenticate middleware - php

When i try to login into my dashboard, my authentication works well without middleware, but when i apply middleware and try to login to the dashboard i get this.
Which this is linked to the my authenticate middleware file
Middleware/Authenticate.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(! Auth::User()) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated. You are not a User.'], 401);
}
abort(403, "You're not a User no permission bro");
}
return $next($request);
}
}
My route is followed by:
Route::get('/auth/signup','UserController#getRegister')->name('getRegister');
Route::post('/auth/signup', 'UserController#userRegister')->name('signup');
Route::post('/auth/signin','UserController#userLogin')->name('user.login');
Route::get('/auth/login', 'UserController#getLogin')->name('login');
Route::get('/', 'UserController#getHome')->name('home');
Route::get('/auth/logout', 'UserController#logOut')->name('logout');
Route::group(['middleware' => 'myauth'], function() {
Route::get('/dashboard', 'UserController#getDashboard')->name('dashboard');
});
Thanks in advance im beginning to think there is a bug because im following the laravel 5.5 practices.

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.

Get current authorised user in middleware

How can I get current user in middleware? Laravel 5.6
When I try to include class
use Illuminate\Support\Facades\Auth;
and then
Auth::user()
I just get null
Middleware
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class DebugbarMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
echo "<pre>"; var_dump(Auth::user()); echo "</pre>"; die();
return $next($request);
}
}
Authorization
$controller = new LoginController();
$request = new Request();
Auth::logout();
$request->setLaravelSession(session()->driver(session()->getDefaultDriver()));
$user = Auth::loginUsingId($id);
if ($user) {
$controller->authenticated($request, $user);
return $this->sendResponse(['messages' => 'User authorization successfully'], 'M User authorization successfully');
}
return $this->sendError('User not found!');
The global middleware stack runs prior to the session being started and authentication details being available.
Define this at the bottom of the 'web' group or in your route middleware.

laravel middleware not working as expected

I have created two middleware in order to protect user route and admin routes
my UserMiddleware looks like this
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
class UserMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->hasRole('user')) {
return $next($request);
}
throw new \Exception("Unauthorized");
}
}
and this is my Adminmiddleware
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use App\Role;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->hasRole('admin')) {
return $next($request);
}
throw new \Exception("Unauthorized");
}
}
Now what i want is when admin is logging in, i want a admin dashboard to open and when user is logging in, i want user dashboard to open, but now, it is redirecting me only to the admin route only when I try to login from user and admin, I have my user protected routes like this
Route::group(['middleware' => 'auth', 'user'], function () {
//all user routes
});
and admin protected routes
Route::group(['middleware' => 'auth', 'admin'], function () {
//all admin routes
});
and in my kernel.php, I have also added
'admin' => \App\Http\Middleware\AdminMiddleware::class,
'user' => \App\Http\Middleware\UserMiddleware::class,
and this is how I have validated a login in my controller
$loginData = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'confirmed' => 1
);
/*
* Checking against the record in database whether the email and password is valid
* Or the record exists in the database
*/
if (Auth::validate($loginData)) {
if (Auth::attempt($loginData)) {
return Redirect::intended('dashboard');
}
}
else {
// if any error send back with message.
Session::flash('error', 'Invalid Email/Password Combination');
return Redirect::to('login');
}
how can I make my middleware work and show admin dashboard when admin logs and user dashboard when user logs in. This has created a big problem for me.
First of all, if you want to show unauthorized users the login form, your middleware should redirect to login form. In order to have it, replace
throw new \Exception("Unauthorized");
with
return redirect(route('login'));
Secondly, your login controller should redirect users to the dashboard corresponding to their roles. In order to get the proper redirect, replace
if (Auth::attempt($loginData)) {
return Redirect::intended('dashboard');
}
with
if (Auth::attempt($loginData)) {
return Redirect::intended(Auth::user()->hasRole('admin') ? 'admin_dashboard' : 'user_dashboard');
}
The last issue is that you apply middleware to your routes incorrectly. If you want to apply multiple middlewares, you need to pass a list as middleware paramter. Replace
['middleware' => 'auth', 'user']
with
['middleware' => ['auth', 'user']]

Categories