Protecting Routes in Laravel 5.3 - php

I am trying to protect my routes in Laravel 5.3. I am using below codes
Route::get('profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
If I try to browse /profile in logout situation it redirects me to /login route. But I would like to redirect it to / route.
How can I do that ??

On laravel 5.3 it's on Exceptions directory. Go to App\Exceptions\Handler.php and on the bottom change the code:
return redirect()->guest('/');

change file app\Middleware\RedirectIfAuthenticated.php
and edit this line:
return redirect('/login');

public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
Please write this function in this file app\Middleware\RedirectIfAuthenticated.php

You can try
Route::group(['middleware'=>'web'],function (){
Route::Auth();
Route::get('/home', 'HomeController#index');});
and change app\Middleware\RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}

Related

Laravel 8.8 redirectTo function does't work

I need to implement logic when authorizing a user and I planned to do this in the redirectTo() function in the LoginController. However, Laravel does not seem to see it and always redirects to the HOME constant.
It seems that all files are correct.
LoginController
protected function redirectTo()
{
return redirect('/test');
}
auth-backend/RedirectsUsers
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect('/account');
}
}
return $next($request);
}
Some users have found that the redirect happens in the middleware/RedirectIfAuthenticated, but I don't know how to fix it. If in this file I replace return redirect(RouteServiceProvider::HOME) with some path, for example redirect('/account') then it returns /account. But I still need to be in the redirectTo() function.
Middleware/RedirectIfAuthenticated
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect('/account');
}
}
return $next($request);
}
How can I make the process come to redirectTo() after authorization?
Define a route in web.php for redirectTo function in Login Controller
Route::get('check-auth', [LoginController::class, 'redirectTo'])->name('auth.redirect-to');
return to the route
return redirect()->route('auth.redirect-to');
make sure to use the LoginController on the top of web.php

Handling Admin and User Authentication - Laravel

I have 2 two users (Admin and operators) for my system and i want to authenticate them to their various pages based on their roles. I am using the Authenticated.php middleware to achieve this job like below
but i get an error when trying to login with any of the users as
Call to undefined method Illuminate\Contracts\Auth\Factory::check()
What am i doing wrong please?
Authenticated.php
public function handle($request, Closure $next, ...$guards)
{
if(Auth::check()) {
if(Auth::user()->hasRole('administrator')) {
return redirect('/');
} else if (Auth::user()->hasRole('operator')) {
return redirect('client/dashboard');
}
}
// $this->authenticate($guards);
return $next($request);
}
Route.php
Route::group(['middleware' => ['auth']], function () {
Route::get('/', 'PagesController#dashboard');
});
Route::group(array('prefix' => 'client', 'namespace' => 'User', 'middleware' => ['auth']), function () {
Route::get('/dashboard', 'DashboardController#create');
});
Aren't you messing up with your if condition? Try the below code in your RedirectIfAuthenticated.php file in App\Http\Middleware. Hope that will resolve your problem.
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if(Auth::user()->hasRole('administrator'))
{
return redirect('/');
}
else
{
return redirect('client/dashboard');
}
}
return $next($request);
}
And Are you using Entrust for handling roles?

Restricting Access to Manager users - Laravel 5.5

I am a newbie with Laravel. I am doing a tutorial and i have issues on restricting access to manager users. I have been able to assign roles (manager and members) to my users at the moment. But my issue lies in the Manager Middleware.
If the user is a manager, it doesn't return the $next($request); but instead it routes to /home after authentication and if user isn't a manager, it routes to /home as well instead of /tickets.
There is a file called RedirectIfAuthenticated, i changed the route in there but the issue still remained the same.
So what am i missing to restrict access to my managers?
Manager middleware
public function handle($request, Closure $next)
{
if(!Auth::check())
{
return redirect('/login');
}
else{
$user = Auth::user();
if($user->hasRole('Manager'))
{
return $next($request);
}
else{
redirect('/tickets');
}
}
return $next($request);
}
Routes
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin', 'middleware' =>'manager'), function () {
Route::get('users', 'UsersController#index');
Route::get('users/{id?}/edit', 'UsersController#edit');
Route::post('users/{id?}/edit','UsersController#update');
Route::get('roles', 'RolesController#index');
Route::get('roles/create', 'RolesController#create');
Route::post('roles/create', 'RolesController#store');
});
Just do the following:
in the else part: instead of redirect('/tickets'); use return redirect('/tickets');
i.e. it will become:
public function handle($request, Closure $next)
{
if(!Auth::check())
{
return redirect('/login');
}
else{
$user = Auth::user();
if($user->hasRole('Manager'))
{
return $next($request);
}
else{
return redirect('/tickets');
}
}
return $next($request);
}
That's it

Laravel auth redirection

I have trouble redirecting after user authentication. I would like to redirect admin to admin panel, and user to home so I made admin middleware:
public function handle($request, Closure $next)
{
if (Auth::user() && Auth::user()->isAdmin()) {
return $next($request);
}
return redirect('/');
}
Routes for admin panel are:
Route::prefix('admin')->middleware(['web', 'admin', 'auth'])->group(function () {
Route::get('/', 'HomeController#index');
Route::resource('user', 'Admin\UserController');
});
I have User and Role models in a M-2-M relationship.
User model:
public function role(){
return $this->belongsToMany('App\Role');
}
public function isAdmin()
{
return ($this->role->first()->name == 'Admin') ? true : false;
}
Auth LoginController:
protected $redirectTo = '/admin';
Auth RedirectIfAuthenticated:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
Issue I'm having is that I always end up on home page. When watching through the inspector I noticed something strange, don't know if it is a standard procedure or not:
Login seems to be triggered twice? Route to /admin was triggered and got 200 OK status, but I never got to see it. If I manually enter it to the browser however, it will lead me to the admin dashboard.

Laravel - How to pass variables to middleware through route group?

This is my route group,
Route::group(['middleware' => 'checkUserLevel'], function () {
// my routes
});
And this is my middleware checkUserLevel,
public function handle($request, Closure $next, $level)
{
$user = Auth::user();
if ($user->level > $level) {
return redirect('testUrl');
}
return $next($request);
}
I want to pass the $level variale to middleware from route group.
Thanks.
You can simply pass multiple arguments into the middleware using a colon. Use it like:
Route::group(['middleware' => 'checkUserLevel:some_value_of_level'], function () {
// my routes
});
Now, you can have this value inside your $level variable.
public function handle($request, Closure $next, $level)
{
$user = Auth::user();
if ($user->level > $level) {
return redirect('testUrl');
}
return $next($request);
}
This would help.
Edit: 14 Dec 2018
You can also send multiple variables to middleware. You just need to seperate the values using a comma (,).
Route::group(['middleware' => 'checkUserLevel:some_value_of_level, one_more_value_to_send'], function () {
// my routes
});
And you will get the value one_more_value_to_send in the variable after $level in the middleware handler.
public function handle($request, Closure $next, $level, $another_value)
{
$user = Auth::user();
if ($user->level > $level) {
return redirect('testUrl');
}
return $next($request);
}
For more details you can refer to: Passing parameters to Middleware in Laravel 5.1
In Laravel 6.x you have to do this
add code like in your middleware
public function handle($request, Closure $next,$module=null,$right=null)
{
dd($module,$right);
return $next($request);
}
your route code like this
Route::get('/department/add', 'DepartmentController#addNew')->middleware('ManualSec:abc,xyz');
In Kernel.php register your middleware in the section of $routeMiddleware like
'ManualSec' => \App\Http\Middleware\ManualSec::class,
by calling the rout using url in my case
http://local.pms.com:8080/department/add
it will result is like:
now you can code in your middleware

Categories