Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

php - Roles with laravel 5, how to allow only admin access to some root

I follow this tutorial : https://www.youtube.com/watch?v=kmJYVhG6UzM Currently I can check in my blade if user is a admin or not like this:

{{ Auth::user()->roles->toArray()[0]['role'] }}
HI ADMIN
@endif

How can I make my route only available for admin user?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to create a middleware for your route.

Use: php artisan make:middleware AdminMiddleware.

You will find in your middleware folder a new file with this name.

Put your logic in your middleware, e.g.

public function handle($request, Closure $next)
{
    if(Auth::check())
    {
        return $next($request);
    }
    else
    {
        return view('auth.login')->withErrors('You are not logged in');
    }

}

Once you have done your logic in your middleware, you can either call it in the route or make the middleware apply to all routes.

If you want to add it to all routes, go to Kernel.php and add it to the $middleware array, e.g.

protected $middleware = [
    'IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode',
    'IlluminateCookieMiddlewareEncryptCookies',
    'IlluminateCookieMiddlewareAddQueuedCookiesToResponse',
    'IlluminateSessionMiddlewareStartSession',
    'IlluminateViewMiddlewareShareErrorsFromSession',
    'AppHttpMiddlewareVerifyCsrfToken',
    'AppHttpMiddlewareAdminMiddleware',
];

If you want to add it to specific routes only, add it to the $routeMiddleware variable and add the alias to the route. E.g.

protected $routeMiddleware = [
    'auth' => 'AppHttpMiddlewareAuthenticate',
    'auth.basic' => 'IlluminateAuthMiddlewareAuthenticateWithBasicAuth',
    'guest' => 'AppHttpMiddlewareRedirectIfAuthenticated',
    'admin' => 'AppHttpMiddlewareAdminMiddleware',
];

You can then add it to a route, as a filter, e.g.

Route::get('admin/profile', ['middleware' => 'admin', function()
{

}]);

For additional info visit the docs:

http://laravel.com/docs/master/middleware

EDIT

An improvement on this would be to use variadic functions which was introduced in PHP 5.6

http://php.net/manual/en/migration56.new-features.php

Instead of having to make a middleware for each permission set you can do the following

PermissionMiddleware

namespace AppHttpMiddleware;

use Closure;
use AppModelsRole;
class PermissionMiddleware
{
    // Pass parameters to this middleware
    public function handle($request, Closure $next, ...$permitted_roles)
    {

        //Get a users role
        $role = new Role;
        $role_name = $role->getUserRoleByName();
        foreach($permitted_roles as $permitted_role) {
            if($permitted_role == $role_name) {
                return $next($request);
            }
        }
        return redirect()->back()->withErrors('You do not have the required permission');

    }
}

Notice the ...$permitted_roles

Route::get('admin/profile', ['middleware' => 'PermissionMiddleware:Admin,Marketing', function()
{

}]);

You can now specify as many roles as required for one middleware rather than creating multiple by using middleware parameters

Docs https://laravel.com/docs/5.3/middleware#middleware-parameters


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...