Implement user policy for updating a users school

This commit is contained in:
Matt Young 2024-05-28 22:48:49 -05:00
parent 06dd3ba574
commit 1b3c25bbdf
4 changed files with 90 additions and 8 deletions

View File

@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use function abort;
use function redirect;
class UserController extends Controller
@ -66,6 +67,8 @@ class UserController extends Controller
public function set_school(Request $request, User $user)
{
if ($request->user()->cannot('set_school',$user)) abort(403);
request()->validate([
'school_id' => ['required','integer','exists:schools,id']
]);

View File

@ -10,7 +10,7 @@ use function is_null;
class SchoolPolicy
{
/**
* Grand admin users access to all functions
* Grant admin users access to all functions
*/
public function before(User $user, string $ability): bool|null
{

View File

@ -0,0 +1,79 @@
<?php
namespace App\Policies;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class UserPolicy
{
/**
* Grant admin users access to all functions
*/
public function before(User $user, string $ability): bool|null
{
if($user->is_admin) return true;
return null;
}
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
//
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, User $model): bool
{
//
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
//
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, User $model): bool
{
//
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, User $model): bool
{
//
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, User $model): bool
{
//
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, User $model): bool
{
//
}
public function set_school(User $user, User $model): bool
{
if($user->school_id) return false;
return $user->id == $model->id;
}
}

View File

@ -1,13 +1,13 @@
@php use App\Models\School;use App\Models\SchoolEmailDomain;use App\Models\User;use Illuminate\Support\Facades\Auth; @endphp
<x-layout.app>
<x-slot:page_title>Test Page</x-slot:page_title>
@php
$x = SchoolEmailDomain::with('school')->where('domain','=',Auth::user()->emailDomain())->get();
foreach ($x as $y)
{
echo "<p>" . $y->school->name . "</p>";
}
@endphp
<form method="POST" action="/users/32/set_school">
@csrf
@method('PATCH')
<input type="text" name="school_id" value="1">
<button>Submit</button>
</form>
</x-layout.app>