Implement project memberships teams and permission model
This commit is contained in:
@@ -0,0 +1,247 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions\ProjectPermissions;
|
||||
|
||||
use App\Models\Project;
|
||||
use App\Models\Team;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class ProjectPermissionService
|
||||
{
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public const PERMISSIONS = [
|
||||
'create',
|
||||
'view',
|
||||
'edit',
|
||||
'delete',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function permissions(): array
|
||||
{
|
||||
return self::PERMISSIONS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, array{label: string, value: string}>
|
||||
*/
|
||||
public function permissionOptions(): array
|
||||
{
|
||||
return collect(self::PERMISSIONS)
|
||||
->map(fn (string $permission): array => [
|
||||
'label' => Str::headline($permission),
|
||||
'value' => $permission,
|
||||
])
|
||||
->all();
|
||||
}
|
||||
|
||||
public function grantAllProjectPermissions(Project $project, User $user): void
|
||||
{
|
||||
$this->syncUserPermissions($project, $user, self::PERMISSIONS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $permissions
|
||||
*/
|
||||
public function syncUserPermissions(Project $project, User $user, array $permissions): void
|
||||
{
|
||||
$sanitizedPermissions = $this->sanitizePermissions($permissions);
|
||||
|
||||
DB::transaction(function () use ($project, $user, $sanitizedPermissions): void {
|
||||
DB::table('project_user_permissions')
|
||||
->where('project_id', $project->id)
|
||||
->where('user_id', $user->id)
|
||||
->delete();
|
||||
|
||||
if ($sanitizedPermissions === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('project_user_permissions')->insert(
|
||||
array_map(
|
||||
fn (string $permission): array => [
|
||||
'project_id' => $project->id,
|
||||
'user_id' => $user->id,
|
||||
'permission' => $permission,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
],
|
||||
$sanitizedPermissions,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $permissions
|
||||
*/
|
||||
public function syncTeamPermissions(Project $project, Team $team, array $permissions): void
|
||||
{
|
||||
$sanitizedPermissions = $this->sanitizePermissions($permissions);
|
||||
|
||||
DB::transaction(function () use ($project, $team, $sanitizedPermissions): void {
|
||||
DB::table('project_team_permissions')
|
||||
->where('project_id', $project->id)
|
||||
->where('team_id', $team->id)
|
||||
->delete();
|
||||
|
||||
if ($sanitizedPermissions === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('project_team_permissions')->insert(
|
||||
array_map(
|
||||
fn (string $permission): array => [
|
||||
'project_id' => $project->id,
|
||||
'team_id' => $team->id,
|
||||
'permission' => $permission,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
],
|
||||
$sanitizedPermissions,
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, int> $userIds
|
||||
*/
|
||||
public function syncTeamMembers(Team $team, array $userIds): void
|
||||
{
|
||||
$team->users()->sync($userIds);
|
||||
}
|
||||
|
||||
public function userHasPermission(User $user, Project $project, string $permission): bool
|
||||
{
|
||||
if ($user->is_admin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$sanitizedPermission = Str::lower(trim($permission));
|
||||
|
||||
if (! in_array($sanitizedPermission, self::PERMISSIONS, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$hasDirectPermission = DB::table('project_user_permissions')
|
||||
->where('project_id', $project->id)
|
||||
->where('user_id', $user->id)
|
||||
->where('permission', $sanitizedPermission)
|
||||
->exists();
|
||||
|
||||
if ($hasDirectPermission) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return DB::table('project_team_permissions')
|
||||
->join('team_user', 'team_user.team_id', '=', 'project_team_permissions.team_id')
|
||||
->where('project_team_permissions.project_id', $project->id)
|
||||
->where('team_user.user_id', $user->id)
|
||||
->where('project_team_permissions.permission', $sanitizedPermission)
|
||||
->exists();
|
||||
}
|
||||
|
||||
public function userCanViewProject(User $user, Project $project): bool
|
||||
{
|
||||
if ($user->is_admin) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return in_array($project->id, $this->viewableProjectIds($user), true);
|
||||
}
|
||||
|
||||
public function userCanManageProjectAccess(User $user, Project $project): bool
|
||||
{
|
||||
return $this->userHasPermission($user, $project, 'edit');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function viewableProjectIds(User $user): array
|
||||
{
|
||||
if ($user->is_admin) {
|
||||
return Project::query()->pluck('id')->all();
|
||||
}
|
||||
|
||||
$directProjectIds = DB::table('project_user_permissions')
|
||||
->where('user_id', $user->id)
|
||||
->pluck('project_id');
|
||||
|
||||
$teamProjectIds = DB::table('project_team_permissions')
|
||||
->join('team_user', 'team_user.team_id', '=', 'project_team_permissions.team_id')
|
||||
->where('team_user.user_id', $user->id)
|
||||
->pluck('project_team_permissions.project_id');
|
||||
|
||||
return $directProjectIds
|
||||
->merge($teamProjectIds)
|
||||
->map(fn (mixed $projectId): int => (int) $projectId)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public function userPermissionMap(Project $project): array
|
||||
{
|
||||
/** @var Collection<int, object{user_id: int, permission: string}> $permissions */
|
||||
$permissions = DB::table('project_user_permissions')
|
||||
->select(['user_id', 'permission'])
|
||||
->where('project_id', $project->id)
|
||||
->orderBy('permission')
|
||||
->get();
|
||||
|
||||
return $permissions
|
||||
->groupBy(fn (object $permission): int => (int) $permission->user_id)
|
||||
->map(fn (Collection $group): array => $group
|
||||
->pluck('permission')
|
||||
->values()
|
||||
->all())
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public function teamPermissionMap(Project $project): array
|
||||
{
|
||||
/** @var Collection<int, object{team_id: int, permission: string}> $permissions */
|
||||
$permissions = DB::table('project_team_permissions')
|
||||
->select(['team_id', 'permission'])
|
||||
->where('project_id', $project->id)
|
||||
->orderBy('permission')
|
||||
->get();
|
||||
|
||||
return $permissions
|
||||
->groupBy(fn (object $permission): int => (int) $permission->team_id)
|
||||
->map(fn (Collection $group): array => $group
|
||||
->pluck('permission')
|
||||
->values()
|
||||
->all())
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $permissions
|
||||
* @return array<int, string>
|
||||
*/
|
||||
private function sanitizePermissions(array $permissions): array
|
||||
{
|
||||
return collect($permissions)
|
||||
->map(fn (mixed $permission): string => Str::lower(trim((string) $permission)))
|
||||
->filter(fn (string $permission): bool => in_array($permission, self::PERMISSIONS, true))
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -2,19 +2,42 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Actions\ProjectPermissions\ProjectPermissionService;
|
||||
use App\Http\Requests\StoreProjectRequest;
|
||||
use App\Http\Requests\SyncProjectPermissionsRequest;
|
||||
use App\Models\Project;
|
||||
use App\Models\Team;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class ProjectController extends Controller
|
||||
{
|
||||
public function index(): Response
|
||||
public function __construct(
|
||||
private readonly ProjectPermissionService $projectPermissionService,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$projectQuery = Project::query()
|
||||
->orderByDesc('id');
|
||||
|
||||
if (! $request->user()->is_admin) {
|
||||
$viewableProjectIds = $this->projectPermissionService->viewableProjectIds($request->user());
|
||||
|
||||
if ($viewableProjectIds === []) {
|
||||
return Inertia::render('projects/Index', [
|
||||
'projects' => [],
|
||||
]);
|
||||
}
|
||||
|
||||
$projectQuery->whereIn('id', $viewableProjectIds);
|
||||
}
|
||||
|
||||
return Inertia::render('projects/Index', [
|
||||
'projects' => Project::query()
|
||||
->orderByDesc('id')
|
||||
'projects' => $projectQuery
|
||||
->get(),
|
||||
]);
|
||||
}
|
||||
@@ -27,14 +50,84 @@ class ProjectController extends Controller
|
||||
public function store(StoreProjectRequest $request): RedirectResponse
|
||||
{
|
||||
$project = Project::query()->create($request->validated());
|
||||
$this->projectPermissionService->grantAllProjectPermissions($project, $request->user());
|
||||
|
||||
return to_route('projects.show', $project);
|
||||
}
|
||||
|
||||
public function show(Project $project): Response
|
||||
public function show(Request $request, Project $project): Response
|
||||
{
|
||||
abort_unless(
|
||||
$this->projectPermissionService->userCanViewProject($request->user(), $project),
|
||||
403,
|
||||
);
|
||||
|
||||
return Inertia::render('projects/Show', [
|
||||
'canManageAccess' => $this->projectPermissionService->userCanManageProjectAccess($request->user(), $project),
|
||||
'project' => $project,
|
||||
]);
|
||||
}
|
||||
|
||||
public function access(Request $request, Project $project): Response
|
||||
{
|
||||
abort_unless(
|
||||
$this->projectPermissionService->userCanManageProjectAccess($request->user(), $project),
|
||||
403,
|
||||
);
|
||||
|
||||
return Inertia::render('projects/Access', [
|
||||
'directPermissions' => $this->projectPermissionService->userPermissionMap($project),
|
||||
'permissionOptions' => $this->projectPermissionService->permissionOptions(),
|
||||
'project' => $project,
|
||||
'status' => session('status'),
|
||||
'teamPermissions' => $this->projectPermissionService->teamPermissionMap($project),
|
||||
'teams' => Team::query()
|
||||
->with('users')
|
||||
->orderBy('name')
|
||||
->get()
|
||||
->map(fn (Team $team): array => [
|
||||
'id' => $team->id,
|
||||
'name' => $team->name,
|
||||
'created_at' => $team->created_at?->toISOString(),
|
||||
'updated_at' => $team->updated_at?->toISOString(),
|
||||
'user_ids' => $team->users->modelKeys(),
|
||||
'users' => $team->users->values(),
|
||||
]),
|
||||
'users' => User::query()
|
||||
->orderBy('name')
|
||||
->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function updateUserPermissions(
|
||||
SyncProjectPermissionsRequest $request,
|
||||
Project $project,
|
||||
User $user,
|
||||
): RedirectResponse {
|
||||
abort_unless(
|
||||
$this->projectPermissionService->userCanManageProjectAccess($request->user(), $project),
|
||||
403,
|
||||
);
|
||||
|
||||
$this->projectPermissionService->syncUserPermissions($project, $user, $request->permissions());
|
||||
|
||||
return to_route('projects.access', $project)
|
||||
->with('status', "{$user->name} permissions were updated.");
|
||||
}
|
||||
|
||||
public function updateTeamPermissions(
|
||||
SyncProjectPermissionsRequest $request,
|
||||
Project $project,
|
||||
Team $team,
|
||||
): RedirectResponse {
|
||||
abort_unless(
|
||||
$this->projectPermissionService->userCanManageProjectAccess($request->user(), $project),
|
||||
403,
|
||||
);
|
||||
|
||||
$this->projectPermissionService->syncTeamPermissions($project, $team, $request->permissions());
|
||||
|
||||
return to_route('projects.access', $project)
|
||||
->with('status', "{$team->name} permissions were updated.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Actions\ProjectPermissions\ProjectPermissionService;
|
||||
use App\Http\Requests\StoreTeamRequest;
|
||||
use App\Http\Requests\UpdateTeamMembersRequest;
|
||||
use App\Models\Team;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
class TeamController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ProjectPermissionService $projectPermissionService,
|
||||
) {}
|
||||
|
||||
public function index(): Response
|
||||
{
|
||||
return Inertia::render('teams/Index', [
|
||||
'status' => session('status'),
|
||||
'teams' => Team::query()
|
||||
->with('users')
|
||||
->orderBy('name')
|
||||
->get()
|
||||
->map(fn (Team $team): array => [
|
||||
'id' => $team->id,
|
||||
'name' => $team->name,
|
||||
'created_at' => $team->created_at?->toISOString(),
|
||||
'updated_at' => $team->updated_at?->toISOString(),
|
||||
'user_ids' => $team->users->modelKeys(),
|
||||
'users' => $team->users->values(),
|
||||
]),
|
||||
'users' => User::query()
|
||||
->orderBy('name')
|
||||
->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(StoreTeamRequest $request): RedirectResponse
|
||||
{
|
||||
$team = Team::query()->create($request->validated());
|
||||
|
||||
return to_route('admin.teams.index')
|
||||
->with('status', "{$team->name} was created.");
|
||||
}
|
||||
|
||||
public function updateMembers(UpdateTeamMembersRequest $request, Team $team): RedirectResponse
|
||||
{
|
||||
$this->projectPermissionService->syncTeamMembers($team, $request->userIds());
|
||||
|
||||
return to_route('admin.teams.index')
|
||||
->with('status', "{$team->name} members were updated.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreTeamRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()?->can('access-admin') ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('teams', 'name'),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Actions\ProjectPermissions\ProjectPermissionService;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class SyncProjectPermissionsRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'permissions' => ['nullable', 'array'],
|
||||
'permissions.*' => [
|
||||
'string',
|
||||
Rule::in(ProjectPermissionService::permissions()),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function permissions(): array
|
||||
{
|
||||
return collect($this->validated('permissions', []))
|
||||
->map(fn (mixed $permission): string => (string) $permission)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateTeamMembersRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()?->can('access-admin') ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, ValidationRule|array<mixed>|string>
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'user_ids' => ['nullable', 'array'],
|
||||
'user_ids.*' => ['integer', Rule::exists('users', 'id')],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, int>
|
||||
*/
|
||||
public function userIds(): array
|
||||
{
|
||||
return collect($this->validated('user_ids', []))
|
||||
->map(fn (mixed $userId): int => (int) $userId)
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Database\Factories\TeamFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
#[Fillable(['name'])]
|
||||
class Team extends Model
|
||||
{
|
||||
/** @use HasFactory<TeamFactory> */
|
||||
use HasFactory;
|
||||
|
||||
public function users(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(User::class)
|
||||
->withTimestamps();
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use Database\Factories\UserFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Laravel\Fortify\TwoFactorAuthenticatable;
|
||||
@@ -32,4 +33,10 @@ class User extends Authenticatable
|
||||
'two_factor_confirmed_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
public function teams(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Team::class)
|
||||
->withTimestamps();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user