Controller middleware - laravel

I have controller named 'AdminController'
And I have a lot of functions in there. The problem is that I dont want in every function user IF statement just like this:
public function index(Request $request)
{
if(Auth::check() && $request->user()->is_admin())
{
return view('admin.index');
}
else
{
flash()->error('You dont have permissions!');
return redirect('home');
}
}
How can I make it more simple with middleware so I could make everything work without using IF statement in every function ?

Create a middleware
php artisan make:middleware IsAdmin
Customize app/Http/Middleware/IsAdmin.php
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
class IsAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::check() && $request->user()->is_admin())
{
return $next($request);
}
flash()->error('You dont have permissions!');
return redirect('home');
}
}
Finally register and use the middleware

Related

Prevent login to user and custom guards at the same time

I am using a custom guard for a different type of user using a custom guard labelled business_user.
I have noticed I am able to login to as both normal users (web) and my business_users.
I've read in the Pusher documentation that I used to create my custom guards in the first place to add additional middleware into my "LoginController".
But I don't actually even have a LoginController, I've created my own controllers for each user type. AuthController (for web) and BusinessController (for business_user).
I have created a third controller labelled LoginController with the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:business_user')->except('logout');
}
}
I also updated my RedirectIfAuthenticated as follows:
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "business_user" && Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
I also have a RedirectIfAuthenticated middleware inside my Middleware folder.
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
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)
{
if ($guard == "business_user" && Auth::guard($guard)->check()) {
return redirect('/dashboard');
}
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
When I land on my user login page, it still allows me to attempt logging in. Can someone tell me how to resolve this?
In LoginController, you can override authenticated method.
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
auth()->login($user); // this method will login with default guard
return redirect()->intended($this->redirectPath());
}
I think because the order of middleware
<?php
public function __construct()
{
$this->middleware('guest')->except('logout'); // this procress first and redirect to login page
$this->middleware('guest:business_user')->except('logout');
}
So, I think you can check directly in __construct() of LoginController or in login view (blade file)
#if (Auth::check('business_user'))
You are already logged in (or perform a redirect somewhere)
#else
//display login form
#endif

Can't access user object

I am trying to handle roles in my application but I have a problem: when I clear cache or logout from the app and log in again I want to be redirected to the login but it sends me the following error
Trying to get property 'rol' of non-object.
<?php
namespace App\Http\Middleware;
use Closure;
class Admin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::user()->rol == 'Admin') {
return $next($request);
}
return redirect()->guest('login');
}
}
you have to check if user is logged in, and then ask if user have rol
use Illuminate\Support\Facades\Auth;
public function handle($request, Closure $next)
{
if (Auth::check()) {
if (Auth::user()->rol == 'Admin') {
return $next($request);
}
return redirect()->guest('login');
}
return redirect()->guest('login');
}

How to fix "Laravel redirect to the same login page" and middleware return false all time?

Work in the server (same code) but in localhost, it returns false always I have tried many ways.
I have tried Laravel build-in function login and so far the result always returns false while debugging.
//Middleware RedirectIfAdmin
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAdmin
{
/**
* 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)
{
$auth=Auth::guard('admin');
if (Auth::guard($guard)->check()) {
return redirect('admin/dashboard');
}
return $next($request);
}
}
I will add other code also if needed please tell me I am a new to ask question here. Please guide me.
Can you add the code from where you are calling the method handle?
namespace App\Http\Middleware;
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAdmin
{
public function handle($request, Closure $next, $guard = 'admin')
{
if (Auth::guard($guard)->check()) {
return redirect('admin/dashboard');
}
return $next($request);
}
}

Auth After Middleware

I wish to authenticate the user after the request with my own middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Middleware\Authenticate;
class AuthenticateAfter extends Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string[] ...$guards
* #return mixed
*
* #throws \Illuminate\Auth\AuthenticationException
*/
public function handle($request, Closure $next, ...$guards)
{
$response = $next($request);
$this->authenticate($request, $guards);
return $response;
}
}
I extend Illuminate\Auth\Middleware\Authenticate and modify the handle method to run as after middleware.
It's then declared in my kernel and on the correct route.
But I always get kicked back to the page I was previously on after logging in.
I want to control the page I go to, so before the middleware kicks in I do:
$request->session()->put('url.intended', 'my-test-url');
But it fails to redirect to this route.
How can I get it to redirect to a custom route?
Try this,
public function handle($request, Closure $next, ...$guards)
{
$response = $next($request);
$this->authenticate($request, $guards);
return redirect('/your_page_path');
}
Just for reference, here what I use to authenticate a user:
public function handle($request, Closure $next)
{
if (auth()->user() && auth()->user()->type != 'admin')
{
return redirect('/unauthorized');
}
return $next($request);
}
Try with: return redirect('view') or return redirect()->to('/route')

Laravel multiple parameters in Route middelware not working

I have problem that using multiple parameters in my Route::middleware isn't working for me. I am trying to assign a specific route only accessible for a superuser and admin role.
When I just use:
role:superuser
it works fine, but when I add a second parameter like:
role:superuser,admin
it fails when I assign myself the admin role but still works for the superuser role.
I am confused so any help would be appreciated!
Here is my RoleMiddleware:
namespace App\Http\Middleware;
use Closure;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string $roles
* #return mixed
*/
public function handle($request, Closure $next, ...$roles)
{
$user = $request->user();
if ($user && $user->isSuperuser($roles)) {
return $next($request);
}
return redirect('/home')->withError('U heeft niet de juiste rechten!');
}
}
Here is my isSuperuser method in my User model:
public function isSuperuser(...$roles)
{
if ($roles) {
return $this->roles == $roles;
}
return $this->roles;
}
Last but not least my routes/web code for the middleware:
Route::get('/users', 'UsersController#index')->middleware(['role:superuser,admin']);
Btw: the method is called 'isSuperuser' but that's just a name. It also has to accept the admin role at some point.
use | instead of , like this:
Route::get('/users', 'UsersController#index')->middleware(['role:superuser|admin']);

Resources