Laravel框架 之 权限控制

本文的示例代码参考laravel-permission-demo

目录

  • Startup

  • laravel-permission

  • Model

  • Route

  • Middleware

  • Exception

  • Scope

Startup

docker run --name laravel-permission-demo -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -d mysql:5.7.17

docker exec -i laravel-permission-demo mysql -uroot -psecret  <<< "CREATE DATABASE IF NOT EXISTS homestead DEFAULT CHARSET utf8 COLLATE utf8_general_ci;"

composer create-project laravel/laravel laravel-permission-demo && cd laravel-permission-demo

sed -i "" "s/DB_USERNAME=homestead/DB_USERNAME=root/g" .env
php artisan make:auth

php artisan migrate

php artisan route:list

laravel-permission

composer require spatie/laravel-permission

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="config"

php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider" --tag="migrations"

php artisan migrate
php artisan make:migration seed_roles_and_permissions_data

database/migrations/*seed_roles_and_permissions_data.php
forget('spatie.permission.cache');

        Permission::create(['name' => 'fetch_machines']);
        Permission::create(['name' => 'create_machines']);

        $projectManager = Role::create(['name' => 'project_manager']);
        $projectManager->givePermissionTo('fetch_machines');
        $projectManager->givePermissionTo('create_machines');

        $driver = Role::create(['name' => 'driver']);
        $driver->givePermissionTo('fetch_machines');
    }

    public function down()
    {
        app()['cache']->forget('spatie.permission.cache');

        $tableNames = config('permission.table_names');

        Model::unguard();
        DB::table($tableNames['role_has_permissions'])->delete();
        DB::table($tableNames['model_has_roles'])->delete();
        DB::table($tableNames['model_has_permissions'])->delete();
        DB::table($tableNames['roles'])->delete();
        DB::table($tableNames['permissions'])->delete();
        Model::reguard();
    }
}
php artisan make:seed UsersTableSeeder

vim database/seeds/UsersTableSeeder.php
times(2)
            ->make()
            ->each(function ($user, $index) {
                if ($index === 0) {
                    $user->name = 'test1';
                    $user->email = '[email protected]';
                } else if ($index === 1) {
                    $user->name = 'test2';
                    $user->email = '[email protected]';
                }
            });
        $user_array = $users->makeVisible(['password', 'remember_token'])->toArray();
        User::insert($user_array);

        $user = User::find(1);
        $user->assignRole('project_manager');

        $user = User::find(2);
        $user->assignRole('driver');
    }
}
vim database/seeds/DatabaseSeeder.php
call(UsersTableSeeder::class);
    }
}
vim app/User.php
php artisan migrate:refresh --seed

Model

php artisan make:model Models/Machine --migration
vim app/Models/Machine.php
vim database/migrations/*create_machines_table.php
increments('id');
            $table->string('name');
            $table->unsignedInteger('project_manager_id');
            $table->unsignedInteger('driver_id');
            $table->timestamps();

            $table->foreign('project_manager_id')
                ->references('id')
                ->on('users');
            $table->foreign('driver_id')
                ->references('id')
                ->on('users');
        });
    }

    public function down()
    {
        Schema::dropIfExists('machines');
    }
}
php artisan migrate
php artisan make:seed MachinesTableSeeder

vim database/seeds/MachinesTableSeeder.php
name = 'machine1';
        $machine->project_manager_id = '1';
        $machine->driver_id = '1';
        $machine->save();

        $machine = new Machine();
        $machine->name = 'machine2';
        $machine->project_manager_id = '1';
        $machine->driver_id = '2';
        $machine->save();
    }
}
vim database/seeds/DatabaseSeeder.php
call(UsersTableSeeder::class);
         $this->call(MachinesTableSeeder::class);
    }
}
php artisan migrate:refresh --seed

Route

vim routes/web.php
name('home');

Route::get('/machines', 'MachinesController@index')->name('machines_list');
Route::get('/machines/create', 'MachinesController@create')->name('machines_create');
php artisan make:controller MachinesController

vim app/Http/Controllers/MachinesController.php
middleware('auth');
    }

    public function index()
    {
        return 'machines_list';
    }

    public function create()
    {
        return 'machines_create';
    }
}
php artisan serve
  • 浏览器打开http://localhost:8000/login 登录如下账号
email: [email protected]

password: secret
  • 浏览器打开http://localhost:8000/machines 返回信息如下
machines_list
  • 浏览器打开http://localhost:8000/machines/create 返回信息如下
machines_create

Middleware

vim app/Http/Kernel.php
protected $routeMiddleware = [
    // ...
    'role' => \Spatie\Permission\Middlewares\RoleMiddleware::class,
    'permission' => \Spatie\Permission\Middlewares\PermissionMiddleware::class,
];
vim routes/web.php
name('home');

Route::middleware(['permission:fetch_machines'])->group(function () {
    Route::get('/machines', 'MachinesController@index')->name('machines_list');
});
Route::middleware(['permission:create_machines'])->group(function () {
    Route::get('/machines/create', 'MachinesController@create')->name('machines_create');
});
php artisan serve
  • 浏览器打开http://localhost:8000/login 登录如下账号
email: [email protected]

password: secret
  • 浏览器打开http://localhost:8000/machines 返回信息如下
machines_list
  • 浏览器打开http://localhost:8000/machines/create 返回信息如下
machines_create

浏览器打开http://localhost:8000/home 退出当前登录账号test1

  • 浏览器打开http://localhost:8000/login 登录如下账号
email: [email protected]

password: secret
  • 浏览器打开http://localhost:8000/machines 返回信息如下
machines_list
  • 浏览器打开http://localhost:8000/machines/create 返回信息如下
Spatie \ Permission \ Exceptions \ UnauthorizedException
User does not have the right permissions.

Exception

vim app/Exceptions/Handler.php
json(['message' => 'Unauthenticated'], 401);
        }
        return parent::render($request, $exception);
    }
}
  • 浏览器打开http://localhost:8000/machines/create 返回信息如下
{ message: "Unauthenticated" }

Scope

vim app/Models/RoleScope.php
roles || !$user->roles->count()) {
            return $query;
        }
        return $query->where($user->roles[0]->name . '_id', $user->id);
    }
}
vim app/Models/Machine.php
vim app/Http/Controllers/MachinesController.php
middleware('auth');
    }

    public function index()
    {
        return Machine::role()->get();
    }

    public function create()
    {
        return 'machines_create';
    }
}
php artisan serve
  • 浏览器打开http://localhost:8000/login 登录如下账号
email: [email protected]

password: secret
  • 浏览器打开http://localhost:8000/machines 返回信息如下
[
    {
        "id": 1,
        "name": "machine1",
        "project_manager_id": 1,
        "driver_id": 1,
        "created_at": "2018-07-24 02:22:38",
        "updated_at": "2018-07-24 02:22:38"
    },
    {
        "id": 2,
        "name": "machine2",
        "project_manager_id": 1,
        "driver_id": 2,
        "created_at": "2018-07-24 02:22:38",
        "updated_at": "2018-07-24 02:22:38"
    }
]

浏览器打开http://localhost:8000/home 退出当前登录账号test1

  • 浏览器打开http://localhost:8000/login 登录如下账号
email: [email protected]

password: secret
  • 浏览器打开http://localhost:8000/machines 返回信息如下
[
    {
        "id": 2,
        "name": "machine2",
        "project_manager_id": 1,
        "driver_id": 2,
        "created_at": "2018-07-24 02:22:38",
        "updated_at": "2018-07-24 02:22:38"
    }
]

你可能感兴趣的:(Laravel框架 之 权限控制)