Laravel Multi-role unable to create in laravel 5 - authentication

I am having trouble creating multi-role application in laravel5 since in laravel 5 the authentication is pre defined so I am not willing to mess around with predefined codes of laravel 5 authentication. I have a constructor that authenticates every controller in my project but I am unable to check user roles for the following roles:-
1. Admin
2. Agent
3. User
I can check manually for every functions but that is not the right process of doing so and if I have a total of around 500 functions I cant go in every function and define manually. please any help
Thank you

Personally I would use middleware and route groups to accomplish the task, which would be similar the way Laravel checks for user authentication.
You just have to determine when you need to run the middleware, which can be done by nesting Route::group's or injecting the middleware from your controller.
So, for an example of nesting you can have something like this in your routes file:
Route::group(['middleware' => ['auth']], function () {
Route::get('dashboard', ['as' => 'dashboard', function () {
return view('dashboard');
}]);
Route::group(['prefix' => 'company', 'namespace' => 'Company', 'middleware' => ['App\Http\Middleware\HasRole'], function () {
Route::get('dashboard', ['as'=>'dashboard', function () {
return view('company.dashboard');
}]);
Route::resource('employees', 'EmployeesController');
...
...
});
});
or you can inject the middleware to your controllers like so:
use Illuminate\Routing\Controller;
class AwesomeController extends Controller {
public function __construct()
{
$this->middleware('hasRole', ['only' => 'update'])
}
}
And then add a one or more Middleware files using something like php artisan make:middleware HasRole which will give you the middleware boiler plate which you could then add your role checking logic:
<?php namespace App\Http\Middleware;
use Closure;
class HasRole {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->is('admin/*')){
[******ADD YOUR LOGIC HERE TO DETERMINE THE ROLE ******]
[******YOU CAN ALSO INCLUDE ANY REDIRECTS IF NECESSARY******]
}
return $next($request);
}
}
Notice I used the $route->is('admin/*') to filter any routes as an example of further filtering requests, which you would probably not include if you are injecting the middleware from the controller.
But if the user passes the required role check you do not need to do anything and they will be allowed to continue to the view. If they fail the role check, you can handle that accordingly, but beware of getting them caught in a failed permission loop.
I assume you get the gist of it, feel free to look into the Laravel middleware docs for more info.

Related

Simple Admin User with Laravel 5.2 Authentication

I've setup Laravel's built in authentication feature, but it doesn't have an admin. I've been looking up ways to do this, but many tutorials seem a bit weighty. I wanted as simple, safe solution that takes advantage of the users table I already have.
I've looked at this: https://laracasts.com/discuss/channels/laravel/user-admin-authentication
The instructions come from several users, and it's a bit hard to follow. I've set up a "isAdmin" column to my users database. I have a middleware for the admin, but I'm not sure how to proceed from here.
If I don't forget anything, this should be enough.
Kernel.php:
protected $routeMiddleware = [
//...
'isAdmin' => \App\Http\Middleware\IsAdminMiddleware::class,
];
IsAdminMiddleware:
public function handle($request, Closure $next)
{
if(!\Auth::user()->isAdmin){
return Redirect::route('index');
}
return $next($request);
}
routes.php:
Route::group(['middleware' => ['auth', 'isAdmin']], function () {
Route::get('/', 'AdminController#index')->name('admin.index');
Route::get('/add-user', 'AdminController#addUser')->name('admin.addUser');
});
The lazy solution, not recommended:
In you AdminController, add the following:
public function __construct(){
if(!\Auth::user()->isAdmin){
dd('Redirect user or whatever, this is where all but admin gets stucked');
}
}

Laravel 5.2 How to change redirects of RedirectIfAuthenticated depending on Controller?

I'm wondering if it is possible to make the authentication redirect differently for each of my controllers? Currently, everything redirects to /home. This is intended for my HomeController. But for ClientController, I want it to redirect to /client (if authenticated) and not /home. Do I have to make a new middleware for each of my controllers or is there a way to accomplish this by reusing auth?
RedirectIfAuthenticated.php
if (Auth::guard($guard)->check()) {
return redirect('/home'); //anyway to change this to /client if coming from ClientController?
}
I have this on my ClientController.php
public function __construct()
{
$this->middleware('auth');
}
Thanks in advance! Fairly new to Laravel and Middleware.
Just use this in User model:
protected $redirectTo = '/client';
You can also achieve this by changing Laravel's core file. If you are using Laravel 5.2 go to project_folder\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RedirectsUsers.php
You can find the following code:
public function redirectPath()
{
if (property_exists($this, 'redirectPath')) {
return $this->redirectPath;
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home'; //Change the route in this line
}
Now, change /home to /client. However, I recommend not to change core files. You can use the first one.
Never mind, I was able to make things work with proper routing.
Added ClientController under web middle which is responsible for all of the authentication.
Route::group(['middleware' => ['web']], function () {
Route::resource('client', 'ClientController');
}
And in
ClientController.php, add to use auth middleware.
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('client');
}

Laravel routes.php include file using Session

Not sure if this is possible, but here it goes.
What I am looking to do is include my "admin" routes as a separate file, only if the user is an admin (therefore a non admin will get a 404 error
routes.php
if( Session::get('user')->is_admin )
require_once('routes-admin.php');
if( Auth::check() )
require_once('routes-user.php');
Route::get('/', function() {
return view('home');
});
routes-admin.php
Route::get('admin', function() {
return view('admin-dashboard');
});
routes-user.php
Route::get('user', function() {
return view('user-dashboard');
});
What I am trying to do is avoid having the test repeated with every single Route
so if my user segment has 10 pages I currently need 30 lines of code dedicated to Auth::check() (the if, else and redirect if not), where I can instead have a single check on routes.php and the user will get a 404 if they don't belong
Is there a way to perform this check outside of the Route?
Perhaps you want to read documentation first?
Route::group(['middleware' => 'auth'], function()
{
Route::get('/', function()
{
// Uses Auth Middleware
});
Route::get('user/profile', function()
{
// Uses Auth Middleware
});
});
Above code does exactly what you need, is "person logged in?" let him go to page "whatever".
You can create middlewares (check if user is admin or basic user) yourself and apply on groups.
Example middleware
class BeforeMiddleware implements Middleware
{
public function handle($request, Closure $next)
{
// Perform action
return $next($request);
}
}
Do not get me wrong, just your approach is really not Laravel like. Try to see some open source projects done in L5 or even in L4. Try to use everything Taylor already done for you. Documentation is your firend here.
Following the response of #Kyslik for the middleware, you can "include" your own routes file in your RouteServiceProvider like the default routes file, the RouteServiceProvide is located in: app/Providers/RouteServiceProvider.php,
Find the section
require app_path('Http/routes.php');
and just replicate with the name of your routes file want to include

'auth' Middleware with Route::resource

How can I use middleware with resources?
Route::resource('myitem', ['middleware' => 'auth', 'uses' => 'App\\Controllers\\MyitemsController']);
Just followed https://laracasts.com/discuss/channels/general-discussion/struggling-with-routeresource-and-auth-middleware but unfortunately could not solve.
Getting error:
ErrorException (E_UNKNOWN)
Array to string conversion
Open: /vendor/laravel/framework/src/Illuminate/Routing/Router.php
protected function getResourceAction($resource, $controller, $method, $options)
{
$name = $this->getResourceName($resource, $method, $options);
return array('as' => $name, 'uses' => $controller.'#'.$method);
}
Using filter with resource was not working that why had to use Route::group
Route::group(array('before' => 'auth'), function()
{
Route::resource('myitem', 'App\\Controllers\\MyitemsController');
});
https://stackoverflow.com/a/17512478/540144
Middleware is a new feature of Laravel 5. In Laravel 4, filters where something similar. So instead of using the key middleware you should use before or after. Also, and that's where the error comes from, the second argument of Route::resource should be the controller name as string and the third one is an array of options:
Route::resource('myitem', 'App\\Controllers\\MyitemsController', ['before' => 'auth']);
Edit
Apparently before filters only work with resource routes when you wrap a group around it. See the OPs answer for an example...
I just came up against this and found the easiest way is to add the middleware straight to the controller.
I found my answer here:
http://laravel.com/docs/master/controllers
class MyitemsController extends Controller {
/**
* Instantiate a new MyitemsController instance.
*/
public function __construct()
{
$this->middleware('auth');
}
}
How to do this in Laravel 5. The Answer you have been waiting for.
Use middleware instead of before
Route::group(array('middleware' => 'auth'), function()
{
Route::resource('user', 'UserController',
['only' => ['edit']]);
}
To check if the route is setup, run:
php artisan route:list
which should show the following:
GET|HEAD | user/{user}/edit | user.edit | App\Http\Controllers\UserController#edit | auth
Note auth instead of guest
Better solution
Use middleware instead of before
Route::group(['middleware' => 'auth'], function(){
Route::resource('myitem', 'MyitemsController');
});
You can check if it's ok with:
php artisan route:list

communicating between modules in zend framework 2

I have an authentication module. Now, I want to ensure that every module passes (communicates) with that authentication module. I guess you could say its the authentication to the entire application. How do I accomplish this?
Well one simple way would be getting that module/module_class via namespaces, then you could just extend the class. Have the functionality automatically called in the parent class or call the method in the child class. This would be a pretty basic way:
// Auth class
class SomeAuthClass
{
public function __construct()
{
// go ahead and call doAuthCrap here, or wait
// and let the child class call it manually
}
protected function doAuthCrap()
{
// code
}
}
use Your\AuthModule\SomeAuthClass;
class SomeOtherModuleClass extends SomeAuthClass
{
public function zippy_snipp()
{
// call some method from the parent auth class (doAuthCrap)
}
}
Or to adhere to some of the new ways ZF2 does things, you could access the auth class via the service manager and write the config for it in service config in your module.php file. There's really multiple ways to go about doing this one and ZF2 offers quite a bit of options for doing stuff like this.
zf2:
// in controller
$auth = $this->getServiceLocator()->get('someAuth');
// in service config in module.php
public function getServiceConfig()
{
return array(
'factories' => array(
'someAuth' => function ($serviceManager) {
// code here
},
)
);
}