Laravel 5.2:集成委托包,创建角色和权限并访问它

时间:2016-03-22 10:53:09

标签: php laravel-5.2 entrust

我是laravel的全新人物。 我安装了laravel 5.2。我在laravel完成了CRUD。现在我想整合laravel身份验证包。所以我选择zizaco \委托。

我按照文档link中的每个步骤操作。但我不明白出了什么问题。在doc中没有提到我必须在哪个文件中添加以下代码。

$owner = new Role();
$owner->name         = 'owner';
$owner->display_name = 'Project Owner'; // optional
$owner->description  = 'User is the owner of a given project'; // optional
$owner->save();

$admin = new Role();
$admin->name         = 'admin';
$admin->display_name = 'User Administrator'; // optional
$admin->description  = 'User is allowed to manage and edit other users'; // optional
$admin->save();

以及文档中的其他以下代码。

甚至

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract

未提及有关实现类。

我做

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

但我收到了错误

Trait 'App\Authenticatable' not found

新学员无法获得放置代码的位置。我搜索很多,但我不能得到正确方向的完美文件。

在哪里创建角色,权限?有人请帮帮我。

3 个答案:

答案 0 :(得分:11)

  1.Install "zizaco/entrust": "5.2.x-dev"
     2.add provider and aliases in app.php
     3.php artisan vendor:publish
     4.php artisan migrate

现在添加user.php

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;


class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword, EntrustUserTrait;
}

下一步为角色

创建模型
 use Zizaco\Entrust\EntrustRole
        class Role extends EntrustRole
        {
            protected $table = 'roles';
            protected $fillable = ['name', 'display_name', 'description']
        }

现在为permmission创建一个模型

use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
protected $table = 'permissions';
    protected $fillable = ['name', 'display_name', 'description'];
}

现在为角色和权限创建种子表

UserTableSeeder.php
    <?php
    use Illuminate\Database\Seeder;
    use App\Permission;
    use App\Role;
    use App\User;
    class UserTableSeeder extends seeder
    {
        public function run()
        {
            Permission::truncate();
            Role::truncate();
            User::truncate();
            \DB::table('role_user')->delete();
            \DB::table('permission_role')->delete();
//create a user          
  $veeru = User::create([
                'name' => 'veeru',
                'email' => 'something@something.com',
                'password' => bcrypt('qwerty'),
            ]);

    //create a role of admin
            $admin = Role::create([
                'name' => 'admin',
                'display_name' => 'Admin',
                'description' => 'Only one and only admin',
            ]);
//create a permission for role
            $manage_users = Permission::create([
                'name' => 'manage-users-roles-and-permissions',
                'display_name' => 'Manage Users,Roles and Permissions',
                'description' => 'Can manage users,roles and permission"s',
            ]);
    //here attaching permission for admin role
            $admin->attachPermission($manage_users);
//here attaching role for user
            $veeru->attachRole($admin);

    //here iam creating another role and permisssion
            $application = Role::create([
                'name' => 'appapirequestlogs',
                'display_name' => 'AppApiRequestLogs',
                'description' => 'This has full control on Application Core Request logs',
            ]);
            $corereq = Permission::create([
                'name' => 'appapireqlogindex',
                'display_name' => 'AppApiReqLogIndex',
                'description' => 'This has control on Application Core Request Logs index only',
            ]);
    here attaching roles and permissions
            $application->attachPermission($corereq);
            $veeru->attachRole($application);
    }

播种后为角色和权限创建路由文件和控制器

routes.php文件

Route::group(['middleware' => 'web'], function () {
    Route::group(['prefix' => 'admin'], function () {
        Route::controller('roles', 'RolesController');
        Route::controller('permissions', 'PermissionsController');
        Route::controller('users', 'UsersController');
    });
});

RolesController.php

use App\Permission;
use App\Role;
use Illuminate\Http\Request;
use App\Http\Requests;

class RolesController extends Controller
{
    function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:admin');
        $this->middleware('permission:manage-users-roles-and-permissions');
    }

    public function getIndex(Request $request)
    {
        $roles = Role::with('perms')->get();
        return view('roles.index', ['roles' => $roles]);
    }

    public function getCreate()
    {
        return view('roles.create');
    }

    public function postCreate(Request $request)
    {
        $role = Role::create([
            'name' => $request->name,
            'display_name' => $request->display_name,
            'description' => $request->description
        ]);
        return redirect()->to('admin/roles/index');
    }

    public function getUpdate($id)
    {
        $role = Role::findOrFail($id);
        return view('roles.update', ['role' => $role]);
    }

    public function postUpdate(Request $request)
    {
        $role = Role::findOrFail($request->get('id'));
        $role->name = $request->get('name');
        $role->display_name = $request->get('display_name');
        $role->description = $request->get('description');
        $role->save();
        return redirect();
    }

    public function getDelete($id)
    {
        $role = Role::findOrFail($id);
        $role->delete();

        return redirect();
    }

    public function getAttach(Request $request)
    {
        $role = Role::where('id', '=', $request->id)->with('perms')->first();
        $permissions_id = $role->perms->pluck('id')->toArray();
        $permissionsNotAttached = Permission::whereNotIn('id', $permissions_id)->get();
        return view('roles.attach', compact('role', 'permissionsNotAttached'));
    }

    public function postAttach(Request $request)
    {
        $role = Role::findOrFail($request->id);
        $permission = Permission::findOrFail($request->permission);
        $role->attachPermission($permission);
        return redirect();
    }

    public function getDetach(Request $request)
    {
        $role = Role::findOrFail($request->role_id);
        $permission = Permission::findOrFail($request->permission_id);
        $role->detachPermission($permission);
        return redirect()->to('/admin/roles/index');

    }
}

同样创建PermissionsController.php

use App\Http\Requests\PermissionRequest;
use App\Permission;
use App\Http\Requests;


class PermissionsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:admin');
        $this->middleware('permission:manage-users-roles-and-permissions');
    }

    public function getIndex()
    {
        $permissions = Permission::all();
        return view('permissions.index', ['permissions' => $permissions]);
    }

    public function getCreate()
    {
        return view('permissions.create');
    }

    public function postCreate(Request $request)
    {
        $permission = Permission::create([
            'name' => $request->name,
            'display_name' => $request->display_name,
            'description' => $request->description
        ]);

        return redirect();
    }

    public function getUpdate($id)
    {
        $permission = Permission::findOrFail($id);
        return view('permissions.update', ['permission' => $permission]);
    }

    public function postUpdate(Request $request)
    {
        $permission = Permission::findOrFail($request->get('id'));
        $permission->name = $request->get('name');
        $permission->display_name = $request->get('display_name');
        $permission->description = $request->get('description');
        $permission->save();
        return redirect();
    }

    public function getDelete($id)
    {
        $permission = Permission::findOrFail($id);
        $permission->delete();
        return redirect();
    }


}

答案 1 :(得分:4)

创建第一个给定流程后

创建角色中间件示例CheckRole

<?php

namespace App\Http\Middleware;


use Closure;

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param $role
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {


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

            return $next($request);
        } else {
            return response()->view('errors.401');
        }
    }
}

现在创建检查权限

<?php namespace App\Http\Middleware;

use Closure;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param $permission
     * @return mixed
     */
    public function handle($request, Closure $next, $permission)
    {
        if (\Auth::user()->can($permission)) {

            return $next($request);
        } else {
            return response()->view('errors.401');
        }
    }
}

在kernal.php中添加这些中间件

'role' => CheckRole::class,
        'permission' => CheckPermission::class

答案 2 :(得分:0)

现在创建一个带有名称的角色并为其添加权限。 例如:

1.create a role name festivals.
2.now create multiple permissions for that
   ->fesindex (only forr index viewing)
   ->fesedit  (only for edit and update)
   ->fesadd   (only for adding)
   ->fesdelete (only for deleting)
3.now attach which permissions you want to give to that role festivals
4.if you want a user to see only index page then
    for role festivals attach only fesindex
5.if you want a user to see index and add a new festival then create a new role for him and add fesindex and fes add 

现在已创建的权限放在您的控制器中

 function __construct(FestivalRepository $repo)
    {
        $this->middleware('auth');
        $this->middleware('permission:fesindex', ['only' => 'getFestivals']);
        $this->middleware('permission:fesedit', ['only' => ['getFestival', 'postUpdateFestival']]);
        $this->middleware('permission:fesadd', ['only' => ['getAddFestival', 'postAddFestival']]);
        $this->middleware('permission:fesapprove', ['only' => 'getChangeStatus']);
        $this->middleware('permission:fesdelete', ['only' => 'getDeleteFestival']);

    }

这里的getFestivals,getAddFestival等是控制器中的方法。