<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace App\Security\Voter;
use App\Entity\Security\User;
use LogicException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Security;
/**
* Description of UserVoter
*
* @author NOUTCHEU Blaise
*/
class UserVoter extends Voter {
// these strings are just invented: you can use anything
const VIEW = 'view';
const EDIT_PASSWORD = 'ROLE_SECURITY_USER_EDIT_PASSWORD';
private $security;
public function __construct(Security $security) {
$this->security = $security;
}
private function canView(User $user_, User $user) {
if ($this->canEditPassword($user_, $user)) {
return true;
}
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
if ($this->security->isGranted('ROLE_DEV')) {
return true;
}
return false;
}
private function canEditPassword(User $user_, User $user) {
return $user === $user_;
}
protected function supports(string $attribute, $subject): bool {
// if the attribute isn't one we support, return false
if (!in_array($attribute, [self::VIEW, self::EDIT_PASSWORD])) {
return false;
}
// only vote on `User` objects
if (!$subject instanceof User) {
return false;
}
return true;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool {
$user = $token->getUser();
// ROLE_SUPER_ADMIN can do anything! The power!
if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
return true;
}
if ($this->security->isGranted('ROLE_DEV')) {
return true;
}
if (!$user instanceof User) {
// the user must be logged in; if not, deny access
return false;
}
// you know $subject is a User object, thanks to `supports()`
/** @var User $user_ */
$user_ = $subject;
switch ($attribute) {
case self::VIEW:
return $this->canView($user_, $user);
case self::EDIT_PASSWORD:
return $this->canEditPassword($user_, $user);
}
throw new LogicException('This code should not be reached!');
}
}