php Laravel-5 向 Auth 添加 hasRole 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31790234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:36:25  来源:igfitidea点击:

Laravel-5 adding hasRole method to Auth

phplaravellaravel-5.1

提问by V4n1ll4

I'm trying to extend the Laravel-5.1 Authmiddleware so that I can add my own method to it:

我正在尝试扩展 Laravel-5.1Auth中间件,以便我可以向其中添加我自己的方法:

Auth::hasRole()

Auth::hasRole()

What do I need to do in order to add the new method hasRole to Auth?

我需要做什么才能将新方法 hasRole 添加到 Auth?

Here is my routes file:

这是我的路由文件:

/* Administrator Routes */

Route::group(['namespace' => 'Admin', 'middleware' => 'timesheets.admin:Administrator'], function()
{
    Route::get('home', 'AdminController@index');
});

Here is my middleware file:

这是我的中间件文件:

<?php

namespace App\Http\Middleware\Auth;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class AdminAuthenticate
{
    /**
     * 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, $role)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('login');
            }
        }

        if (auth()->check() && auth()->user()->hasRole($role)) {
            return $next($request);
        }

    }
}

回答by jakehallas

Could you try adding the following to your User model:-

您能否尝试将以下内容添加到您的用户模型中:-

public function hasRole($role)
{
    return User::where('role', $role)->get();
}

This should firstly check to see if you User table has the field 'role' and then check your parameter $roleagainst the rolefield.

这应该首先检查您的用户表是否具有字段“角色”,然后$role根据该role字段检查您的参数。

You can the check by doing the following:

您可以通过执行以下操作进行检查:

if( Auth::user()->hasRole($role) )

You may need to adjust the example to your needs. Let me know if you need anything else.

您可能需要根据需要调整示例。需要帮助请叫我。

/------------EDIT-----------------/

/ - - - - - - 编辑 - - - - - - - - -/

If you have two seperate tables, one holding the user information and the other holding the users privileges/roles you could add another function to the User model:

如果您有两个单独的表,一个保存用户信息,另一个保存用户权限/角色,您可以向 User 模型添加另一个功能:

public function userID()
{
    return $this->user_id; 
}

This will check for if you have a user ID field if so, it will return the id for the authenticated user.

这将检查您是否有用户 ID 字段,如果有,它将返回经过身份验证的用户的 ID。

Then add this to your hasRolesmethod:

然后将其添加到您的hasRoles方法中:

    public function hasRoles($userID, $roles)
{
    return Your\User\Roles\Model::where('role', $role)->where('user_id', $user_id)->get();
}

Your middleware would look like this:

你的中间件看起来像这样:

public function handle($request, Closure $next, $role)
{
    if ($this->auth->guest()) {
        if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return redirect()->guest('login');
        }
    }

    $userID = Auth::user()->userID();

    if (auth()->check() && auth()->user()->hasRole($userID, $role)) {
        return $next($request);
    }

}

If I understood correctly what you want. I believe this should work for you.

如果我理解正确你想要什么。我相信这应该对你有用。

回答by mike

I've taken a different tack by using a trait in my Usermodel.

我通过在我的User模型中使用特征采取了不同的策略。

<?php
namespace App\Traits;

use App\Role;
use App\User;

trait HasRoles{
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public static function findByRole(Role $role)
    {
        return $role->users()->get();
    }

    public function hasRole(Role $role)
    {
        return $this->roles()->get()->contains($role);
    }
}

回答by omarjebari

There are some good packages to help with this if you don't want to brew your own. I can recommend both: Zizaco Entrust: https://github.com/Zizaco/entrustand Sentinel: https://cartalyst.com/manual/sentinel/2.0

如果你不想自己酿造,有一些很好的软件包可以帮助解决这个问题。我可以同时推荐:Zizaco Entrust:https: //github.com/Zizaco/entrust和 Sentinel:https://cartalyst.com/manual/sentinel/2.0