<?php
namespace App\Security;
use App\Entity\Course;
use App\Entity\User;
use App\Repository\AdminPositionRepository;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
/**
* Checks if a user has admin access based on their IRMS position(s).
*/
class AdminVoter extends Voter
{
private AdminPositionRepository $adminPositionRepository;
public function __construct(AdminPositionRepository $adminPositionRepository)
{
$this->adminPositionRepository = $adminPositionRepository;
}
protected function supports(string $attribute, $subject): bool
{
if ($attribute != 'ADMIN' && $attribute != 'ADMIN_II') {
return false;
}
if ($subject !== null && !$subject instanceof Course) {
return false;
}
return true;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
$user = $token->getUser();
if (!$user instanceof User) {
// must be logged in
return false;
}
if ($attribute == 'ADMIN_II') {
return self::isIIAdmin($user);
}
/** @var ?Course $subject */
if ($subject === null || !$subject->getImperialIntelligence()) {
return $this->isAdmin($user);
}
return self::canSeeCourse($user, $subject);
}
public function canSeeCourse(User $user, Course $course): bool
{
return $course->getImperialIntelligence() ? self::isIIAdmin($user) : self::isAdmin($user);
}
public function isAdmin(User $user): bool
{
$adminRoles = $this->adminPositionRepository->findAllIds();
return !empty(array_intersect($user->getRoles(), $adminRoles));
}
public function isIIAdmin(User $user): bool
{
$iiAdminRoles = $this->adminPositionRepository->findAllImperialIntelligenceIds();
return !empty(array_intersect($user->getRoles(), $iiAdminRoles));
}
}