Route restriction in Laravel for selected role - php

I have a users table with two types of users: Vendor and Customer. Every thing is fine with login if vendor role is 1 redirect to vendor Dashboard and for customer role is 2 redirect to customer dashboard but after login how to prevent route to customer dashboard if logged as vendor and vice versa
Controller for login depend on role:
class CustomerLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:web');
}
public function showLoginForm()
{
return view('Customer.login');
}
public function login(Request $request)
{
$this->validate($request,[
'email'=>'required|email',
'password'=>'required|min:6',
]);
if (Auth::guard('web')->attempt(['email'=>$request->email,'password'=>$request->password,'active'=>1,'role_id'=>2], $request->remember)) {
return redirect()->intended(route('customer.dashboard'));
} elseif (Auth::guard('web')->attempt(['email'=>$request->email,'password'=>$request->password,'active'=>1,'role_id'=>1],$request->remember)) {
return redirect()->intended(route('vendor.dashboard'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
}
after login route controller:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('index.customer.customerdashboard');
}
public function vendor()
{
return view('index.vendor.vendordashboard');
}

You need to create a middleware with
php artisan make:middleware PortectedVendorRoutesMiddleware
Then, in the handle method of that file, add the logic to check for the user's role
public function handle($request, Closure $next)
{
if (auth()->user()->role_id == 1) {
return $next($request);
}
abort(404);
}
Now you need to protect your routes
Route::group(['middleware' => App\Http\Middleware\ProtectVendorRoutesMiddleware::class], function () {
// Your protected vendor routes here
});
Or since Laravel 5.5
Route::middleware([App\Http\Middleware\ProtectVendorRoutesMiddleware::class])->group(function () {
// Your protected vendor routes here
});
Repeat the process for Customer routes.

Related

deleting a user with query builder laravel

I'm trying to delete a user account using laravel query builder so I'm doing this
AuthRepository
class AuthRepository implements IAuthRepository
{
....
public function delete($user_id)
{
$res = User::where('id', $user_id->id)->delete();;
if ($res) {
return response('Success, user was deleted', 204);
} else {
return response()->json(error);
}
}
}
In controller
class AuthController extends Controller
{
protected $auth;
public function delete($user_id)
{
return $user_id->delete();
}
}
in api.php
Route::group(['prefix' => 'auth'], function () {
Route::group(['middleware' => 'auth:api'], function () {
// Delete user
Route::post('user/delete/{user_id}', 'AuthController#delete');
});
});
Passing user_id to ${API_URL}/auth/user/delete/{user_id} I'm facing
Call to a member function delete() in Controller on line return $user_id->delete();. Can someone please explain me why is this happening, thanks.
Take advantage of the route model binding and to this instead:
public function delete(User $user)
{
return $user->delete();
}
And your route:
Route::post('user/delete/{user}', 'AuthController#delete');
You cannot call delete() on an integer.
If you don't want to use the Route model binding as suggested by #nakov and insist on using id then you have to get the user first before deleting.
public function delete($user_id)
{
$user = User::findOrFail($user_id);
return $user->delete();
}

Laravrl5- user permissions for whole module controllers

I created a simple system to set permissions for users in the admin panel using AdminMiddleware.
Every user has permissions like groups, posts, pages ....
Routes/web:
Route::group(['middleware' => 'admin'], function()
{
Route::get('/admin' , 'admin\AdminController#index')->name('admin');
//all admin panel routes
}
In the AdminMiddleware
public function handle($request, Closure $next)
{
if(Auth::check()){
if ($request->user()->user_type !== 'man')
{
return redirect('/');
}
$user_permissions = Auth::user()->permissions;
foreach($user_permissions as $value){
$controller = Controllers::get_controller($value->controller_id);
$permissions['name'] = $controller->controller_name;
$all_permissions[] = $permissions;
unset($permissions);
}
foreach ($all_permissions as $value){
$controllers[] = trim($value['name']);
}
$request->user()->controllers = $controllers;
return $next($request);
}
else{
return redirect('/login');
}
}
So I get a list of all user permissions which represent controllers names and in every controller (in this controller i check if the user has permission named 'users' to access the users controller to view their data)
protected $user;
public function __construct(){
$this->middleware(function ($request, $next) {
$this->user= Auth::user();
if(!in_array('users',$this->user->controllers)){
session()->flash('error' , 'No permission');
return redirect('/admin');
}
else{
return $next($request);
}
});
}
I use this for every controller and it works for a small project but when it comes to a large project with modules (nWidart/laravel-modules) it'll be hard. What I want is to check for the permission for the whole module not for every single controller in the module. So if I have a module named blog I want to check if the logged in user has permission to access any controller in that module how could this be done?
I created a middleware for every module and in the middleware i get user permissions and check if he the permission to access this group
public function handle($request, Closure $next)
{
if(Auth::check()){
if ($request->user()->user_type !== 'man')
{
return redirect('/');
}
$user_permissions = Auth::user()->permissions;
$user_group = Auth::user()->group_id;
if($user_group == 1){ //all permissions admin
return $next($request);
}
else{
//get user permissions as an array
if(in_array('groups',$user_permissions)){ //module name is groups
return $next($request);
}
else{
return redirect('/home');
}
}
}
else{
return redirect('/login');
}
}
Routes
Route::group(['middleware' => 'admin'], function()
{
Route::get('/admin' , 'admin\AdminController#index')->name('admin');
});
Route::group(['middleware' => 'users'], function()
{
Route::get('/adminUsers' , '\Modules\Users\Http\Controllers\UsersController#index');
});
Route::group(['middleware' => 'groups'], function()
{
Route::get('/groups' , '\Modules\Groups\Http\Controllers\GroupsController#index');
});

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 5.1 page authentication using routes

I'm working on a site that needs an admin panel. I am currently trying to set up the authentication of that panel, though I can not find a way to deny access from any guest users (non-admins). I have a login page, of course, and after login, it routes to the admin page, though you can also go to /admin when you're not logged in.
routes.php :
Route::get('home', function(){
if (Auth::guest()) {
return Redirect::to('/');
} else {
return Redirect::to('admin');
}
});
Route::get('admin', function () {
return view('pages.admin.start');
});
MainController.php :
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class MainController extends Controller {
public function getIndex() {
return view('pages.index');
}
public function getAbout() {
return view('pages.about');
}
public function getPortfolio() {
return view('pages.portfolio');
}
public function getShop() {
return view('pages.shop');
}
public function getContact() {
return view('pages.contact');
}
/*public function getAdmin() {
return view('pages.admin.start');
}*/
}
I could really use some help here, because I'm totaly stuck, and yes, I have read the documentation, though maybe I'm just missing something.
Assuming you have a line like this:
'auth' => 'App\Http\Middleware\Authenticate',
in your app/Http/Kernel.php file:
put all the routes you need "authenticated" inside the grouping, but keep the "guest" routes outside of them :
Route::get('home', function(){
if (Auth::guest()) {
return Redirect::to('/');
} else {
return Redirect::to('admin');
}
});
Route::group( ['middleware' => 'auth' ], function(){
Route::get('admin', function () {
return view('pages.admin.start');
});
Route::just-another-route()...;
Route::just-another-route()...;
});
Documentation: http://laravel.com/docs/5.1/routing#route-groups
You should use a Middleware to handle authentication of your users
1) First you have to create a middleware that will check if the user requiring the page is an admin, and if not you have to redirect; something like this:
class AdminMiddleware
{
public function handle(Request $request, Closure $next )
{
//if User is not admin
//redirect to no permess
return $next($request);
}
}
2) Then you have to bind the middleware to the routes you want to be accessible only from an admin user:
//bind the middleware to all the routes inside this group
Route::group( ['middleware' => 'adminmiddleware' ], function()
{
Route::get('admin', function () {
return view('pages.admin.start');
});
//other routes
});

Laravel 5 redirect loop error

I trying to make a login and admin script, the problem is that I have a redirect loop I dont know why.
I want the login users and can be in the / path not /home.
If change return new RedirectResponse(url('/')); to return new RedirectResponse(url('/anotherpage')); it works but I want to be /
Routes:
Route::get('/', [
'as' => 'home', 'uses' => 'HomeController#index'
]);
// Tutorials Routes
Route::get('/tutorials', 'HomeController#tutorials');
Route::get('/tutorials/{category?}', 'HomeController#tutorialsCategory');
Route::get('/tutorials/{category?}/{lesson?}', 'HomeController#tutorialsLesson');
// Courses and Series Routes
Route::get('/courses-and-series', 'HomeController#coursesandseries');
// Admin Routes
Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function()
{
Route::get('/admin', function()
{
return 'Is admin';
});
});
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
Admin middleware:
public function handle($request, Closure $next)
{
if (Auth::user()->type != 'Admin')
{
return abort(404);
}
return $next($request);
}
RedirectIfAuthenticated:
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
return new RedirectResponse(url('/'));
}
return $next($request);
}
Home Controller:
class HomeController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('home');
}
public function tutorials()
{
return view('pages.tutorials');
}
public function tutorialsCategory()
{
return view('pages.tutorials');
}
public function tutorialsLesson()
{
return view('pages.single');
}
public function coursesandseries()
{
return view('pages.coursesandseries');
}
public function single()
{
return view('pages.single');
}
}
You are having these redirection loops because all the methods in HomeController are protected by Guest Middleware.
Since you wish to redirect authenticated users to HomeController#index
Remove $this->middleware('guest'); from HomeController
or
Modify the Guest Middleware to ignore index method
$this->middleware('guest', ['only' => ['tutorials','tutorialsCategory']])
List other methods you wish to protect with Guest Middleware excluding Index method

Categories