Skip to content

Commit

Permalink
Added policies
Browse files Browse the repository at this point in the history
  • Loading branch information
JakubKermes committed Mar 9, 2024
1 parent 340a2b8 commit 3eb802e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
13 changes: 9 additions & 4 deletions app/Http/Controllers/CityOpinionController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use App\Http\Requests\CityOpinionRequest;
use App\Models\CityOpinion;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;

class CityOpinionController extends Controller
{
Expand All @@ -22,19 +23,23 @@ public function update(CityOpinionRequest $request, CityOpinion $cityOpinion): v
{
$opinion = $request->only(["rating", "content", "city_id"]);

if ($cityOpinion->user_id === Auth::id()) {
$response = Gate::inspect("update", $cityOpinion);

if ($response->allowed()) {
$cityOpinion->update($opinion);
} else {
abort(403);
abort(403, $response->message());
}
}

public function destroy(CityOpinion $cityOpinion): void
{
if ($cityOpinion->user_id === Auth::id() || Auth::user()->hasRole("admin")) {
$response = Gate::inspect("delete", $cityOpinion);

if ($response->allowed()) {
$cityOpinion->delete();
} else {
abort(403);
abort(403, $response->message());
}
}
}
30 changes: 30 additions & 0 deletions app/Policies/CityOpinionPolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\CityOpinion;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class CityOpinionPolicy
{
public function update(User $user, CityOpinion $cityOpinion): Response
{
if ($cityOpinion->user_id !== $user->id) {
return Response::allow();
}

return Response::denyWithStatus(403, "You do not own this opinion");
}

public function delete(User $user, CityOpinion $cityOpinion): Response
{
if ($cityOpinion->user_id === $user->id || $user->hasRole("admin")) {
return Response::allow();
}

return Response::denyWithStatus(403, "You do not own this opinion");
}
}

0 comments on commit 3eb802e

Please sign in to comment.