Group Access to pages in laravel - laravel

Inside an AuthServiceProvider Access Control is defined. I need to check permission to access page in the routes web.php.
If user is not admin then page should redirect error page or page not found .
How to create a middleware that redirect to 404 page if somebody tries to access the page from the url.
AuthServiceProvider
Gate::define('isAdmin',function($user){
return $user->type === 'admin';
});
Gate::define('isGeneralUser',function($user){
return $user->type === 'user';
});
Gate::define('isPaidUser',function($user){
return $user->type === 'paid';
});
Route web.php
if (Gate::allows('isAdmin') && Gate::allows('isPaidUser')) {
Route::get('/home-page', function () {
return view('pages.trades');
});
}

create middleware
class CheckIsTradeable
{
public function handle($request, Closure $next)
{
if ($request->user()->type !== 'admin' && $request->user()->type !== 'paid') {
abort(404);
}
return $next($request);
}
}
Register inside Kernal
protected $routeMiddleware = [
...
'isTradeable' => \App\Http\Middleware\CheckIsTradeable::class,
];
and check it in your route
Route::get('/home-page', function () {
return view('pages.trades');
})->middleware('isTradeable');

Related

How to fix this, i try to load dashboard route when the auth middleware is true

But when authentication was success, it shown error Route [/db1] not defined. I hace declared db1 route, but this route can access only if user has session. Anyone can tell me what wrong with my code?
this is my route:
Route::group(['middleware' => ['userSession']], function() { Route::get('/db1', [WasteController::class, 'db1'])->name('db1'); });
this is my kernel in middlewareGroup:
'userSession' => [ \App\Http\Middleware\CheckUserSession::class, ],
this is my middleware:
public function handle($request, Closure $next) {
if ($request->session()->get('status') != 'true') {
//status user cannot be found in session
return redirect('/');
}
return $next($request);
}
i have tried but it show error db1 route not defined
Did you try this?
public function handle($request, Closure $next) {
if ($request->session()->get('status') = 'true') {
//status user cannot be found in session
return $next($request);
}
return redirect('/');
}

Laravel middleware login redirect

how to create middleware redirect about role. I have 2 middleware, first Admin, next User. Need redirect after login, if role Admin, example redirect to /admin, if User redirect to /user.
Admin middleware:
if(Auth::check() && Auth::user()->isRole() == "Admin"){
return $next($request);
}
return redirect('login');
User middleware:
if(Auth::check() && Auth::user()->isRole() == "User"){
return $next($request);
}
return redirect('login');
WEB routes
Route::group(['middleware' => ['auth']], function () {
Route::get('/', 'DashboardController#index');
Route::group(['middleware' => ['auth' => 'admin']], function (){
Route::resource('/admin', 'AdminController');
});
Route::group(['middleware' => ['auth' => 'user']], function (){
Route::resource('/user', 'AdminController');
});
});
You can make your admin/user middleware to inherit laravel's Authenticate middleware: Illuminate\Auth\Middleware\Authenticate, then have their definitions as below.
Admin Middleware-
public function handle($request, Closure $next, ...$guards)
// Ensure auth - this will automagically re-direct if not authed.
$this->authenticate($request, $guards);
if(Auth::user()->isRole() == "Admin")
return $next($request);
return redirect('/user-default-page')
}
// You can define this for your un-authenticated redirects
protected function redirectTo($request)
{
return '/login';
}
User middleware will then be:-
public function handle($request, Closure $next, ...$guards)
// Ensure auth - this will automagically re-direct if not authed.
$this->authenticate($request, $guards);
if(Auth::user()->isRole() == "User")
return $next($request);
return redirect('/admin-default-page')
}
// You can define this for your un-authenticated redirects
protected function redirectTo($request)
{
return '/login';
}
For routes:
Route::group(['middleware' => 'admin'], function () {
// Put here admin routes, e.g
Route::resource('/admin', 'AdminController');
}
Route::group(['middleware' => 'user'], function () {
// Put here user routes, e.g
Route::resource('/users', 'UserController');
}
// You can still use the default auth routes, say for routes that (somehow), both admin and user can access
Route::group(['middleware' => 'auth'], function () {
Route::resource('/dashboard', 'DashboardController');
}
// Admin Middleware
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->role->id == 1)
{
return $next($request);
}else {
return redirect()->route('login');
}
}
// User Middleware
public function handle($request, Closure $next)
{
if(Auth::check() && Auth::user()->role->id == 2 )
{
return $next($request);
}else {
return redirect()->route('login');
}
}
// Admin Route Group
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
})
// User Middleware
Route::group(['as'=>'user.','prefix'=>'user','namespace'=>'Author','middleware'=>['auth','user']], function (){
Route::get('dashboard','DashboardController#index')->name('dashboard');
});

How to protect a route with middleware in laravel?

i have a problem with my middleware. when i login as admin, it's working fine and redirect to /Admin/home same as Operator (i have 2 user, Admin & Operator). The problem is when i hit url as example : /Operator/home as Admin role, it can access it. And that's the problem.
I'have create a new middleware CheckMiddleware, and registered to kernel in array $routeMiddleware as checkMiddleware:
public function handle($request, Closure $next)
{
$user = $request->user();
if ($user) {
if ($user->isAdmin()) {
return $next($request);
}elseif($user->isOperator()){
return $next($request);
}
}
return dd('Forbidden page. you have to login as admin/operator');
}
In the route :
Route::group(['prefix'=>'Admin' ,'middleware' => 'checkMiddleware'], function() {
Route::get('/home', 'HomeController#index')->name('homeAdmin');
});
Route::group(['prefix'=>'Operator' ,'middleware' => 'checkMiddleware'], function() {
Route::get('/home', 'HomeController#index')->name('homeAdmin');
});
Auth::routes();
in User model :
public function isAdmin(){
if ($this->role_id === 1) {
return true;
}
return false;
}
public function isOperator(){
if ($this->role_id === 2) {
return true;
}
return false;
}
What i want is, Admin cannot access Operator and Operator Cannot Access Admin.
if this is not clear, tell me what file you want to see.
The problem is if user is admin then accept request and user is operator still accept request. That code below
if ($user->isAdmin()) {
return $next($request);
}elseif($user->isOperator()){
return $next($request);
}
For simple solution, just create two middleware for admin and operator. Then apply admin middleware for route (group) need admin role, and apply operator middleware for route (group) need operator role.
If you have some route allow admin and operator role access, just add both to that route.
UPDATE
If you want to use 1 middleware, do like this :
if ($user->isAdmin() && $request->route()->getPrefix() == 'admin') {
return $next($request);
}
if ($user->isOperator() && $request->route()->getPrefix() == 'operator') {
return $next($request);
}
return abort(401) // OR SOME ROUTE YOU WANT

Laravel 5.4 Route [login] not defined

Hi I have following route and constructor in my controller i want to check if user is authenticated or not if not then redirect to /warehouse/login page. but for some reasons i am getting Route [login] not defined error.
I am migrating my functions from Laravel 4.2 to Laravel 5.4
Constructor:
public function __construct()
{
$this->middleware('auth');
$this->middleware(function ($request, $next) {
if (!Auth::check()) {
$url = URL::current();
$routeName = Route::currentRouteName();
if ($routeName != "AdminLogin" && $routeName != 'admin') {
Session::put('pre_admin_login_url', $url);
}
return redirect('/warehouse/login');
}
return $next($request);
}, array('except' => array('WarehouseAdminLogin', 'WarehouseAdminVerify')));
}
Routes:
Route::get('/warehouse', 'WarehouseController#index');
Route::get('/warehouse/login', array('as' => 'WarehouseAdminLogin', 'uses' => 'WarehouseController#login'));
You didnt define your login function.
make a function
public function login()
{'your code'}
in your WarehouseController
Edited: the problem is that you have not a route named login. This error is caused by:
$this->middleware('auth');
because this code in the auth middleware:
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
So what to do is remove auth middleware and try again or make a route with login name.

add control to resource routes

My resource route looks like :
$router->resource('subnets', 'subnetController');
I saw on the documentation that a resource route can have an array of parameters... is there a parameter that permits you to choose who can access to those routes ? If I was using basic routing that would be something like :
Route::get('/subnets', function () {
if (Auth::user()['attributes']['role'] == 'admin') return view('subnets.index');
else return view ('errors.403');
});
you should use middleware..
create middleware > https://laravel.com/docs/5.3/middleware
write this on handler middleware
public function handle($request, Closure $next)
{
if ($request->user()->role == 'admin') {
return $next($request);
}
abort(403, 'Access denied');
}
routes.php
Route::group(['middleware' => 'your_middleware_name'], function () {
Route::resource('subnets', 'subnetController');
});

Resources