【问题标题】:Laravel 5 - Authenticate against two tablesLaravel 5 - 针对两个表进行身份验证
【发布时间】:2017-06-14 22:55:03
【问题描述】:

我对 Laravel 有点陌生,并且在以我想要的方式验证用户时遇到了问题。我的数据库中目前有一个用户表和一个公司表。

我已经看到许多基于用户是否是管理员使用 gaurds 对多个表进行身份验证的示例,但我希望通过以下方式对所有用户进行身份验证:

  1. 用户的emailpassword 匹配(用户表中的字段)
  2. 用户的status 当前处于活动状态(用户表中的字段)
  3. 用户属于具有活动status 的公司(公司表中的字段)

【问题讨论】:

    标签: authentication laravel-5.3


    【解决方案1】:

    自从我发布这个问题以来,我一直在尽可能多地进行研究,最终得到了一个令人满意的解决方案。我不确定这是否是最干净的方式,但它对我有用。如果其他人可以从中受益,以下是我采取的步骤:

    1) 我在app\User.php 模型中添加了以下代码:

       # company / user relationship
       public function company() {
          return $this->belongsTo('App\Company', 'comp_id');
       }
    
       # determine if company is active
       public function activeCompany() {
          $comp_stat = $this->company()->first(['status'])->toArray();
    
          return ($comp_stat >= 1) ? true : false;
       }
    

    然后我修改了app\Http\Middleware\Authenticate.php中的handle方法如下:

       public function handle($request, Closure $next, $guard = null) {
          if (Auth::guard($guard)->guest()) {
             if ($request->ajax() || $request->wantsJson()) {
                return response('Unauthorized.', 401);
             } else {
                return redirect()->guest('login');
             }
          }
    
          /* begin modified section */
    
          if (Auth::check()) {
             # logout if company is inactive
             if (!auth()->user()->activeCompany()) {
                Auth::logout();
                return redirect()->guest('login')->with('comp-status-error', true);
             }
    
             # logout if user is inactive
             if (auth()->user()->status != 1) {
                Auth::logout();
                return redirect()->guest('login')->with('user-status-error', true);
             }
          }
    
          /* end modified section */
    
          return $next($request);
       }
    

    因此,从技术上讲,用户在公司和用户状态检查之前已经通过身份验证,这就是您必须手动调用 Auth::logout() 的原因。这也是为什么它让我感觉有点“脏”的原因,但同样,我想不出任何其他方法,所以我不得不做有效的事情!如果他们看到更好的方法来实现这一点,我鼓励任何人发表评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-03
      • 1970-01-01
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 2020-01-14
      • 2018-07-03
      相关资源
      最近更新 更多