Custom Filter for Laravel Route - php

I'm trying to make some custom filters for my Laravel application.
In filter.php I have
Route::filter('admin', function()
{
if (Auth::guest() AND ! Auth::user()->isAdmin()) {
return 'Not Authorized';
}
});
User.php model
public function isAdmin()
{
if($this->role==1) return true;
else return false;
}
And finally in the Route:
//SECTIONS ONLY FOR ADMIN
Route::group(array('prefix' => 'admins', 'before' => array('admin')), function(){
Route::get('/frontoffice', 'FrontofficeController#index');
Route::get('/frontoffice/about', 'FrontofficeController#about');
Route::get('/frontoffice/research', 'FrontofficeController#research');
});
I'm logged in as an Admin in my application, but still I'm getting NotFoundHttpException when I try to access the above URLs in the route.
Any idea why?

Related

Laravel 5.8 redirected you too many times, middleware problem

I have a signup route. After it register on step1, it emails to the user to verify his account and have a link on his email. After clicking the link, it should redirect to signup/step2, and finished and he can access the job-seeker/home.
so the logic is after finished the registration, user cannot visit again to signup/step2 cause user already finished fill up the form.
and before fillup signup/step2, he can't access also the job-seeker/home. So it's vice versa.
basically my middleware was first: check if the user completed the step2 and added true on column is_completed in database. then on the second middleware is to visit only his route by his role, he can't access other routes from other role and redirect to his home based on his role.
But it throws me too many redirect and switching both side even I still didn't fill up the step2 yet. this is my gif below.
MyCode
Kernel.php
class Kernel extends HttpKernel
{
...
protected $routeMiddleware = [
...
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'isCompleted' => \App\Http\Middleware\IsCompleted::class,
];
Middleware/IsCompleted.php
class IsCompleted
{
public function handle($request, Closure $next)
{
if(auth()->user()->isCompleted == 1){
return $next($request);
}
// if 0, redirect to step2
return redirect()->route('register.step2');
}
Middleware/RedirectIfAuthenticated.php
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if ( Auth::user()->hasRole('job-seeker') ) {
return redirect()->route('job-seeker.home');
} else if(Auth::user()->hasRole('admin')) {
return redirect()->route('admin.home');
}
}
return $next($request);
Routes/Web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::group(['middleware' => ['verified', 'isCompleted']], function() {
Route::group(['prefix' => 'admin', 'name' => 'admin.'], function() {
Route::get('/home', function(){ return "test"; })->name('admin.home');
});
Route::group(['prefix' => 'job-seeker', 'name' => 'job-seeker.'], function() {
Route::get('/home', 'Jobseeker\HomeController#index')->name('job-seeker.home');
});
});
Auth::routes(['verify' => true, 'register' => false]);
Route::get('signup/{usertype}' , 'Auth\RegisterController#getStep1')->name('register.step1');
Route::post('signup/{usertype}' , 'Auth\RegisterController#postStep1');
Route::group(['middleware' => ['auth']], function() {
Route::get('signup/step2' , 'Auth\RegisterController#getStep2')->name('register.step2');
Route::post('signup/step2' , 'Auth\RegisterController#postStep2');
});
EDIT 1
I inspect the page and go to network tab, and this is the result.
your RedirectIfAuthenticated keeps redirecting all the time. It doesn't ever get to $next($request) for Authenticated User.
You need to have some logic like
if (route is seeker.home and user can visit seeker.home) {
return $next(request);
}
instead of
return redirect()->route('job-seeker.home');

Restricting Users Using Middlewares - Laravel

I have two roles in my app admin and users. Both roles are using a middleware called auth. Now in the application, when i login as a admin, i am not able to route to user page (that is perfect).
But when i login as user, i am able to route to admin page but my auth must prevent the user from accessing the admin page. Currently, that is my issue... What am i not doing right?
Below is my code
AuthMiddleWare
if (Auth::check())
{
if(Auth::user()->roles->pluck('name')->first() == "admin")
{
// return $next($request);
return Redirect::to('/admin/dashboard');
}
else if(Auth::user()->roles->pluck('name')->first() == "user")
{
return Redirect::to('/user/dashboard/');
}
else{
return Redirect::to('login');
}
}
Route
Route::group(array('prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => ['auth']), function () {
Route::get('dashboard','Controller#show');
}
Route::group(array('prefix' => 'user', 'namespace' => 'User', 'middleware' => ['auth']), function () {
Route::get('dashboard','Controller#show');
}
Try the following code:
if (Auth::check())
{
if(in_aaray('admin', Auth::user()->roles->pluck('name')->all()))
{
// return $next($request);
return redirect('/admin/dashboard');
}
else if(in_array('user', Auth::user()->roles->pluck('name')->all()))
{
return redirect('/user/dashboard/');
}
else{
return redirect('login');
}
}else{
return redirect('login');
}
you need to make custom auth in laravel and make different table for admin and user

Laravel 5.3 : redirected you too many times error

I am experiencing this error when trying to navigate to "/admin". Other routes such as "/employee" are working fine.
Here are my current web routes
Auth::routes();
/* Voyager Routes */
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
...
});
/* Badge App Routes - All the dashboard routes for managers, employees and HRs are defined here */
Route::group(['middleware' => 'auth', 'prefix' => 'employee'], function () {
Route::get('/', 'frontend\DashboardController#index')->name('homepage');
Route::get('dashboard', 'frontend\DashboardController#index')->name('homepage');
...
});
Route::group(['middleware' => 'auth'], function () {
Route::resource('team-manager', 'frontend\TeamManagerController');
Route::resource('badges', 'backend\BadgeController');
Route::get('badges/award/{id?}', 'backend\BadgeController#award');
Route::post('store_award', 'backend\BadgeController#storeAward')->name('store_award');
});
/* User Redirector - Based on user role */
Route::group(['middleware' => ['redirector']], function () {
Route::get('/');
Route::get('login');
});
And here's my middleware redirector
public function handle($request, Closure $next){
if (!Auth::guest()) {
$user = User::find(Auth::id());
// TODO: fix static id below
return $user->role_id == 1 ? redirect('admin') : redirect('employee');
}
return redirect(route('voyager.login'));
}
Thank you in advance!
The problem is in your middleware:
return $user->role_id == 1 ? redirect('admin') : redirect('employee');
You have admin role, and you are also in /admin page. Then your middleware redirects you again and again to /admin.
It is better to check if the user is not in the /admin or /admin/* related routes, then redirect him to admin.
if($user->role_id == 1) {
//check if user is in /admin or /admin related routes.
return ($request->is('/admin') or $request->is('/admin/*')) ? $next($request) : redirect('admin');
} else {
redirect('/employee');
}

LARAVEL $router->bind for only backend(admin)

In RouteServiceProvider I have:
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
and url for admin is "/admin/user/1".
but for frontend url is "/user/username"
So I want to check if this is "admin" or "frontend" url and for admin bind user but for frontend don't bind user:
$adminRoute = //check if this is admin or frontend url ("/admin/user/1" or "/user/username")
if($adminRoute){
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
}else{
//nothing
}
PS. I don't want change findOrFail() function to find user by username I want disable binding for non admin urls.
Try this:
Route::group(array('prefix' => 'admin'), function() {
$router->bind('user', function ($value) {
return app(UserInterface::class)->findOrFail($value);
});
});

How to restrict routes in Laravel 4?

I have 2 types of user :
Admin
Not Admin
Admin will get the full-access, where Not Admin will only get the index.
Here are my routes
Route::get('users','UserController#index');
Route::get('users/create', array('as'=>'users.create', 'uses'=>'UserController#create'));
Route::post('users/store','UserController#store');
Route::get('users/{id}', array('before' =>'profile', 'uses'=>'UserController#show'));
Route::get('users/{id}/edit', 'UserController#edit');
Route::put('users/{id}/update', array('as'=>'users.update', 'uses'=>'UserController#update'));
Route::delete('users/{id}/destroy',array('as'=>'users.destroy', 'uses'=>'UserController#destroy'));
How do I make a restriction so that Admin will get the full-access, where Not Admin will only get the access to index.
Add this to your filters.php
Route::filter('admin', function()
{
if (Auth::user()->type == "Admin") // Change this to match your !
{
if (Request::ajax())
{
return Response::make('Unauthorized', 404);
}
}
else return View::make('error'); // Need to have this view !
});
Then try this on your routes.php
Route::group(array('before'=>'admin'),function() {
//Users
Route::get('users','UserController#index');
Route::get('users/create', array('as'=>'users.create', 'uses'=>'UserController#create'));
Route::post('users/store','UserController#store');
Route::get('users/{id}', array('before' =>'profile', 'uses'=>'UserController#show'));
Route::get('users/{id}/edit', 'UserController#edit');
Route::put('users/{id}/update', array('as'=>'users.update', 'uses'=>'UserController#update'));
Route::delete('users/{id}/destroy',array('as'=>'users.destroy', 'uses'=>'UserController#destroy'));
Repeat for if (Auth::user()->type != "Admin")
You would use a route filter that checks their permission level.
To elaborate on #ceejayoz answer with an example:
/*
* Check if user is logged in
*/
Route::filter('auth', function(){
if(!Auth::check()){
return Redirect::to('login')->with('message', 'You must be logged in');
}
});
/*
* Check if the logged in users group name is 'admin'
*/
Route::filter('admin', function(){
if(Auth::user()->group->name != 'admin'){
return Redirect::to('home')->with('message', 'You do not have access to this');
}
});
//Users must be logged in to access these routes
Route::group(array('before'=>'auth'), function(){
Route::get('users','UserController#index');
//Users must be an administrator to access these routes
Route::group(array('before'=>'admin'), function(){
Route::get('users/create', array('as'=>'users.create', 'uses'=>'UserController#create'));
Route::post('users/store','UserController#store');
Route::get('users/{id}', array('before' =>'profile', 'uses'=>'UserController#show'));
Route::get('users/{id}/edit', 'UserController#edit');
Route::put('users/{id}/update', array('as'=>'users.update', 'uses'=>'UserController#update'));
Route::delete('users/{id}/destroy',array('as'=>'users.destroy', 'uses'=>'UserController#destroy'));
});
});

Categories