Skip to content

Commit

Permalink
Add a policy to restrict goal management to owner
Browse files Browse the repository at this point in the history
  • Loading branch information
cdubz committed Nov 10, 2021
1 parent 3f04f14 commit f17fb75
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 6 deletions.
20 changes: 20 additions & 0 deletions app/Policies/GoalPolicy.php
@@ -0,0 +1,20 @@
<?php

namespace App\Policies;

use App\Models\Goal;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class GoalPolicy
{
use HandlesAuthorization;

/**
* Determine whether the user can access (show, edit, delete) the goal.
*/
public function access(User $user, Goal $goal): bool {
return $user->id === $goal->user_id;
}

}
3 changes: 3 additions & 0 deletions app/Providers/AuthServiceProvider.php
Expand Up @@ -2,7 +2,9 @@

namespace App\Providers;

use App\Models\Goal;
use App\Models\User;
use App\Policies\GoalPolicy;
use App\Policies\UserPolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

Expand All @@ -13,6 +15,7 @@ class AuthServiceProvider extends ServiceProvider
* @inheritdoc
*/
protected $policies = [
Goal::class => GoalPolicy::class,
User::class => UserPolicy::class,
];

Expand Down
11 changes: 5 additions & 6 deletions routes/auth.php
Expand Up @@ -26,8 +26,9 @@
Route::get('/foods/{food}/delete', [FoodController::class, 'delete'])->name('foods.delete');

// Goals.
Route::resource('goals', GoalController::class);
Route::get('/goals/{goal}/delete', [GoalController::class, 'delete'])->name('goals.delete');
Route::resource('goals', GoalController::class)->only(['index', 'create', 'store']);
Route::resource('goals', GoalController::class)->except(['index', 'create', 'store'])->middleware(['can:access,goal']);
Route::get('/goals/{goal}/delete', [GoalController::class, 'delete'])->middleware(['can:access,goal'])->name('goals.delete');

// Ingredient picker.
Route::get('/ingredient-picker/search', [IngredientPickerController::class, 'search'])->name('ingredient-picker.search');
Expand All @@ -51,10 +52,8 @@

// Users.
Route::get('/profile/{user}', [ProfileController::class, 'show'])->name('profiles.show');
});

Route::middleware(['auth', 'can:editProfile,user'])->group(function () {
// Profiles (non-admin Users variant).
Route::get('/profile/{user}/edit', [ProfileController::class, 'edit'])->name('profiles.edit');
Route::put('/profile/{user}', [ProfileController::class, 'update'])->name('profiles.update');
Route::get('/profile/{user}/edit', [ProfileController::class, 'edit'])->middleware(['can:editProfile,user'])->name('profiles.edit');
Route::put('/profile/{user}', [ProfileController::class, 'update'])->middleware(['can:editProfile,user'])->name('profiles.update');
});

0 comments on commit f17fb75

Please sign in to comment.