Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made package more user friendly #12

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
12 changes: 6 additions & 6 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
DB_CONNECTION=sqlite
#DB_HOST=127.0.0.1
#DB_PORT=3306
#DB_DATABASE=laravel
#DB_USERNAME=root
#DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
Expand Down
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,21 @@ This is a simple app to demonstrate implementing the spatie/laravel-permission p

Many of the code examples used in this demo also come from the examples in the Spatie package README.

## Running Demo
```
composer install
npm install
# Setup your .env file, provided .env.example will work for sqlite
cp -n .env.example .env
touch database/database.sqlite
php artisan key:generate
php artisan db:seed

# Run Dev Server
php artisan serve
```

## Creating Your Own Demo
## Creating Your Own Demo From Scratch
You could create your own with the following steps:

Initial setup:
Expand Down
5 changes: 2 additions & 3 deletions app/Http/Controllers/ExamplesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ class ExamplesController extends Controller
{
public function show_my_roles()
{
// $user = auth()->user();
// or
$user = User::first();

$user = auth()->user();
$roles = $user->getRoleNames();

return var_export($roles, true);
Expand Down
7 changes: 6 additions & 1 deletion app/Models/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@ class Post extends Model

public function scopePublished(Builder $query)
{
return $query->where('published', 1);
//view unpublished posts if user has permission to
if(!auth()->user()?->getAllPermissions()->pluck('name')->contains('view unpublished posts'))
{
return $query->where('published', 1);
}

}

public function author()
Expand Down
4 changes: 2 additions & 2 deletions app/Policies/PostPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ public function create(User $user)
*/
public function update(User $user, Post $post)
{
if ($user->can('edit own posts')) {
return $user->id == $post->user_id;
if ($user->id == $post->user_id) {
return true;
}

if ($user->can('edit all posts')) {
Expand Down
116 changes: 83 additions & 33 deletions database/seeders/PermissionsDemoSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,103 @@
namespace Database\Seeders;

// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class PermissionsDemoSeeder extends Seeder
{
protected User $author;
protected User $admin;
protected User $member;

/**
* Create some roles and permissions.
* Create some roles and permissions, users, posts

*/
public function run(): void
{

$this->setupPermissions();
$this->setupUsers();
$this->setupPosts();

}

protected function setupPermissions(): void
{
// Reset cached roles and permissions
app()[PermissionRegistrar::class]->forgetCachedPermissions();

// create permissions
Permission::create(['name' => 'edit articles']);
Permission::create(['name' => 'delete articles']);
Permission::create(['name' => 'publish articles']);
Permission::create(['name' => 'unpublish articles']);

// create roles and assign existing permissions
$role1 = Role::create(['name' => 'Writer']);
$role1->givePermissionTo('edit articles');
$role1->givePermissionTo('delete articles');

$role2 = Role::create(['name' => 'Admin']);
$role2->givePermissionTo('publish articles');
$role2->givePermissionTo('unpublish articles');

// create a demo user
$user = \App\Models\User::factory()->create([
'name' => 'Example User',
'email' => '[email protected]',
]);
$user->assignRole($role1);


// super admin
Permission::create(['name' => 'assign roles']);
$role3 = Role::create(['name' => 'Super-Admin']);
$role3->givePermissionTo('assign roles');
$admin = \App\Models\User::factory()->create([
'name' => 'Admin User',
'email' => '[email protected]',
]);
$admin->assignRole('Super-Admin');
Permission::findOrCreate('view unpublished posts');
Permission::findOrCreate('create posts');
Permission::findOrCreate('edit own posts');
Permission::findOrCreate('edit all posts');
Permission::findOrCreate('delete own posts');
Permission::findOrCreate('delete any post');

Role::findOrCreate('author')
->givePermissionTo(['create posts', 'edit own posts', 'delete own posts']);

Role::findOrCreate('admin')
->givePermissionTo(['view unpublished posts', 'create posts', 'edit all posts', 'delete any post']);
}

protected function setupUsers(): void
{


$this->author = User::factory()->create([
'name' => 'Example Author',
'email' => '[email protected]',
]);
$this->author->assignRole('author');

$this->admin = User::factory()->create([
'name' => 'Admin User',
'email' => '[email protected]',
]);
$this->admin->assignRole('admin');

$this->member = User::factory()->create([
'name' => 'Example Member',
'email' => '[email protected]',
]);
}

protected function setupPosts()
{
Post::factory()->create([
'title' => 'This is the first post. (author)',
'published' => 1,
'user_id' => $this->author->id,
]);

Post::factory()->create([
'title' => 'This is the second post. (admin)',
'published' => 1,
'user_id' => $this->admin->id,
]);

Post::factory()->create([
'title' => 'This is the third post. (author)',
'published' => 1,
'user_id' => $this->author->id,
]);

Post::factory()->create([
'title' => 'This is the fourth post. (admin, unpublished)',
'published' => 0,
'user_id' => $this->admin->id,
]);

Post::factory()->create([
'title' => 'This is the fifth post. (member)',
'published' => 1,
'user_id' => $this->member->id,
]);
}
}
17 changes: 13 additions & 4 deletions resources/views/permissions-demo.blade.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
@hasrole('writer')
<p>You have been assigned the [writer] role.</p>
@hasrole('author')
<p>You have been assigned the [author] role.</p>
@else
<p>You do NOT have the writer role.</p>
<p>You do NOT have the author role.</p>
@endhasrole

@can('edit articles')
@can('edit all posts')
<p>You have permission to [edit articles].</p>
@else
<p>Sorry, you may NOT edit articles.</p>
@endcan


<div>
<ul>
<li><a href="{{route('showAssignedRoles')}}">Assign Permissions Page</a></li>
<li> <a href="{{route('show')}}">View My Roles</a></li>
<li><a href="{{route('post.index')}}">View Posts</a></li>
</ul>
</div>
2 changes: 2 additions & 0 deletions resources/views/posts/edit.blade.php
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
This would be the edit form for the post:
{{ $post->title }}

<p>If you didn't have the edit articles PERMISSION that the "Writer" ROLE provides you would get a 403 error instead of this page. Try that out by logging in as admin account which won't have this permission and will return a 403 error.</p>
12 changes: 11 additions & 1 deletion resources/views/posts/index.blade.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
@can('edit all posts')
<p>You have permission to [edit all posts]. Clicking Edit Post below will return a edit page</p>
@else
<p>You do NOT have permission to [edit all posts]. Clicking edit below will return a 403 Error UNLESS you own the post. For guests they will get a redirect to login page</p>
@endcan

@foreach($posts as $p)
<p>{{ $p->id }}. {{ $p->title }}</p>
<p>{{ $p->id }}. <a href="{{route('post.show', ['post' => $p->id])}}"> {{ $p->title }}</a> (<a href="{{route('post.edit', ['post' => $p->id])}}">Edit Post</a>)</p>
@endforeach

<p>
<a href="{{route('home')}}" class="">Back to Demo Home Page</a>
</p>
11 changes: 10 additions & 1 deletion resources/views/posts/show.blade.php
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
{{ $post->title }}
<p>Title: <strong>{{ $post->title }}</strong></p>
<p>{{ $post->body }}</p>

@can('edit articles')
<p><a href="{{route('post.edit', ['post' => $p->id])}}">Edit Post</a></p>
@endcan

<p>
<a href="{{route('home')}}" class="">Back to Demo Home Page</a>
</p>
42 changes: 40 additions & 2 deletions resources/views/welcome.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
</style>
</head>
<body class="antialiased">
<div class="relative sm:flex sm:justify-center sm:items-center min-h-screen bg-dots-darker bg-center bg-gray-100 dark:bg-dots-lighter dark:bg-gray-900 selection:bg-red-500 selection:text-white">
<div class="relative sm:flex sm:justify-center sm:items-center min-h-screen bg-dots-darker bg-center bg-gray-100 dark:bg-dots-lighter dark:bg-gray-900 selection:bg-red-500 selection:text-white dark:text-white">
@if (Route::has('login'))
<div class="sm:fixed sm:top-0 sm:right-0 p-6 text-right">
@auth
Expand All @@ -41,10 +41,48 @@
<div class="mt-16">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 lg:gap-8">

@include('permissions-demo')
@hasrole('admin')
<p>You have been assigned the [admin] role.</p>
@else
<p>You do NOT have the admin role.</p>
@endhasrole

@can('edit all posts')
<p>You have permission to [edit all posts].</p>
@else
<p>Sorry, you may NOT edit [edit all posts].</p>
@endcan

</div>


</div>
<div>
<h1 class="text-xl mt-6 font-bold">Example Accounts:</h1>
<div>
<h2 class="text-lg mt-6 mb-4 font-bold">Admin Account with [admin] role</h2>
<p>User: [email protected]</p>
<p>Password: password</p>
</div>
<div>
<h2 class="text-lg mt-6 mb-4 font-bold">Author Account with [author] role</h2>
<p>User: [email protected]</p>
<p>Password: password</p>
</div>
<div>
<h2 class="text-lg mt-6 mb-4 font-bold">Normal Account with No Permissions</h2>
<p>User: [email protected]</p>
<p>Password: password</p>
</div>

</div>
<p class="text-xl text-center btn btn-md btn-danger mt-6">
<a href="{{route('home')}}" class="">View Demo</a>
</p>

<p class="text-xl text-center btn btn-md btn-danger mt-6">
<a href="{{route('post.index')}}" class="">View Posts As Guest User</a>
</p>

<div class="flex justify-center mt-16 px-0 sm:items-center sm:justify-between">
<div class="text-center text-sm text-gray-500 dark:text-gray-400 sm:text-left">
Expand Down
2 changes: 1 addition & 1 deletion tests/Feature/ExamplesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ public function it_responds_to_show_my_roles()

$response->assertStatus(200);
$response->assertSee('Collection');
$response->assertSee('Writer');
$response->assertSee('author');
}
}
12 changes: 6 additions & 6 deletions tests/Feature/PermissionsDemoTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ public function setUp(): void
{
parent::setUp();

$permission = Permission::create(['name' => 'edit articles']);
$role1 = Role::create(['name' => 'writer']);
$permission = Permission::create(['name' => 'edit all posts']);
$role1 = Role::create(['name' => 'admin']);
$role1->givePermissionTo($permission->name);
}

Expand All @@ -28,7 +28,7 @@ public function it_recognizes_blade_hasrole_directive()
{
$response = $this->get('/');

$response->assertSeeText('writer');
$response->assertSeeText('admin');
$response->assertDontSeeText('@hasrole');
}

Expand All @@ -39,7 +39,7 @@ public function it_shows_message_confirming_permission_is_not_granted()
{
$response = $this->get('/');

$response->assertSeeText('Sorry, you may NOT edit articles.');
$response->assertSeeText('Sorry, you may NOT edit [edit all posts]');
}

/**
Expand All @@ -48,13 +48,13 @@ public function it_shows_message_confirming_permission_is_not_granted()
public function it_shows_message_confirming_permission_is_granted()
{
$user = \App\Models\User::factory()->create();
$user->assignRole('writer');
$user->assignRole('admin');

$response = $this->actingAs(\App\Models\User::find($user->id))->get('/');

$response->assertDontSeeText('@hasrole');

$response->assertSeeText("You have permission to [edit articles].");
$response->assertSeeText("You have permission to [edit all posts].");
}

}
Loading