Answer the question
In order to leave comments, you need to log in
Laravel. How to properly authorize actions in the service?
There is the essence of projects. The project has a property with a list of users who work with this project.
Accordingly, there are such operations (permissions):
1. projects.view - viewing the list of projects in which you participate.
2. projects.users.view - viewing the list of project participants
3. projects.users.edit - editing the list of project participants
It turns out that users who have permission projects.view see a list of projects in which they participate.
Some of the users who have permission projects.users.view can also see all the members of this project.
Here is the route:
$options = ['only' => ['index', 'store', 'destroy']];
Route::resource('/projects/{projectId}/users', 'ProjectUsersController', $options)->names('projects.users');
class ProjectUsersController extends Controller
{
public function index(ProfileRepository $profileRepository, $projectId)
{
$this->authorize('projects.users.view');
$project = Project::find($projectId);
$this->authorize('access', $project);
$userIds = $project->users()->select('id')->pluck('id')->toArray();
$users = $profileRepository->getByIds($userIds);
return $users;
}
}
class ProjectPolicy
{
use HandlesAuthorization;
public function access(User $user, Project $project)
{
if ($user->can('projects.view') == false) {
return false;
}
if ($user->id == $project->created_by) {
return true;
}
if ($project->users()->pluck('id')->contains($user->id)) {
return true;
}
return false;
}
}
$this->authorize('projects.users.view');
$project = Project::find($projectId);
$this->authorize('access', $project);
$projectUsersService->getUsers($project);
// далее еще будут добавление и удаление участников
$this->authorize('projects.users.edit');
$project = Project::find($projectId);
$this->authorize('access', $project);
$projectUsersService->addUser($project, $userId);
class ProjectUsersService
{
public function getUsers(ProfileRepository $profileRepository, int $projectId)
{
$project = Project::find($projectId);
if (\Auth::user()->can('access', $project) == false) {
throw new \Exception();
}
$userIds = $project->users()->select('id')->pluck('id')->toArray();
$users = $profileRepository->getByIds($userIds);
return $users;
}
public function addUserInProject(int $projectId, int $userId)
{
$project = Project::find($projectId);
if (\Auth::user()->can('access', $project) == false) {
throw new \Exception();
}
$project->users()->attach($userId);
}
public function deleteUserFromProject(int $projectId, int $userId)
{
$project = Project::find($projectId);
if (\Auth::user()->can('access', $project) == false) {
throw new \Exception();
}
$project->users()->detach($userId);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question