added entrust role based permission

This commit is contained in:
jack
2018-05-07 16:25:42 +08:00
parent a1db64d1c1
commit 3373524bc1
30 changed files with 1200 additions and 92 deletions
+3
View File
@@ -58,5 +58,8 @@ class Kernel extends HttpKernel
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'ability' => 'App\Http\Middleware\TokenEntrustAbility',
'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
];
}
@@ -0,0 +1,39 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;
class TokenEntrustAbility extends BaseMiddleware
{
public function handle($request, Closure $next, $roles, $permissions, $validateAll = false)
{
if (! $token = $this->auth->setRequest($request)->getToken()) {
return $this->respond('tymon.jwt.absent', 'token_not_provided', 400);
}
try {
$user = $this->auth->authenticate($token);
} catch (TokenExpiredException $e) {
return $this->respond('tymon.jwt.expired', 'token_expired', $e->getStatusCode(), [$e]);
} catch (JWTException $e) {
return $this->respond('tymon.jwt.invalid', 'token_invalid', $e->getStatusCode(), [$e]);
}
if (! $user) {
return $this->respond('tymon.jwt.user_not_found', 'user_not_found', 404);
}
if (!$request->user()->ability(explode('|', $roles), explode('|', $permissions), array('validate_all' => $validateAll))) {
return $this->respond('tymon.jwt.invalid', 'token_invalid', 401, 'Unauthorized');
}
$this->events->fire('tymon.jwt.valid', $user);
return $next($request);
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php namespace App;
use Zizaco\Entrust\EntrustPermission;
class Permission extends EntrustPermission
{
}
+7
View File
@@ -0,0 +1,7 @@
<?php namespace App;
use Zizaco\Entrust\EntrustRole;
class Role extends EntrustRole
{
}
+3
View File
@@ -6,10 +6,13 @@ use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Notifications\ResetPassword as ResetPasswordNotification;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
use EntrustUserTrait;
/**
* The attributes that are mass assignable.
+2 -1
View File
@@ -10,7 +10,8 @@
"laravel/framework": "5.6.*",
"laravel/socialite": "^3.0",
"laravel/tinker": "~1.0",
"tymon/jwt-auth": "^1.0.0-rc.2"
"tymon/jwt-auth": "^1.0.0-rc.2",
"zizaco/entrust": "dev-master"
},
"require-dev": {
"filp/whoops": "^2.0",
Generated
+82 -3
View File
@@ -1,10 +1,10 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"content-hash": "777287fc4aaae3154db63f6a9e15bf4d",
"content-hash": "bbcc333ace48de3a56664e9bf1182b6d",
"packages": [
{
"name": "dnoegel/php-xdg-base-dir",
@@ -2882,6 +2882,84 @@
"environment"
],
"time": "2016-09-01T10:05:43+00:00"
},
{
"name": "zizaco/entrust",
"version": "dev-master",
"source": {
"type": "git",
"url": "https://github.com/Zizaco/entrust.git",
"reference": "ba9241426f9c518982d868e2cbac381a9581d802"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Zizaco/entrust/zipball/ba9241426f9c518982d868e2cbac381a9581d802",
"reference": "ba9241426f9c518982d868e2cbac381a9581d802",
"shasum": ""
},
"require": {
"illuminate/cache": "~5.0",
"illuminate/console": "~5.0",
"illuminate/support": "~5.0",
"php": ">=5.5.0"
},
"require-dev": {
"illuminate/database": "~5.0",
"mockery/mockery": "dev-master",
"phpunit/phpunit": "~4.1",
"sami/sami": "dev-master"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Zizaco\\Entrust\\EntrustServiceProvider"
],
"aliases": {
"Entrust": "Zizaco\\Entrust\\EntrustFacade"
}
}
},
"autoload": {
"classmap": [
"src/commands"
],
"psr-4": {
"Zizaco\\Entrust\\": "src/Entrust/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Andrew Elkins",
"homepage": "http://andrewelkins.com"
},
{
"name": "Zizaco Zizuini",
"email": "zizaco@gmail.com"
},
{
"name": "Ben Batschelet",
"homepage": "http://github.com/bbatsche"
},
{
"name": "Michele Angioni",
"email": "michele.angioni@gmail.com"
}
],
"description": "This package provides a flexible way to add Role-based Permissions to Laravel",
"keywords": [
"acl",
"auth",
"illuminate",
"laravel",
"permission",
"roles"
],
"time": "2017-11-13T23:46:19+00:00"
}
],
"packages-dev": [
@@ -4745,7 +4823,8 @@
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {
"tymon/jwt-auth": 5
"tymon/jwt-auth": 5,
"zizaco/entrust": 20
},
"prefer-stable": false,
"prefer-lowest": false,
+3
View File
@@ -157,6 +157,8 @@ return [
* Package Service Providers...
*/
Zizaco\Entrust\EntrustServiceProvider::class,
/*
* Application Service Providers...
*/
@@ -214,6 +216,7 @@ return [
'URL' => Illuminate\Support\Facades\URL::class,
'Validator' => Illuminate\Support\Facades\Validator::class,
'View' => Illuminate\Support\Facades\View::class,
'Entrust' => Zizaco\Entrust\EntrustFacade::class,
],
+1
View File
@@ -68,6 +68,7 @@ return [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'users',
],
// 'users' => [
+92
View File
@@ -0,0 +1,92 @@
<?php
/**
* This file is part of Entrust,
* a role & permission management solution for Laravel.
*
* @license MIT
* @package Zizaco\Entrust
*/
return [
/*
|--------------------------------------------------------------------------
| Entrust Role Model
|--------------------------------------------------------------------------
|
| This is the Role model used by Entrust to create correct relations. Update
| the role if it is in a different namespace.
|
*/
'role' => 'App\Role',
/*
|--------------------------------------------------------------------------
| Entrust Roles Table
|--------------------------------------------------------------------------
|
| This is the roles table used by Entrust to save roles to the database.
|
*/
'roles_table' => 'roles',
/*
|--------------------------------------------------------------------------
| Entrust Permission Model
|--------------------------------------------------------------------------
|
| This is the Permission model used by Entrust to create correct relations.
| Update the permission if it is in a different namespace.
|
*/
'permission' => 'App\Permission',
/*
|--------------------------------------------------------------------------
| Entrust Permissions Table
|--------------------------------------------------------------------------
|
| This is the permissions table used by Entrust to save permissions to the
| database.
|
*/
'permissions_table' => 'permissions',
/*
|--------------------------------------------------------------------------
| Entrust permission_role Table
|--------------------------------------------------------------------------
|
| This is the permission_role table used by Entrust to save relationship
| between permissions and roles to the database.
|
*/
'permission_role_table' => 'permission_role',
/*
|--------------------------------------------------------------------------
| Entrust role_user Table
|--------------------------------------------------------------------------
|
| This is the role_user table used by Entrust to save assigned roles to the
| database.
|
*/
'role_user_table' => 'role_user',
/*
|--------------------------------------------------------------------------
| User Foreign key on Entrust's role_user Table (Pivot)
|--------------------------------------------------------------------------
*/
'user_foreign_key' => 'user_id',
/*
|--------------------------------------------------------------------------
| Role Foreign key on Entrust's role_user Table (Pivot)
|--------------------------------------------------------------------------
*/
'role_foreign_key' => 'role_id',
];
+303
View File
@@ -0,0 +1,303 @@
<?php
/*
* This file is part of jwt-auth.
*
* (c) Sean Tymon <tymon148@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this in your .env file, as it will be used to sign
| your tokens. A helper command is provided for this:
| `php artisan jwt:secret`
|
| Note: This will be used for Symmetric algorithms only (HMAC),
| since RSA and ECDSA use a private/public key combo (See below).
|
*/
'secret' => env('JWT_SECRET'),
/*
|--------------------------------------------------------------------------
| JWT Authentication Keys
|--------------------------------------------------------------------------
|
| The algorithm you are using, will determine whether your tokens are
| signed with a random string (defined in `JWT_SECRET`) or using the
| following public & private keys.
|
| Symmetric Algorithms:
| HS256, HS384 & HS512 will use `JWT_SECRET`.
|
| Asymmetric Algorithms:
| RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
|
*/
'keys' => [
/*
|--------------------------------------------------------------------------
| Public Key
|--------------------------------------------------------------------------
|
| A path or resource to your public key.
|
| E.g. 'file://path/to/public/key'
|
*/
'public' => env('JWT_PUBLIC_KEY'),
/*
|--------------------------------------------------------------------------
| Private Key
|--------------------------------------------------------------------------
|
| A path or resource to your private key.
|
| E.g. 'file://path/to/private/key'
|
*/
'private' => env('JWT_PRIVATE_KEY'),
/*
|--------------------------------------------------------------------------
| Passphrase
|--------------------------------------------------------------------------
|
| The passphrase for your private key. Can be null if none set.
|
*/
'passphrase' => env('JWT_PASSPHRASE'),
],
/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour.
|
| You can also set this to null, to yield a never expiring token.
| Some people may want this behaviour for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'ttl' => env('JWT_TTL', 60),
/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks.
|
| You can also set this to null, to yield an infinite refresh time.
| Some may want this instead of never expiring tokens for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
| See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
| for possible values.
|
*/
'algo' => env('JWT_ALGO', 'HS256'),
/*
|--------------------------------------------------------------------------
| Required Claims
|--------------------------------------------------------------------------
|
| Specify the required claims that must exist in any token.
| A TokenInvalidException will be thrown if any of these claims are not
| present in the payload.
|
*/
'required_claims' => [
'iss',
'iat',
'exp',
'nbf',
'sub',
'jti',
],
/*
|--------------------------------------------------------------------------
| Persistent Claims
|--------------------------------------------------------------------------
|
| Specify the claim keys to be persisted when refreshing a token.
| `sub` and `iat` will automatically be persisted, in
| addition to the these claims.
|
| Note: If a claim does not exist then it will be ignored.
|
*/
'persistent_claims' => [
// 'foo',
// 'bar',
],
/*
|--------------------------------------------------------------------------
| Lock Subject
|--------------------------------------------------------------------------
|
| This will determine whether a `prv` claim is automatically added to
| the token. The purpose of this is to ensure that if you have multiple
| authentication models e.g. `App\User` & `App\OtherPerson`, then we
| should prevent one authentication request from impersonating another,
| if 2 tokens happen to have the same id across the 2 different models.
|
| Under specific circumstances, you may want to disable this behaviour
| e.g. if you only have one authentication model, then you would save
| a little on token size.
|
*/
'lock_subject' => true,
/*
|--------------------------------------------------------------------------
| Leeway
|--------------------------------------------------------------------------
|
| This property gives the jwt timestamp claims some "leeway".
| Meaning that if you have any unavoidable slight clock skew on
| any of your servers then this will afford you some level of cushioning.
|
| This applies to the claims `iat`, `nbf` and `exp`.
|
| Specify in seconds - only if you know you need it.
|
*/
'leeway' => env('JWT_LEEWAY', 0),
/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),
/*
| -------------------------------------------------------------------------
| Blacklist Grace Period
| -------------------------------------------------------------------------
|
| When multiple concurrent requests are made with the same JWT,
| it is possible that some of them fail, due to token regeneration
| on every request.
|
| Set grace period in seconds to prevent parallel request failure.
|
*/
'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),
/*
|--------------------------------------------------------------------------
| Cookies encryption
|--------------------------------------------------------------------------
|
| By default Laravel encrypt cookies for security reason.
| If you decide to not decrypt cookies, you will have to configure Laravel
| to not encrypt your cookie token by adding its name into the $except
| array available in the middleware "EncryptCookies" provided by Laravel.
| see https://laravel.com/docs/master/responses#cookies-and-encryption
| for details.
|
| Set it to true if you want to decrypt cookies.
|
*/
'decrypt_cookies' => false,
/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/
'providers' => [
/*
|--------------------------------------------------------------------------
| JWT Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to create and decode the tokens.
|
*/
'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,
/*
|--------------------------------------------------------------------------
| Authentication Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to authenticate users.
|
*/
'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
/*
|--------------------------------------------------------------------------
| Storage Provider
|--------------------------------------------------------------------------
|
| Specify the provider that is used to store tokens in the blacklist.
|
*/
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
],
];
@@ -0,0 +1,75 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class EntrustSetupTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::beginTransaction();
// Create table for storing roles
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
// Create table for associating roles to users (Many-to-Many)
Schema::create('role_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['user_id', 'role_id']);
});
// Create table for storing permissions
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('display_name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
// Create table for associating permissions to roles (Many-to-Many)
Schema::create('permission_role', function (Blueprint $table) {
$table->integer('permission_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permissions')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('role_id')->references('id')->on('roles')
->onUpdate('cascade')->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
DB::commit();
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('permission_role');
Schema::drop('permissions');
Schema::drop('role_user');
Schema::drop('roles');
}
}
+16
View File
@@ -12,5 +12,21 @@ class DatabaseSeeder extends Seeder
public function run()
{
// $this->call(UsersTableSeeder::class);
Model::unguard();
DB::table('users')->delete();
$users = array(
['name' => 'Ryan Chenkie', 'email' => 'ryanchenkie@gmail.com', 'password' => Hash::make('secret')],
['name' => 'Chris Sevilleja', 'email' => 'chris@scotch.io', 'password' => Hash::make('secret')],
['name' => 'Holly Lloyd', 'email' => 'holly@scotch.io', 'password' => Hash::make('secret')],
['name' => 'Adnan Kukic', 'email' => 'adnan@scotch.io', 'password' => Hash::make('secret')],
);
foreach ($users as $user)
{
User::create($user);
}
Model::reguard();
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+87 -87
View File
File diff suppressed because one or more lines are too long
+16
View File
@@ -0,0 +1,16 @@
<template>
<card :title="$t('home')">
This is admin
</card>
</template>
<script>
export default {
middleware: 'auth',
middleware: 'admin',
metaInfo () {
return { title: this.$t('home') }
}
}
</script>
+59
View File
@@ -0,0 +1,59 @@
<template>
<div>
<div class="top-right links">
<template v-if="authenticated">
<router-link :to="{ name: 'home' }">
{{ $t('home') }}
</router-link>
</template>
<template v-else>
<router-link :to="{ name: 'login' }">
{{ $t('login') }}
</router-link>
<router-link :to="{ name: 'register' }">
{{ $t('register') }}
</router-link>
</template>
</div>
<div class="text-center">
<div class="title mb-4">
This is admin
</div>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
layout: 'basic',
metaInfo () {
return { title: this.$t('home') }
},
data: () => ({
title: window.config.appName
}),
computed: mapGetters({
authenticated: 'auth/check'
})
}
</script>
<style scoped>
.top-right {
position: absolute;
right: 10px;
top: 18px;
}
.title {
font-size: 85px;
}
</style>
+4
View File
@@ -10,6 +10,8 @@ const Settings = () => import('~/pages/settings/index').then(m => m.default || m
const SettingsProfile = () => import('~/pages/settings/profile').then(m => m.default || m)
const SettingsPassword = () => import('~/pages/settings/password').then(m => m.default || m)
const Admin = () => import('~/pages/admin/home').then(m => m.default || m)
export default [
{ path: '/', name: 'welcome', component: Welcome },
@@ -26,6 +28,8 @@ export default [
{ path: 'profile', name: 'settings.profile', component: SettingsProfile },
{ path: 'password', name: 'settings.password', component: SettingsPassword }
] },
{ path: '/admin', name: 'home', component: Home },
{ path: '*', component: NotFound }
]
+1 -1
View File
@@ -17,7 +17,7 @@ Route::group(['middleware' => 'auth:api'], function () {
Route::post('logout', 'Auth\LoginController@logout');
Route::get('/user', function (Request $request) {
return $request->user();
return $request->user()->load('roles');
});
Route::patch('settings/profile', 'Settings\ProfileController@update');