【问题标题】:What is the best way to configure route restriction in PHP Laravel 5?在 PHP Laravel 5 中配置路由限制的最佳方法是什么?
【发布时间】:2015-09-05 18:54:06
【问题描述】:

我是 Laravel 5 中间件的新手——我最近刚刚在我的应用程序中添加了一个新的 user type == Dev。我需要为该用户类型设置一定的路线限制 - 就他们可以/不能访问的内容而言。


所以我创造

DevMiddleware.php

<?php

namespace App\Http\Middleware;

use App\Article;
use Closure, View ;
use Illuminate\Contracts\Auth\Guard;

class DevMiddleware
{
    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     * @return void
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->auth->getUser()->type !== "Dev") {
            return View::make('errors.404');
        }

        return $next($request);
    }
}

我已经注册了

内核.php

'dev' =&gt; 'App\Http\Middleware\DevMiddleware',


我用在我的

Routes.php

$router->group(['middleware' => ['auth', 'admin', 'dev' ] ], function() {

    //Any routes goes in here

});

当我去那里的那些路线时 - 不断收到 404 错误。

我希望能够去那些路线。

我在这里做错了什么?我该如何解决?

【问题讨论】:

  • 代替getUser() 试试user()。 API 状态 getUser() 返回当前缓存的用户,我不完全确定这究竟意味着什么。 user() 返回当前登录的用户,这可能是您真正想要的。
  • 现在试试。如果它有效,我会回复你。
  • 不工作!我也尝试Auth::user()-&gt;type == "Dev" 也不起作用。
  • 尝试mail自己或单步执行代码以查看Auth::user()-&gt;type 返回的内容。也许会有所帮助。

标签: php laravel laravel-5 laravel-routing middleware


【解决方案1】:

您有 3 个中间件在那里运行,但您假设 DEV 一个失败了。粘贴其他 2 的内容。另外,您正在使用:

$this->auth->getUser()->type

那有什么作用?如果用户是管理员,它可能在 DEV 中间件上失败(或相反)。

P.S:如果您需要处理角色,我建议您使用 Entrust Package。

【讨论】:

    【解决方案2】:

    您是否对其他中间件使用相同的逻辑?如果是这样,那么逻辑将像 OR 语句一样,如果 'auth' 失败,或 'admin' 失败,或 'dev' 失败,则 404。

    我不确定处理您想要的“最佳”方式,但我有一个来自开源项目的示例; laravel-5-boilerplate:

    Route::group([
            'middleware' => 'access.routeNeedsRole',
            'role'       => ['admin', 'dev'],
            'redirect'   => '/',
            'with'       => ['flash_danger', 'You do not have access to do that.']
        ], function ()
        {
        //Any routes goes in here
        });
    

    【讨论】:

      猜你喜欢
      • 2015-08-14
      • 2020-02-12
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 2012-10-14
      • 2010-10-10
      • 1970-01-01
      • 2015-10-21
      相关资源
      最近更新 更多