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');
});
Related
I have an authorization using middleware where Function could only run when authorized
this is my middleware:
class IsAdmin
{
public function handle($request, Closure $next)
{
if (auth()->check() && auth()->user()->is_admin == 1) {
return $next($request);
}
return abort(403, 'Forbidden');
}
}
my Controller:
public function destroy(int $bookId, int $reviewId, Request $request)
{
// #TODO implement
$check_bookReview = BookReview::firstWhere('id', $reviewId)->where('book_id', $bookId);
if ($check_bookReview && isAdmin()) {
BookReview::destroy($reviewId);
return response()->noContent();
} else {
abort(404);
}
}
and my api.php as well my Kernel:
'auth.admin' => \App\Http\Middleware\IsAdmin::class
Route::group(['middleware' => ['auth.admin']], function (){
Route::post('/books', 'BooksController#store');
Route::post('/books/{id}/reviews', 'BooksReviewController#store');
Route::delete('/books/{bookId}/reviews/{reviewId}', 'BooksReviewController#destroy');
});
and i have a User db field where it contains api_token and is_admin like below:
and my Postman still return 403 forbidden while i already gave an authorization by headers:
what should i do here, to fulfill my function?
Looks like your Authenticate middleware is not working, so it likely fails on auth()->check().
Make sure to use the auth middleware from Laravel, you can also use a guard as described here:
https://laravel.com/docs/9.x/authentication#protecting-routes
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('/');
}
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');
});
I am trying to protect a route using two middle-wares so that both expert and user can access the same route but as soon a user tries to access the route he is logged out.
I had created two middle-wares for expert and user and protect the route using these middle-wares.
Web.php
Route::group(['middleware' => ['expert','user']], function () {
Route::post('/showForm','UserController#showFormFilled');
});
User Middle ware
public function handle($request, Closure $next)
{
//////////////////// check if user is logged in ///////////////////
if(Auth::check())
{
////////////////// check user role id //////////////////////////
if(auth()->user()->role_id == 3)
{
return $next($request);
}
else if (auth()->user()->role_id==2)
{
return redirect('/expert');
}
}
else
{
return redirect('/login');
}
}
Expert Middle ware
public function handle($request, Closure $next)
{
if(Auth::check()){
if(auth()->user()->role_id == 2)
return $next($request);
else if (auth()->user()->role_id==3)
return redirect('/dashboard');
}
else {
return redirect('/login');
}
}
Both the users should be able to access the same route.
#hamzahummam - there is no way to achieve what you are looking for using the above separate-middlware-for-each-type method. Each middleware prematurely redirects [either to /dashboard or to /expert etc] the request without allowing it to passthrough other middleware. Best would be to use a third-party package that provides a more comprehensive and fine-grained access control [example: https://github.com/Zizaco/entrust]
If that's not an option, the best case would be to implement a single middleware and pass the role as parameter. See: Laravel Middleware Parameters
A minimal example would look like:
public function handle($request, Closure $next, $role)
{
// Assuming Auth::check() passes
$roleId = auth()->user()->role_id;
if ($roleId == 2 && strpos($role, 'expert') !== false) {
// Logged in user is `expert` and route allows `expert` access
return $next($request);
} else if ($roleId == 3 && strpos($role, 'user') !== false) {
// Logged in user is `user` and route allows `user` access
return $next($request);
} // and so on...
// Handle failures here
if ($roleId == 2 && strpos($role, 'expert') === false) {
// an `expert` is trying to access route that can't be accessed
return redirect('/expert-dashboard');
} // and so on...
}
You'd define routes as:
Route::group(['middleware' => ['new_middleware:expert,user' ]], function () {
Route::post('/showForm','UserController#showFormFilled');
});
Hope this helps.
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');