feat: add per-doctor permissions management in clinics
- Implement DoctorPermissionsModal for managing doctor permissions in clinics. - Create usePermissions hook to handle user permissions context. - Add migration for clinic_doctor_permissions table with default permissions. - Develop ClinicDoctorPermissionController for handling permissions API. - Create ClinicDoctorPermission entity to manage permissions data. - Implement ClinicDoctorPermissionRepository for database interactions. - Add ClinicDoctorPermissionChecker for permission validation logic. - Write tests for clinic doctor permissions functionality.
This commit is contained in:
@@ -8,6 +8,8 @@ use App\Auth\Repository\UserActiveContextRepository;
|
||||
use App\Auth\Repository\UserRepository;
|
||||
use App\Auth\Service\OtpService;
|
||||
use App\Auth\Service\TokenService;
|
||||
use App\Clinic\Entity\ClinicDoctorPermission;
|
||||
use App\Clinic\Repository\ClinicDoctorPermissionRepository;
|
||||
use App\Clinic\Repository\ClinicRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Secretary\Repository\DoctorSecretaryRepository;
|
||||
@@ -37,6 +39,7 @@ class AuthController extends BaseController
|
||||
private readonly RateLimiterFactory $passwordResetLimiter,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
private readonly ClinicRepository $clinicRepo,
|
||||
private readonly ClinicDoctorPermissionRepository $clinicDoctorPermRepo,
|
||||
private readonly DoctorSecretaryRepository $secretaryRepo,
|
||||
private readonly UserActiveContextRepository $contextRepo,
|
||||
private readonly UserPasswordHasherInterface $hasher,
|
||||
@@ -703,11 +706,18 @@ class AuthController extends BaseController
|
||||
'name' => 'مطب شخصی ' . $doctor->getName(),
|
||||
'role' => 'doctor',
|
||||
];
|
||||
foreach ($this->clinicRepo->findByDoctor($doctor) as $clinic) {
|
||||
// پزشکِ عضو کلینیک «مالک» نیست؛ نقش doctor با scope کلینیک میگیرد تا
|
||||
// فقط نوبتهای خودش در آن کلینیک را ببیند، نه دسترسی کامل پنل کلینیک.
|
||||
$memberClinics = $this->clinicRepo->findByDoctor($doctor);
|
||||
$permMap = $this->clinicDoctorPermRepo->mapByClinicForDoctor(
|
||||
$doctor,
|
||||
array_map(fn($c) => $c->getId(), $memberClinics),
|
||||
);
|
||||
|
||||
foreach ($memberClinics as $clinic) {
|
||||
// پزشکِ عضو کلینیک «مالک» نیست؛ نقش doctor با scope کلینیک میگیرد و
|
||||
// دسترسیاش را مجوزهای همان کلینیک تعیین میکند، نه hardcode.
|
||||
// اگر همین پزشک مالک کلینیک باشد، نقش کامل clinic در بلوک مالک پایین ست میشود.
|
||||
$isOwner = $clinic->getUser()->getId() === $user->getId();
|
||||
$perm = $permMap[$clinic->getId()] ?? null;
|
||||
$contexts[] = [
|
||||
'type' => 'clinic',
|
||||
'db_uuid' => $clinic->getUuid(),
|
||||
@@ -715,6 +725,7 @@ class AuthController extends BaseController
|
||||
'role' => $isOwner ? 'clinic' : 'doctor',
|
||||
'scope' => $isOwner ? null : 'clinic',
|
||||
'doctor_uuid' => $doctor->getUuid(),
|
||||
'permissions' => $isOwner ? null : $this->contextPermissions($perm),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -764,6 +775,21 @@ class AuthController extends BaseController
|
||||
return $contexts;
|
||||
}
|
||||
|
||||
/**
|
||||
* مجوزی که به کلاینت داده میشود: نبودِ سطر یعنی عضویت قدیمی (پیشفرض)، و
|
||||
* سطر غیرفعال یعنی هیچ دسترسی.
|
||||
*/
|
||||
private function contextPermissions(?ClinicDoctorPermission $perm): array
|
||||
{
|
||||
if ($perm === null) {
|
||||
return ClinicDoctorPermission::DEFAULT_PERMISSIONS;
|
||||
}
|
||||
|
||||
return $perm->isActive()
|
||||
? $perm->getPermissions()
|
||||
: ['version' => 1, 'resources' => []];
|
||||
}
|
||||
|
||||
private function findContextByDbUuid(string $dbUuid, array $contexts): ?array
|
||||
{
|
||||
foreach ($contexts as $ctx) {
|
||||
|
||||
@@ -43,6 +43,8 @@ class ClinicController extends BaseController
|
||||
private readonly CityRepository $cityRepo,
|
||||
private readonly UserRepository $userRepo,
|
||||
private readonly WeeklyScheduleRepository $scheduleRepo,
|
||||
private readonly \App\Clinic\Repository\ClinicDoctorPermissionRepository $permRepo,
|
||||
private readonly \App\Clinic\Security\ClinicDoctorPermissionChecker $permChecker,
|
||||
private readonly FileValidatorService $fileValidator,
|
||||
private readonly \App\Representation\Service\DomainContextResolver $domainResolver,
|
||||
private readonly string $projectDir,
|
||||
@@ -210,7 +212,8 @@ class ClinicController extends BaseController
|
||||
return $this->error(ErrorCodes::ERR_VALIDATION_002, 'کلینیک یافت نشد', 404);
|
||||
}
|
||||
|
||||
if ($clinic->getUser()->getId() !== $user->getId() && !$user->hasRole('ROLE_ADMIN')) {
|
||||
// مالک و ادمین همیشه؛ پزشکِ عضو فقط با مجوز clinic_info.update
|
||||
if (!$this->permChecker->can($user, $clinic, 'clinic_info', 'update')) {
|
||||
return $this->error(ErrorCodes::ERR_AUTH_006, 'دسترسی ممنوع', 403);
|
||||
}
|
||||
|
||||
@@ -377,6 +380,7 @@ class ClinicController extends BaseController
|
||||
|
||||
$clinic->removeDoctor($doctor);
|
||||
$this->clinicRepo->save($clinic);
|
||||
$this->permRepo->deleteFor($clinic, $doctor);
|
||||
|
||||
return $this->success(['message' => 'پزشک از کلینیک جدا شد']);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Clinic\Controller;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Clinic\Entity\Clinic;
|
||||
use App\Clinic\Entity\ClinicDoctorPermission;
|
||||
use App\Clinic\Repository\ClinicDoctorPermissionRepository;
|
||||
use App\Clinic\Repository\ClinicRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Controller\BaseController;
|
||||
use App\Shared\Exception\AppException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use OpenApi\Attributes as OA;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\CurrentUser;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
|
||||
#[OA\Tag(name: 'Clinic Doctor Permissions')]
|
||||
class ClinicDoctorPermissionController extends BaseController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClinicRepository $clinicRepo,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
private readonly ClinicDoctorPermissionRepository $permRepo,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
#[Route('/api/v1/admin/clinic/{clinicUuid}/doctor-permissions', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function listPermissions(string $clinicUuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$clinic = $this->resolveClinic($clinicUuid, $user);
|
||||
|
||||
$data = array_map(
|
||||
fn(ClinicDoctorPermission $p) => $p->toArray(),
|
||||
$this->permRepo->findByClinic($clinic),
|
||||
);
|
||||
|
||||
return $this->success($data);
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/clinic/{clinicUuid}/doctor/{doctorUuid}/permissions', methods: ['GET'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function showPermissions(string $clinicUuid, string $doctorUuid, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$clinic = $this->resolveClinic($clinicUuid, $user);
|
||||
$doctor = $this->resolveMember($clinic, $doctorUuid);
|
||||
|
||||
return $this->success($this->permRepo->getOrCreate($clinic, $doctor)->toArray());
|
||||
}
|
||||
|
||||
#[Route('/api/v1/admin/clinic/{clinicUuid}/doctor/{doctorUuid}/permissions', methods: ['PATCH'])]
|
||||
#[IsGranted('IS_AUTHENTICATED_FULLY')]
|
||||
public function updatePermissions(string $clinicUuid, string $doctorUuid, Request $request, #[CurrentUser] User $user): JsonResponse
|
||||
{
|
||||
$clinic = $this->resolveClinic($clinicUuid, $user);
|
||||
$doctor = $this->resolveMember($clinic, $doctorUuid);
|
||||
$perm = $this->permRepo->getOrCreate($clinic, $doctor);
|
||||
|
||||
$body = json_decode($request->getContent(), true) ?? [];
|
||||
|
||||
if (array_key_exists('permissions', $body)) {
|
||||
if (!is_array($body['permissions'])) {
|
||||
throw new AppException(ErrorCodes::ERR_VALIDATION_001, 'permissions باید آبجکت باشد', 422, 'permissions');
|
||||
}
|
||||
$perm->mergePermissions($body['permissions']);
|
||||
}
|
||||
|
||||
if (array_key_exists('active', $body)) {
|
||||
$perm->setActive((bool) $body['active']);
|
||||
}
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
return $this->success($perm->toArray());
|
||||
}
|
||||
|
||||
private function resolveClinic(string $clinicUuid, User $user): Clinic
|
||||
{
|
||||
$clinic = $this->clinicRepo->findByUuid($clinicUuid);
|
||||
if ($clinic === null) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'کلینیک یافت نشد', 404);
|
||||
}
|
||||
|
||||
$isOwner = $clinic->getUser()->getId() === $user->getId();
|
||||
if (!$user->hasRole('ROLE_ADMIN') && !$isOwner) {
|
||||
throw new AppException(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ندارید', 403);
|
||||
}
|
||||
|
||||
return $clinic;
|
||||
}
|
||||
|
||||
private function resolveMember(Clinic $clinic, string $doctorUuid): \App\Doctor\Entity\Doctor
|
||||
{
|
||||
$doctor = $this->doctorRepo->findByUuid($doctorUuid);
|
||||
if ($doctor === null || !$clinic->hasDoctor($doctor)) {
|
||||
throw new AppException(ErrorCodes::ERR_NOT_FOUND_001, 'این پزشک به کلینیک متصل نیست', 404);
|
||||
}
|
||||
|
||||
return $doctor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
<?php
|
||||
|
||||
namespace App\Clinic\Entity;
|
||||
|
||||
use App\Clinic\Repository\ClinicDoctorPermissionRepository;
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
/**
|
||||
* سطح دسترسی یک پزشکِ عضو در یک کلینیک مشخص.
|
||||
*
|
||||
* جدول join «clinic_doctors» عمداً دستنخورده میماند (شش نقطه در کد به ManyToMany
|
||||
* آن وابستهاند)؛ این جدول موازی فقط مجوزها را نگه میدارد.
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: ClinicDoctorPermissionRepository::class)]
|
||||
#[ORM\Table(name: 'clinic_doctor_permissions')]
|
||||
#[ORM\UniqueConstraint(name: 'uniq_clinic_doctor_permission', columns: ['clinic_id', 'doctor_id'])]
|
||||
class ClinicDoctorPermission
|
||||
{
|
||||
public const DEFAULT_PERMISSIONS = [
|
||||
'version' => 1,
|
||||
'resources' => [
|
||||
'appointments' => ['view' => true, 'create' => true, 'cancel' => true, 'update_status' => true],
|
||||
'appointment_settings' => ['view' => true, 'update' => true],
|
||||
'patients' => ['view' => true, 'create' => true, 'update' => true, 'delete' => false],
|
||||
'payments' => ['view' => true, 'create' => false, 'update' => false, 'delete' => false],
|
||||
'services' => ['view' => true, 'update' => false],
|
||||
'clinic_info' => ['view' => true, 'update' => false],
|
||||
],
|
||||
];
|
||||
|
||||
#[ORM\Id]
|
||||
#[ORM\GeneratedValue]
|
||||
#[ORM\Column(type: 'integer')]
|
||||
private ?int $id = null;
|
||||
|
||||
#[ORM\Column(type: 'string', length: 36, unique: true)]
|
||||
private string $uuid;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Clinic::class)]
|
||||
#[ORM\JoinColumn(name: 'clinic_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private Clinic $clinic;
|
||||
|
||||
#[ORM\ManyToOne(targetEntity: Doctor::class)]
|
||||
#[ORM\JoinColumn(name: 'doctor_id', referencedColumnName: 'id', nullable: false, onDelete: 'CASCADE')]
|
||||
private Doctor $doctor;
|
||||
|
||||
#[ORM\Column(name: 'permission', type: 'json')]
|
||||
private array $permissions;
|
||||
|
||||
#[ORM\Column(type: 'boolean')]
|
||||
private bool $active = true;
|
||||
|
||||
#[ORM\Column(name: 'created_at', type: 'integer')]
|
||||
private int $createdAt;
|
||||
|
||||
#[ORM\Column(name: 'updated_at', type: 'integer')]
|
||||
private int $updatedAt;
|
||||
|
||||
public function __construct(Clinic $clinic, Doctor $doctor)
|
||||
{
|
||||
$this->uuid = Uuid::v4()->toRfc4122();
|
||||
$this->clinic = $clinic;
|
||||
$this->doctor = $doctor;
|
||||
$this->permissions = self::DEFAULT_PERMISSIONS;
|
||||
$this->createdAt = time();
|
||||
$this->updatedAt = time();
|
||||
}
|
||||
|
||||
public function getId(): ?int { return $this->id; }
|
||||
public function getUuid(): string { return $this->uuid; }
|
||||
public function getClinic(): Clinic { return $this->clinic; }
|
||||
public function getDoctor(): Doctor { return $this->doctor; }
|
||||
public function getPermissions(): array { return $this->permissions; }
|
||||
public function isActive(): bool { return $this->active; }
|
||||
public function getCreatedAt(): int { return $this->createdAt; }
|
||||
public function getUpdatedAt(): int { return $this->updatedAt; }
|
||||
|
||||
public function setActive(bool $v): self { $this->active = $v; $this->touch(); return $this; }
|
||||
|
||||
public function can(string $resource, string $action): bool
|
||||
{
|
||||
if (!$this->active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (bool) ($this->permissions['resources'][$resource][$action] ?? false);
|
||||
}
|
||||
|
||||
/** ادغام عمقی — فقط منابع/اکشنهایی که ارسال شدهاند تغییر میکنند. */
|
||||
public function mergePermissions(array $patch): void
|
||||
{
|
||||
$current = $this->permissions;
|
||||
$resources = $patch['resources'] ?? $patch;
|
||||
|
||||
foreach ($resources as $resource => $actions) {
|
||||
if (!is_array($actions) || !isset(self::DEFAULT_PERMISSIONS['resources'][$resource])) {
|
||||
continue;
|
||||
}
|
||||
foreach ($actions as $action => $value) {
|
||||
if (!array_key_exists($action, self::DEFAULT_PERMISSIONS['resources'][$resource])) {
|
||||
continue;
|
||||
}
|
||||
$current['resources'][$resource][$action] = (bool) $value;
|
||||
}
|
||||
}
|
||||
|
||||
$this->permissions = $current;
|
||||
$this->touch();
|
||||
}
|
||||
|
||||
private function touch(): void { $this->updatedAt = time(); }
|
||||
|
||||
/**
|
||||
* envelope کامل برگردانده میشود (نه flatten) تا کلاینت همهجا با یک شکل واحد
|
||||
* روبهرو باشد — برخلاف DoctorSecretary::toArray که آن را تخت میکند.
|
||||
*/
|
||||
public function toArray(): array
|
||||
{
|
||||
return [
|
||||
'uuid' => $this->uuid,
|
||||
'clinic_uuid' => $this->clinic->getUuid(),
|
||||
'doctor_uuid' => $this->doctor->getUuid(),
|
||||
'doctor_name' => $this->doctor->getName(),
|
||||
'active' => $this->active,
|
||||
'permissions' => $this->permissions,
|
||||
'created_at' => $this->createdAt,
|
||||
'updated_at' => $this->updatedAt,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Clinic\Repository;
|
||||
|
||||
use App\Clinic\Entity\Clinic;
|
||||
use App\Clinic\Entity\ClinicDoctorPermission;
|
||||
use App\Doctor\Entity\Doctor;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<ClinicDoctorPermission>
|
||||
*/
|
||||
class ClinicDoctorPermissionRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, ClinicDoctorPermission::class);
|
||||
}
|
||||
|
||||
public function findOneFor(Clinic $clinic, Doctor $doctor): ?ClinicDoctorPermission
|
||||
{
|
||||
return $this->findOneBy(['clinic' => $clinic, 'doctor' => $doctor]);
|
||||
}
|
||||
|
||||
/** @return ClinicDoctorPermission[] */
|
||||
public function findByClinic(Clinic $clinic): array
|
||||
{
|
||||
return $this->findBy(['clinic' => $clinic]);
|
||||
}
|
||||
|
||||
/**
|
||||
* پزشکانی که پیش از این قابلیت عضو شدهاند سطر مجوز ندارند؛ در اولین دسترسی
|
||||
* با مجوز پیشفرض ساخته میشود.
|
||||
*/
|
||||
public function getOrCreate(Clinic $clinic, Doctor $doctor): ClinicDoctorPermission
|
||||
{
|
||||
$perm = $this->findOneFor($clinic, $doctor);
|
||||
if ($perm !== null) {
|
||||
return $perm;
|
||||
}
|
||||
|
||||
$perm = new ClinicDoctorPermission($clinic, $doctor);
|
||||
$em = $this->getEntityManager();
|
||||
$em->persist($perm);
|
||||
$em->flush();
|
||||
|
||||
return $perm;
|
||||
}
|
||||
|
||||
/**
|
||||
* مجوزهای یک پزشک در چند کلینیک، کلیددار با شناسهٔ کلینیک — برای پرهیز از N+1
|
||||
* هنگام ساخت available_contexts.
|
||||
*
|
||||
* @param int[] $clinicIds
|
||||
* @return array<int, ClinicDoctorPermission>
|
||||
*/
|
||||
public function mapByClinicForDoctor(Doctor $doctor, array $clinicIds): array
|
||||
{
|
||||
if ($clinicIds === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->createQueryBuilder('p')
|
||||
->andWhere('p.doctor = :doctor')
|
||||
->andWhere('IDENTITY(p.clinic) IN (:clinics)')
|
||||
->setParameter('doctor', $doctor)
|
||||
->setParameter('clinics', $clinicIds)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
$map = [];
|
||||
foreach ($rows as $row) {
|
||||
$map[$row->getClinic()->getId()] = $row;
|
||||
}
|
||||
|
||||
return $map;
|
||||
}
|
||||
|
||||
public function deleteFor(Clinic $clinic, Doctor $doctor): void
|
||||
{
|
||||
$perm = $this->findOneFor($clinic, $doctor);
|
||||
if ($perm === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$em = $this->getEntityManager();
|
||||
$em->remove($perm);
|
||||
$em->flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Clinic\Security;
|
||||
|
||||
use App\Auth\Entity\User;
|
||||
use App\Clinic\Entity\Clinic;
|
||||
use App\Clinic\Repository\ClinicDoctorPermissionRepository;
|
||||
use App\Doctor\Repository\DoctorRepository;
|
||||
use App\Shared\Constant\ErrorCodes;
|
||||
use App\Shared\Exception\AppException;
|
||||
|
||||
/**
|
||||
* تصمیمگیرندهٔ واحد برای «این کاربر در این کلینیک اجازهٔ فلان کار را دارد؟».
|
||||
*
|
||||
* مالک کلینیک و ادمین همیشه مجازند — مالک هرگز نباید بتواند خودش را قفل کند.
|
||||
*/
|
||||
class ClinicDoctorPermissionChecker
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClinicDoctorPermissionRepository $permRepo,
|
||||
private readonly DoctorRepository $doctorRepo,
|
||||
) {}
|
||||
|
||||
public function can(User $user, Clinic $clinic, string $resource, string $action): bool
|
||||
{
|
||||
if ($user->hasRole('ROLE_ADMIN') || $clinic->getUser()->getId() === $user->getId()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$doctor = $this->doctorRepo->findByUser($user);
|
||||
if ($doctor === null || !$clinic->hasDoctor($doctor)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->permRepo->getOrCreate($clinic, $doctor)->can($resource, $action);
|
||||
}
|
||||
|
||||
public function assert(User $user, Clinic $clinic, string $resource, string $action): void
|
||||
{
|
||||
if (!$this->can($user, $clinic, $resource, $action)) {
|
||||
throw new AppException(ErrorCodes::ERR_ACCESS_DENIED, 'دسترسی ندارید', 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user