cs: Fix code style (safe rules only).

This commit is contained in:
Pol Dellaiera
2021-11-23 14:06:38 +01:00
parent 149d7ce991
commit 8f96a1121d
1223 changed files with 65199 additions and 64625 deletions

View File

@@ -1,12 +1,20 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Authorization;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use function get_class;
use function in_array;
/**
* Voter for Chill software.
@@ -17,15 +25,17 @@ abstract class AbstractChillVoter extends Voter implements ChillVoterInterface
{
protected function supports($attribute, $subject)
{
@trigger_error('This voter should implements the new `supports` '
@trigger_error(
'This voter should implements the new `supports` '
. 'methods introduced by Symfony 3.0, and do not rely on '
. 'getSupportedAttributes and getSupportedClasses methods.',
E_USER_DEPRECATED);
E_USER_DEPRECATED
);
// @TODO: getSupportedAttributes() should be created in here and made abstract or in ChillVoterInterface.
// @TODO: getSupportedClasses() should be created in here and made abstract or in ChillVoterInterface.
return \in_array($attribute, $this->getSupportedAttributes($attribute))
&& \in_array(\get_class($subject), $this->getSupportedClasses());
return in_array($attribute, $this->getSupportedAttributes($attribute))
&& in_array(get_class($subject), $this->getSupportedClasses());
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)

View File

@@ -1,19 +1,29 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Authorization;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Repository\UserACLAwareRepositoryInterface;
use Chill\MainBundle\Security\ParentRoleHelper;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcherInterface;
use Chill\MainBundle\Security\Resolver\ScopeResolverDispatcher;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Role\Role;
use Chill\MainBundle\Entity\Scope;
use Symfony\Component\Security\Core\User\UserInterface;
use Traversable;
use UnexpectedValueException;
use function array_merge;
/**
* Helper for authorizations.
@@ -24,14 +34,14 @@ class AuthorizationHelper implements AuthorizationHelperInterface
{
private CenterResolverDispatcherInterface $centerResolverDispatcher;
private ScopeResolverDispatcher $scopeResolverDispatcher;
private LoggerInterface $logger;
private UserACLAwareRepositoryInterface $userACLAwareRepository;
private ParentRoleHelper $parentRoleHelper;
private ScopeResolverDispatcher $scopeResolverDispatcher;
private UserACLAwareRepositoryInterface $userACLAwareRepository;
public function __construct(
CenterResolverDispatcherInterface $centerResolverDispatcher,
LoggerInterface $logger,
@@ -47,168 +57,11 @@ class AuthorizationHelper implements AuthorizationHelperInterface
}
/**
* Determines if a user is active on this center
*
* @param Center|Center[] $center May be an array of center
*/
public function userCanReachCenter(User $user, $center): bool
{
if ($center instanceof \Traversable) {
foreach ($center as $c) {
if ($c->userCanReachCenter($user, $c)) {
return true;
}
}
return false;
}
if ($center instanceof Center) {
foreach ($user->getGroupCenters() as $groupCenter) {
if ($center->getId() === $groupCenter->getCenter()->getId()) {
return true;
}
}
return false;
}
throw new \UnexpectedValueException(
sprintf(
'The entity given is not an instance of %s, %s given',
Center::class,
get_class($center)
)
);
}
/**
* Determines if the user has access to the given entity.
*
* if the entity implements Chill\MainBundle\Entity\HasScopeInterface,
* the scope is taken into account.
*
* @param User $user
* @param mixed $entity the entity may also implement HasScopeInterface
* @param string|Role $attribute
* @return boolean true if the user has access
*/
public function userHasAccess(User $user, $entity, $attribute)
{
$center = $this->centerResolverDispatcher->resolveCenter($entity);
if (is_iterable($center)) {
foreach ($center as $c) {
if ($this->userHasAccessForCenter($user, $c, $entity, $attribute)) {
return true;
}
}
return false;
} elseif ($center instanceof Center) {
return $this->userHasAccessForCenter($user, $center, $entity, $attribute);
} elseif (NULL === $center) {
return false;
} else {
throw new \UnexpectedValueException("could not resolver a center");
}
}
private function userHasAccessForCenter(User $user, Center $center, $entity, $attribute): bool
{
if (!$this->userCanReachCenter($user, $center)) {
$this->logger->debug("user cannot reach center of entity", [
'center_name' => $center->getName(),
'user' => $user->getUsername()
]);
return false;
}
foreach ($user->getGroupCenters() as $groupCenter){
//filter on center
if ($groupCenter->getCenter() === $center) {
$permissionGroup = $groupCenter->getPermissionsGroup();
//iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role allow to reach the required role
if ($this->isRoleReached($attribute, $roleScope->getRole())) {
//if yes, we have a right on something...
// perform check on scope if necessary
if ($this->scopeResolverDispatcher->isConcerned($entity)) {
$scope = $this->scopeResolverDispatcher->resolveScope($entity);
if (NULL === $scope) {
return true;
}
if (is_iterable($scope)) {
foreach ($scope as $s) {
if ($s === $roleScope->getScope()) {
return true;
}
}
} else {
if ($scope === $roleScope->getScope()) {
return true;
}
}
} else {
return true;
}
}
}
}
}
$this->logger->debug("user can reach center entity, but not role", [
'username' => $user->getUsername(),
'center' => $center->getName()
]);
return false;
}
/**
* Get reachable Centers for the given user, role,
* and optionally Scope
*
* @return Center[]|array
*/
public function getReachableCenters(UserInterface $user, string $role, ?Scope $scope = null): array
{
if ($role instanceof Role) {
$role = $role->getRole();
}
$centers = array();
foreach ($user->getGroupCenters() as $groupCenter){
$permissionGroup = $groupCenter->getPermissionsGroup();
//iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role is in the reachable roles
if ($this->isRoleReached($role, $roleScope->getRole())) {
if ($scope === null) {
$centers[] = $groupCenter->getCenter();
break 1;
}
if ($scope->getId() == $roleScope->getScope()->getId()){
$centers[] = $groupCenter->getCenter();
break 1;
}
}
}
}
return $centers;
}
/**
* Filter an array of centers, return only center which are reachable
* Filter an array of centers, return only center which are reachable.
*
* @param User $user The user
* @param array $centers a list of centers which are going to be filtered
* @param string|Center $role
* @param Center|string $role
*/
public function filterReachableCenters(User $user, array $centers, $role): array
{
@@ -228,27 +81,75 @@ class AuthorizationHelper implements AuthorizationHelperInterface
}
/**
* Return all reachable scope for a given user, center and role
* @deprecated use UserACLAwareRepositoryInterface::findUsersByReachedACL instead
*
* @deprecated Use getReachableCircles
* @param array|Center|Center[] $center
* @param array|Scope|Scope[]|null $scope
*
* @param Center|Center[] $center
* @return Scope[]|array
* @return User[]
*/
public function getReachableScopes(UserInterface $user, string $role, $center): array
public function findUsersReaching(string $role, $center, $scope = null, bool $onlyEnabled = true): array
{
return $this->userACLAwareRepository
->findUsersByReachedACL($role, $center, $scope, $onlyEnabled);
}
/**
* Return all the role which give access to the given role. Only the role
* which are registered into Chill are taken into account.
*
* @return string[] the role which give access to the given $role
*/
public function getParentRoles(string $role): array
{
trigger_deprecation('Chill\MainBundle', '2.0', 'use ParentRoleHelper::getParentRoles instead');
return $this->parentRoleHelper->getParentRoles($role);
}
/**
* Get reachable Centers for the given user, role,
* and optionally Scope.
*
* @return array|Center[]
*/
public function getReachableCenters(UserInterface $user, string $role, ?Scope $scope = null): array
{
if ($role instanceof Role) {
$role = $role->getRole();
}
$centers = [];
return $this->getReachableCircles($user, $role, $center);
foreach ($user->getGroupCenters() as $groupCenter) {
$permissionGroup = $groupCenter->getPermissionsGroup();
//iterate on roleScopes
foreach ($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role is in the reachable roles
if ($this->isRoleReached($role, $roleScope->getRole())) {
if (null === $scope) {
$centers[] = $groupCenter->getCenter();
break;
}
if ($scope->getId() == $roleScope->getScope()->getId()) {
$centers[] = $groupCenter->getCenter();
break;
}
}
}
}
return $centers;
}
/**
* Return all reachable circle for a given user, center and role
* Return all reachable circle for a given user, center and role.
*
* @param string|Role $role
* @param Role|string $role
* @param Center|Center[] $center
*
* @return Scope[]
*/
public function getReachableCircles(UserInterface $user, $role, $center)
@@ -257,7 +158,7 @@ class AuthorizationHelper implements AuthorizationHelperInterface
if (is_iterable($center)) {
foreach ($center as $c) {
$scopes = \array_merge($scopes, $this->getReachableCircles($user, $role, $c));
$scopes = array_merge($scopes, $this->getReachableCircles($user, $role, $c));
}
return $scopes;
@@ -267,12 +168,12 @@ class AuthorizationHelper implements AuthorizationHelperInterface
$role = $role->getRole();
}
foreach ($user->getGroupCenters() as $groupCenter){
foreach ($user->getGroupCenters() as $groupCenter) {
if ($center->getId() === $groupCenter->getCenter()->getId()) {
//iterate on permissionGroup
$permissionGroup = $groupCenter->getPermissionsGroup();
//iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) {
foreach ($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role is in the reachable roles
if ($this->isRoleReached($role, $roleScope->getRole())) {
$scopes[] = $roleScope->getScope();
@@ -285,41 +186,160 @@ class AuthorizationHelper implements AuthorizationHelperInterface
}
/**
* Return all reachable scope for a given user, center and role.
*
* @deprecated use UserACLAwareRepositoryInterface::findUsersByReachedACL instead
* @param Center|Center[]|array $center
* @param Scope|Scope[]|array|null $scope
* @param bool $onlyActive true if get only active users
* @return User[]
* @deprecated Use getReachableCircles
*
* @param Center|Center[] $center
*
* @return array|Scope[]
*/
public function findUsersReaching(string $role, $center, $scope = null, bool $onlyEnabled = true): array
public function getReachableScopes(UserInterface $user, string $role, $center): array
{
return $this->userACLAwareRepository
->findUsersByReachedACL($role, $center, $scope, $onlyEnabled);
if ($role instanceof Role) {
$role = $role->getRole();
}
return $this->getReachableCircles($user, $role, $center);
}
/**
* Test if a parent role may give access to a given child role
* Determines if a user is active on this center.
*
* @param Center|Center[] $center May be an array of center
*/
public function userCanReachCenter(User $user, $center): bool
{
if ($center instanceof Traversable) {
foreach ($center as $c) {
if ($c->userCanReachCenter($user, $c)) {
return true;
}
}
return false;
}
if ($center instanceof Center) {
foreach ($user->getGroupCenters() as $groupCenter) {
if ($center->getId() === $groupCenter->getCenter()->getId()) {
return true;
}
}
return false;
}
throw new UnexpectedValueException(
sprintf(
'The entity given is not an instance of %s, %s given',
Center::class,
get_class($center)
)
);
}
/**
* Determines if the user has access to the given entity.
*
* if the entity implements Chill\MainBundle\Entity\HasScopeInterface,
* the scope is taken into account.
*
* @param mixed $entity the entity may also implement HasScopeInterface
* @param Role|string $attribute
*
* @return bool true if the user has access
*/
public function userHasAccess(User $user, $entity, $attribute)
{
$center = $this->centerResolverDispatcher->resolveCenter($entity);
if (is_iterable($center)) {
foreach ($center as $c) {
if ($this->userHasAccessForCenter($user, $c, $entity, $attribute)) {
return true;
}
}
return false;
}
if ($center instanceof Center) {
return $this->userHasAccessForCenter($user, $center, $entity, $attribute);
}
if (null === $center) {
return false;
}
throw new UnexpectedValueException('could not resolver a center');
}
/**
* Test if a parent role may give access to a given child role.
*
* @param string $childRole The role we want to test if he is reachable
* @param string $parentRole The role which should give access to $childRole
* @return boolean true if the child role is granted by parent role
*
* @return bool true if the child role is granted by parent role
*/
private function isRoleReached(string $childRole, string $parentRole)
{
return $this->parentRoleHelper->isRoleReached($childRole, $parentRole);
}
/**
* Return all the role which give access to the given role. Only the role
* which are registered into Chill are taken into account.
*
* @param string $role
* @return string[] the role which give access to the given $role
*/
public function getParentRoles(string $role): array
private function userHasAccessForCenter(User $user, Center $center, $entity, $attribute): bool
{
trigger_deprecation('Chill\MainBundle', '2.0', 'use ParentRoleHelper::getParentRoles instead');
return $this->parentRoleHelper->getParentRoles($role);
if (!$this->userCanReachCenter($user, $center)) {
$this->logger->debug('user cannot reach center of entity', [
'center_name' => $center->getName(),
'user' => $user->getUsername(),
]);
return false;
}
foreach ($user->getGroupCenters() as $groupCenter) {
//filter on center
if ($groupCenter->getCenter() === $center) {
$permissionGroup = $groupCenter->getPermissionsGroup();
//iterate on roleScopes
foreach ($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role allow to reach the required role
if ($this->isRoleReached($attribute, $roleScope->getRole())) {
//if yes, we have a right on something...
// perform check on scope if necessary
if ($this->scopeResolverDispatcher->isConcerned($entity)) {
$scope = $this->scopeResolverDispatcher->resolveScope($entity);
if (null === $scope) {
return true;
}
if (is_iterable($scope)) {
foreach ($scope as $s) {
if ($roleScope->getScope() === $s) {
return true;
}
}
} else {
if ($roleScope->getScope() === $scope) {
return true;
}
}
} else {
return true;
}
}
}
}
}
$this->logger->debug('user can reach center entity, but not role', [
'username' => $user->getUsername(),
'center' => $center->getName(),
]);
return false;
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Authorization;
use Chill\MainBundle\Entity\Center;
@@ -10,17 +17,14 @@ interface AuthorizationHelperInterface
{
/**
* Get reachable Centers for the given user, role,
* and optionnaly Scope
* and optionnaly Scope.
*
* @param null|Scope $scope
* @return Center[]
*/
public function getReachableCenters(UserInterface $user, string $role, ?Scope $scope = null): array;
/**
* @param Center|Center[]|array $center
* @return array
* @param array|Center|Center[] $center
*/
public function getReachableScopes(UserInterface $user, string $role, $center): array;
}

View File

@@ -1,12 +1,19 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Authorization;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class ChillExportVoter extends Voter
{
@@ -21,7 +28,7 @@ class ChillExportVoter extends Voter
protected function supports($attribute, $subject): bool
{
return $attribute === self::EXPORT;
return self::EXPORT === $attribute;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool

View File

@@ -1,30 +1,17 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Authorization;
/**
* Provides methods for compiling voter and build admin role fields.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ChillVoterInterface
{
}

View File

@@ -1,24 +1,28 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Authorization;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcher;
use Chill\MainBundle\Security\Resolver\CenterResolverDispatcherInterface;
use function in_array;
final class DefaultVoterHelper implements VoterHelperInterface
{
protected AuthorizationHelper $authorizationHelper;
private AuthorizationHelper $authorizationHelper;
protected CenterResolverDispatcherInterface $centerResolverDispatcher;
private CenterResolverDispatcherInterface $centerResolverDispatcher;
protected array $configuration = [];
private array $configuration = [];
/**
* @param array $configuration
*/
public function __construct(
AuthorizationHelper $authorizationHelper,
CenterResolverDispatcherInterface $centerResolverDispatcher,
@@ -31,13 +35,13 @@ final class DefaultVoterHelper implements VoterHelperInterface
public function supports($attribute, $subject): bool
{
foreach ($this->configuration as list($attributes, $subj)) {
if ($subj === null) {
if ($subject === null && \in_array($attribute, $attributes, true)) {
foreach ($this->configuration as [$attributes, $subj]) {
if (null === $subj) {
if (null === $subject && in_array($attribute, $attributes, true)) {
return true;
}
} elseif ($subject instanceof $subj) {
return \in_array($attribute, $attributes, true);
return in_array($attribute, $attributes, true);
}
}
@@ -50,7 +54,7 @@ final class DefaultVoterHelper implements VoterHelperInterface
return false;
}
if (NULL === $subject) {
if (null === $subject) {
return [] !== $this->authorizationHelper->getReachableCenters($token->getUser(), $attribute, null);
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Authorization;
@@ -9,6 +16,7 @@ use Chill\MainBundle\Security\Resolver\CenterResolverDispatcherInterface;
class DefaultVoterHelperFactory implements VoterHelperFactoryInterface
{
protected AuthorizationHelper $authorizationHelper;
protected CenterResolverDispatcherInterface $centerResolverDispatcher;
public function __construct(

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Authorization;
@@ -8,9 +15,11 @@ use Chill\MainBundle\Security\Resolver\CenterResolverDispatcherInterface;
final class DefaultVoterHelperGenerator implements VoterGeneratorInterface
{
protected AuthorizationHelper $authorizationHelper;
protected CenterResolverDispatcherInterface $centerResolverDispatcher;
protected array $configuration = [];
private AuthorizationHelper $authorizationHelper;
private CenterResolverDispatcherInterface $centerResolverDispatcher;
private array $configuration = [];
public function __construct(
AuthorizationHelper $authorizationHelper,
@@ -22,9 +31,9 @@ final class DefaultVoterHelperGenerator implements VoterGeneratorInterface
public function addCheckFor(?string $subject, array $attributes): self
{
$this->configuration[] = [$attributes, $subject];
$this->configuration[] = [$attributes, $subject];
return $this;
return $this;
}
public function build(): VoterHelperInterface

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Authorization;
interface VoterGeneratorInterface
@@ -7,6 +14,7 @@ interface VoterGeneratorInterface
/**
* @param string $class The FQDN of a class
* @param array $attributes an array of attributes
*
* @return $this
*/
public function addCheckFor(?string $class, array $attributes): self;

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Authorization;
interface VoterHelperFactoryInterface

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Authorization;

View File

@@ -1,18 +1,24 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use function array_keys;
/**
* Helper which traverse all role to find parents
* Helper which traverse all role to find parents.
*/
class ParentRoleHelper
{
protected RoleHierarchyInterface $roleHierarchy;
/**
* The role in a hierarchy, given by the parameter
* `security.role_hierarchy.roles` from the container.
@@ -21,12 +27,14 @@ class ParentRoleHelper
*/
protected array $hierarchy;
protected RoleHierarchyInterface $roleHierarchy;
public function __construct(
RoleHierarchyInterface $roleHierarchy,
ParameterBagInterface $parameterBag
) {
$this->roleHierarchy = $roleHierarchy;
$this->hierarchy = $parameterBag->get('security.role_hierarchy.roles');
$this->hierarchy = $parameterBag->get('security.role_hierarchy.roles');
}
/**
@@ -35,14 +43,13 @@ class ParentRoleHelper
*
* The array contains always the current $role (which give access to himself)
*
* @param string $role
* @return string[] the role which give access to the given $role
*/
public function getParentRoles(string $role): array
{
$parentRoles = [$role];
// transform the roles from role hierarchy from string to Role
$roles = \array_keys($this->hierarchy);
$roles = array_keys($this->hierarchy);
foreach ($roles as $r) {
$childRoles = $this->roleHierarchy->getReachableRoleNames([$r]);
@@ -56,10 +63,11 @@ class ParentRoleHelper
}
/**
* Test if a parent role may give access to a given child role
* Test if a parent role may give access to a given child role.
*
* @param string $childRole The role we want to test if he is reachable
* @param string $parentRole The role which should give access to $childRole
*
* @return bool true if the child role is granted by parent role
*/
public function isRoleReached($childRole, $parentRole): bool
@@ -69,5 +77,4 @@ class ParentRoleHelper
return in_array($childRole, $reachableRoles);
}
}

View File

@@ -1,77 +1,73 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Entity\User;
use Symfony\Component\EventDispatcher\Event;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverEvent extends Event
{
public const ASK_TOKEN_INVALID_FORM = 'chill_main.ask_token_invalid_form';
public const ASK_TOKEN_SUCCESS = 'chill_main.ask_token_success';
public const INVALID_TOKEN = 'chill_main.password_recover_invalid_token';
/**
*
* @var User
*/
protected $user;
/**
*
* @var string
*/
protected $token;
/**
*
* @var string
*/
protected $ip;
/**
*
* @var boolean
* @var bool
*/
protected $safelyGenerated;
const ASK_TOKEN_INVALID_FORM = 'chill_main.ask_token_invalid_form';
const INVALID_TOKEN = 'chill_main.password_recover_invalid_token';
const ASK_TOKEN_SUCCESS = 'chill_main.ask_token_success';
/**
* @var string
*/
protected $token;
/**
* @var User
*/
protected $user;
/**
*
* @param type $token
* @param User $user
* @param type $ip
* @param bool $safelyGenerated true if generated safely (from console command, etc.)
*/
public function __construct($token = null, User $user = null, $ip = null, bool $safelyGenerated = false)
public function __construct($token = null, ?User $user = null, $ip = null, bool $safelyGenerated = false)
{
$this->user = $user;
$this->token = $token;
$this->ip = $ip;
$this->safelyGenerated = $safelyGenerated;
}
public function getIp()
{
return $this->ip;
}
/**
* @return string
*/
public function getToken()
{
return $this->token;
}
/**
*
* @return User|null
*/
public function getUser()
@@ -79,38 +75,16 @@ class PasswordRecoverEvent extends Event
return $this->user;
}
/**
*
* @return string
*/
public function getToken()
{
return $this->token;
}
public function getIp()
{
return $this->ip;
}
/**
*
* @return boolean
*/
public function hasIp(): bool
{
return !empty($this->ip);
}
/**
*
* @return boolean
*/
public function hasUser(): bool
{
return $this->user instanceof User;
}
public function isSafelyGenerated(): bool
{
return $this->safelyGenerated;

View File

@@ -1,83 +1,67 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverEventSubscriber implements EventSubscriberInterface
{
/**
*
* @var PasswordRecoverLocker
*/
protected $locker;
public function __construct(PasswordRecoverLocker $locker)
{
$this->locker = $locker;
}
public static function getSubscribedEvents(): array
{
return [
PasswordRecoverEvent::INVALID_TOKEN => [
[ 'onInvalidToken' ]
['onInvalidToken'],
],
PasswordRecoverEvent::ASK_TOKEN_INVALID_FORM => [
[ 'onAskTokenInvalidForm' ]
['onAskTokenInvalidForm'],
],
PasswordRecoverEvent::ASK_TOKEN_SUCCESS => [
[ 'onAskTokenSuccess']
]
['onAskTokenSuccess'],
],
];
}
public function onInvalidToken(PasswordRecoverEvent $event)
{
// set global lock
$this->locker->createLock('invalid_token_global', null);
// set ip lock
if ($event->hasIp()) {
$this->locker->createLock('invalid_token_by_ip', $event->getIp());
}
}
public function onAskTokenInvalidForm(PasswordRecoverEvent $event)
{
// set global lock
$this->locker->createLock('ask_token_invalid_form_global', null);
// set ip lock
if ($event->hasIp()) {
$this->locker->createLock('ask_token_invalid_form_by_ip', $event->getIp());
}
}
public function onAskTokenSuccess(PasswordRecoverEvent $event)
{
$this->locker->createLock('ask_token_success_by_user', $event->getUser());
}
public function onInvalidToken(PasswordRecoverEvent $event)
{
// set global lock
$this->locker->createLock('invalid_token_global', null);
// set ip lock
if ($event->hasIp()) {
$this->locker->createLock('invalid_token_by_ip', $event->getIp());
}
}
}

View File

@@ -1,170 +1,163 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Redis\ChillRedis;
use LogicException;
use Psr\Log\LoggerInterface;
use UnexpectedValueException;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverLocker
{
public const ASK_TOKEN_INVALID_FORM_TTL = 3600;
/**
* The maximum of invalid token globally (across all ip)
* TTL to keep invalid token recorded.
*/
const MAX_INVALID_TOKEN_GLOBAL = 50;
public const INVALID_TOKEN_TTL = 3600;
public const MAX_ASK_TOKEN_BY_USER = 10;
public const MAX_ASK_TOKEN_INVALID_FORM_BY_IP = 10;
public const MAX_ASK_TOKEN_INVALID_FORM_GLOBAL = 50;
/**
* The maximum of invalid token by ip
* The maximum of invalid token by ip.
*/
const MAX_INVALID_TOKEN_BY_IP = 10;
public const MAX_INVALID_TOKEN_BY_IP = 10;
/**
* TTL to keep invalid token recorded
* The maximum of invalid token globally (across all ip).
*/
const INVALID_TOKEN_TTL = 3600;
const MAX_ASK_TOKEN_INVALID_FORM_GLOBAL = 50;
const MAX_ASK_TOKEN_INVALID_FORM_BY_IP = 10;
const MAX_ASK_TOKEN_BY_USER = 10;
const ASK_TOKEN_INVALID_FORM_TTL = 3600;
public const MAX_INVALID_TOKEN_GLOBAL = 50;
/**
*
* @var ChillRedis
*/
protected $chillRedis;
/**
*
* @var LoggerInterface
*/
protected $logger;
public function __construct(ChillRedis $chillRedis, LoggerInterface $logger)
{
$this->chillRedis = $chillRedis;
$this->logger = $logger;
}
public function createLock($usage, $discriminator = null)
{
$max = $this->getMax($usage);
$ttl = $this->getTtl($usage);
for ($i = 0; $i < $max; $i++) {
for ($i = 0; $i < $max; ++$i) {
$key = self::generateLockKey($usage, $i, $discriminator);
if (0 === $this->chillRedis->exists($key)) {
$this->chillRedis->set($key, 1);
$this->chillRedis->setTimeout($key, $ttl);
break;
}
}
}
public function isLocked($usage, $discriminator = null)
{
$max = $this->getMax($usage);
for ($i = 0; $i < $max; $i++) {
$key = self::generateLockKey($usage, $i, $discriminator);
if ($this->chillRedis->exists($key) === 0) {
return false;
}
/**
* @param string $usage 'invalid_token_global' or ...
* @param mixed|null $discriminator
*/
public static function generateLockKey($usage, int $number, $discriminator = null)
{
switch ($usage) {
case 'invalid_token_global':
return sprintf('invalid_token_global_%d', $number);
case 'invalid_token_by_ip':
return sprintf('invalid_token_ip_%s_%d', $discriminator, $number);
case 'ask_token_invalid_form_global':
return sprintf('ask_token_invalid_form_global_%d', $number);
case 'ask_token_invalid_form_by_ip':
return sprintf('ask_token_invalid_form_by_ip_%s_%d', $discriminator, $number);
case 'ask_token_success_by_user':
return sprintf('ask_token_success_by_user_%s_%d', $discriminator->getId(), $number);
default:
throw new LogicException('this usage is not implemented');
}
$this->logger->warning("locking reaching for password recovery", [
'usage' => $usage,
'discriminator' => $discriminator
]);
return true;
}
public function getMax($usage)
{
switch ($usage) {
case 'invalid_token_global':
return self::MAX_INVALID_TOKEN_GLOBAL;
case 'invalid_token_by_ip':
return self::MAX_INVALID_TOKEN_BY_IP;
case 'ask_token_invalid_form_global':
return self::MAX_ASK_TOKEN_INVALID_FORM_GLOBAL;
case 'ask_token_invalid_form_by_ip':
return self::MAX_ASK_TOKEN_INVALID_FORM_BY_IP;
case 'ask_token_success_by_user':
return self::MAX_ASK_TOKEN_BY_USER;
default:
throw new \UnexpectedValueException("this usage '$usage' is not yet implemented");
throw new UnexpectedValueException("this usage '{$usage}' is not yet implemented");
}
}
public function getTtl($usage)
{
switch ($usage) {
case 'invalid_token_global':
case 'invalid_token_by_ip':
return self::INVALID_TOKEN_TTL;
case 'ask_token_invalid_form_global':
case 'ask_token_invalid_form_by_ip':
return self::ASK_TOKEN_INVALID_FORM_TTL;
case 'ask_token_success_by_user':
return self::ASK_TOKEN_INVALID_FORM_TTL * 24;
default:
throw new \UnexpectedValueException("this usage '$usage' is not yet implemented");
throw new UnexpectedValueException("this usage '{$usage}' is not yet implemented");
}
}
/**
*
* @param string $usage 'invalid_token_global' or ...
* @param int $number
*/
public static function generateLockKey($usage, int $number, $discriminator = null)
public function isLocked($usage, $discriminator = null)
{
switch($usage) {
case "invalid_token_global":
return sprintf('invalid_token_global_%d', $number);
case "invalid_token_by_ip":
return sprintf('invalid_token_ip_%s_%d', $discriminator, $number);
case "ask_token_invalid_form_global":
return sprintf('ask_token_invalid_form_global_%d', $number);
case "ask_token_invalid_form_by_ip":
return sprintf('ask_token_invalid_form_by_ip_%s_%d', $discriminator, $number);
case 'ask_token_success_by_user':
return sprintf('ask_token_success_by_user_%s_%d', $discriminator->getId(), $number);
default:
throw new \LogicException("this usage is not implemented");
$max = $this->getMax($usage);
for ($i = 0; $i < $max; ++$i) {
$key = self::generateLockKey($usage, $i, $discriminator);
if ($this->chillRedis->exists($key) === 0) {
return false;
}
}
$this->logger->warning('locking reaching for password recovery', [
'usage' => $usage,
'discriminator' => $discriminator,
]);
return true;
}
}

View File

@@ -1,67 +1,52 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
*
* Chill is a software for social workers
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Entity\User;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
class PasswordRecoverVoter extends Voter
{
const TRY_TOKEN = 'CHILL_PASSWORD_TRY_TOKEN';
const ASK_TOKEN = 'CHILL_PASSWORD_ASK_TOKEN';
protected $supported = [
self::TRY_TOKEN,
self::ASK_TOKEN
];
public const ASK_TOKEN = 'CHILL_PASSWORD_ASK_TOKEN';
public const TRY_TOKEN = 'CHILL_PASSWORD_TRY_TOKEN';
/**
*
* @var PasswordRecoverLocker
*/
protected $locker;
/**
*
* @var RequestStack
*/
protected $requestStack;
protected $supported = [
self::TRY_TOKEN,
self::ASK_TOKEN,
];
public function __construct(PasswordRecoverLocker $locker, RequestStack $requestStack)
{
$this->locker = $locker;
$this->requestStack = $requestStack;
}
protected function supports($attribute, $subject): bool
{
if (!in_array($attribute, $this->supported)) {
return false;
}
return true;
}
@@ -69,34 +54,36 @@ class PasswordRecoverVoter extends Voter
{
switch ($attribute) {
case self::TRY_TOKEN:
if (TRUE === $this->locker->isLocked('invalid_token_global')) {
if (true === $this->locker->isLocked('invalid_token_global')) {
return false;
}
$ip = $this->requestStack->getCurrentRequest()->getClientIp();
if (TRUE === $this->locker->isLocked('invalid_token_by_ip', $ip)) {
if (true === $this->locker->isLocked('invalid_token_by_ip', $ip)) {
return false;
}
return true;
case self::ASK_TOKEN:
if (TRUE === $this->locker->isLocked('ask_token_invalid_form_global')) {
if (true === $this->locker->isLocked('ask_token_invalid_form_global')) {
return false;
}
$ip = $this->requestStack->getCurrentRequest()->getClientIp();
if (TRUE === $this->locker->isLocked('ask_token_invalid_form_by_ip', $ip)) {
if (true === $this->locker->isLocked('ask_token_invalid_form_by_ip', $ip)) {
return false;
}
if ($subject instanceof User) {
if (TRUE === $this->locker->isLocked('ask_token_success_by_user', $subject)) {
if (true === $this->locker->isLocked('ask_token_success_by_user', $subject)) {
return false;
}
}
return true;
}
return false;

View File

@@ -1,59 +1,44 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Security\PasswordRecover\TokenManager;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Chill\MainBundle\Notification\Mailer;
use Chill\MainBundle\Entity\User;
/**
*
* Chill is a software for social workers
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Notification\Mailer;
use DateTimeInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use function array_merge;
class RecoverPasswordHelper
{
public const RECOVER_PASSWORD_ROUTE = 'password_recover';
/**
*
* @var TokenManager
*/
protected $tokenManager;
/**
*
* @var UrlGeneratorInterface
*/
protected $urlGenerator;
/**
*
* @var Mailer
*/
protected $mailer;
protected $routeParameters;
const RECOVER_PASSWORD_ROUTE = 'password_recover';
/**
* @var TokenManager
*/
protected $tokenManager;
/**
* @var UrlGeneratorInterface
*/
protected $urlGenerator;
public function __construct(
TokenManager $tokenManager,
UrlGeneratorInterface $urlGenerator,
TokenManager $tokenManager,
UrlGeneratorInterface $urlGenerator,
Mailer $mailer,
array $routeParameters
) {
@@ -64,64 +49,65 @@ class RecoverPasswordHelper
}
/**
*
* @param User $user
* @param \DateTimeInterface $expiration
* @param bool $absolute
* @param array $parameters additional parameters to url
*
* @return string
*/
public function generateUrl(User $user, \DateTimeInterface $expiration, $absolute = true, array $parameters = [])
public function generateUrl(User $user, DateTimeInterface $expiration, $absolute = true, array $parameters = [])
{
$context = $this->urlGenerator->getContext();
$previousHost = $context->getHost();
$previousScheme = $context->getScheme();
$context->setHost($this->routeParameters['host']);
$context->setScheme($this->routeParameters['scheme']);
$url = $this->urlGenerator->generate(
self::RECOVER_PASSWORD_ROUTE,
\array_merge(
self::RECOVER_PASSWORD_ROUTE,
array_merge(
$this->tokenManager->generate($user, $expiration),
$parameters),
$parameters
),
$absolute ? UrlGeneratorInterface::ABSOLUTE_URL : UrlGeneratorInterface::ABSOLUTE_PATH
);
);
// reset the host
$context->setHost($previousHost);
$context->setScheme($previousScheme);
return $url;
}
public function sendRecoverEmail(
User $user,
\DateTimeInterface $expiration,
$template = '@ChillMain/Password/recover_email.txt.twig',
array $templateParameters = [],
User $user,
DateTimeInterface $expiration,
$template = '@ChillMain/Password/recover_email.txt.twig',
array $templateParameters = [],
$force = false,
array $additionalUrlParameters = [],
$emailSubject = 'Recover your password'
) {
$content = $this->mailer->renderContentToUser(
$user,
$template,
\array_merge([
$user,
$template,
array_merge(
[
'user' => $user,
'url' => $this->generateUrl($user, $expiration, true, $additionalUrlParameters)
'url' => $this->generateUrl($user, $expiration, true, $additionalUrlParameters),
],
$templateParameters
));
)
);
$this->mailer->sendNotification(
$user,
[ $emailSubject ],
$user,
[$emailSubject],
[
'text/plain' => $content,
],
null,
$force);
],
null,
$force
);
}
}

View File

@@ -1,103 +1,99 @@
<?php
/*
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Entity\User;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Psr\Log\LoggerInterface;
use UnexpectedValueException;
use function bin2hex;
use function hash;
use function hex2bin;
use function random_bytes;
use function strlen;
use function trim;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class TokenManager
{
public const HASH = 'h';
public const TIMESTAMP = 'ts';
public const TOKEN = 't';
public const TOKEN_LENGTH = 24;
public const USERNAME_CANONICAL = 'u';
/**
*
* @var string
*/
protected $secret;
/**
*
* @var LoggerInterface
*/
protected $logger;
const TOKEN = 't';
const HASH = 'h';
const TIMESTAMP = 'ts';
const USERNAME_CANONICAL = 'u';
const TOKEN_LENGTH = 24;
/**
* @var string
*/
protected $secret;
public function __construct($secret, LoggerInterface $logger)
{
$this->secret = $secret;
$this->logger = $logger;
}
public function generate(User $user, \DateTimeInterface $expiration)
public function generate(User $user, DateTimeInterface $expiration)
{
$token = \random_bytes(self::TOKEN_LENGTH);
$token = random_bytes(self::TOKEN_LENGTH);
$username = $user->getUsernameCanonical();
if (empty($username)) {
throw new \UnexpectedValueException("username should not be empty to generate a token");
throw new UnexpectedValueException('username should not be empty to generate a token');
}
$timestamp = $expiration->getTimestamp();
$hash = \hash('sha1', $token.$username.$timestamp.$this->secret);
return [
self::HASH => $hash,
self::TOKEN => \bin2hex($token),
self::TIMESTAMP => $timestamp,
self::USERNAME_CANONICAL => $username
];
$hash = hash('sha1', $token . $username . $timestamp . $this->secret);
return [
self::HASH => $hash,
self::TOKEN => bin2hex($token),
self::TIMESTAMP => $timestamp,
self::USERNAME_CANONICAL => $username,
];
}
public function verify($hash, $token, User $user, $timestamp)
{
$token = \hex2bin(\trim($token));
if (\strlen($token) !== self::TOKEN_LENGTH) {
$token = hex2bin(trim($token));
if (strlen($token) !== self::TOKEN_LENGTH) {
return false;
}
$username = $user->getUsernameCanonical();
$date = \DateTimeImmutable::createFromFormat('U', $timestamp);
if ($date < new \DateTime('now')) {
$date = DateTimeImmutable::createFromFormat('U', $timestamp);
if ($date < new DateTime('now')) {
$this->logger->info('receiving a password recover token with expired '
. 'validity');
return false;
}
$expected = \hash('sha1', $token.$username.$timestamp.$this->secret);
$expected = hash('sha1', $token . $username . $timestamp . $this->secret);
if ($expected !== $hash) {
return false;
}
return true;
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security;

View File

@@ -1,11 +1,18 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security;
/**
* Declare role
* Declare role.
*
* The role are added to the configuration at compile time.
*

View File

@@ -1,10 +1,16 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Resolver;
final class CenterResolverDispatcher implements CenterResolverDispatcherInterface
{
/**
@@ -29,7 +35,7 @@ final class CenterResolverDispatcher implements CenterResolverDispatcherInterfac
'
);
foreach($this->resolvers as $resolver) {
foreach ($this->resolvers as $resolver) {
if ($resolver->supports($entity, $options)) {
return $resolver->resolveCenter($entity, $options);
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Resolver;
@@ -13,7 +20,8 @@ interface CenterResolverDispatcherInterface
{
/**
* @param object $entity
* @return null|Center|Center[]
*
* @return Center|Center[]|null
*/
public function resolveCenter($entity, ?array $options = []);
}

View File

@@ -1,21 +1,29 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Resolver;
use Chill\MainBundle\Entity\Center;
interface CenterResolverInterface
{
/**
* @param object $entity
*/
public function supports($entity, ?array $options = []): bool;
public static function getDefaultPriority(): int;
/**
* @param object $entity
*
* @return Center|Center[]
*/
public function resolveCenter($entity, ?array $options = []);
public static function getDefaultPriority(): int;
/**
* @param object $entity
*/
public function supports($entity, ?array $options = []): bool;
}

View File

@@ -1,10 +1,19 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Resolver;
use Chill\MainBundle\Entity\Center;
use UnexpectedValueException;
use function is_array;
final class CenterResolverManager implements CenterResolverManagerInterface
{
@@ -20,19 +29,28 @@ final class CenterResolverManager implements CenterResolverManagerInterface
public function resolveCenters($entity, ?array $options = []): array
{
foreach($this->resolvers as $resolver) {
foreach ($this->resolvers as $resolver) {
if ($resolver->supports($entity, $options)) {
$resolved = $resolver->resolveCenter($entity, $options);
if (null === $resolved) {
return [];
} elseif ($resolved instanceof Center) {
}
if ($resolved instanceof Center) {
return [$resolved];
} elseif (\is_array($resolved)) {
}
if (is_array($resolved)) {
return $resolved;
}
throw new \UnexpectedValueException(sprintf("the return type of a %s should be an instance of %s, an array or null. Resolver is %s",
CenterResolverInterface::class, Center::class, get_class($resolver)));
throw new UnexpectedValueException(sprintf(
'the return type of a %s should be an instance of %s, an array or null. Resolver is %s',
CenterResolverInterface::class,
Center::class,
get_class($resolver)
));
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\Resolver;
@@ -10,6 +17,7 @@ interface CenterResolverManagerInterface
{
/**
* @param object $entity
*
* @return Center[]
*/
public function resolveCenters($entity, ?array $options = []): array;

View File

@@ -1,21 +1,26 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Resolver;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\HasCenterInterface;
use Chill\MainBundle\Entity\HasCentersInterface;
use UnexpectedValueException;
class DefaultCenterResolver implements CenterResolverInterface
{
public function supports($entity, ?array $options = []): bool
public static function getDefaultPriority(): int
{
return $entity instanceof HasCenterInterface || $entity instanceof HasCentersInterface;
return -256;
}
/**
* @inheritDoc
*
* @param HasCenterInterface $entity
* @param array $options
*/
@@ -23,15 +28,17 @@ class DefaultCenterResolver implements CenterResolverInterface
{
if ($entity instanceof HasCenterInterface) {
return $entity->getCenter();
} elseif ($entity instanceof HasCentersInterface) {
return $entity->getCenters();
} else {
throw new \UnexpectedValueException("should be an instanceof");
}
if ($entity instanceof HasCentersInterface) {
return $entity->getCenters();
}
throw new UnexpectedValueException('should be an instanceof');
}
public static function getDefaultPriority(): int
public function supports($entity, ?array $options = []): bool
{
return -256;
return $entity instanceof HasCenterInterface || $entity instanceof HasCentersInterface;
}
}

View File

@@ -1,33 +1,23 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Resolver;
use Chill\MainBundle\Entity\HasScopeInterface;
use Chill\MainBundle\Entity\HasScopesInterface;
use UnexpectedValueException;
class DefaultScopeResolver implements ScopeResolverInterface
{
public function supports($entity, ?array $options = []): bool
public static function getDefaultPriority(): int
{
return $entity instanceof HasScopeInterface || $entity instanceof HasScopesInterface;
}
/**
* @inheritDoc
*
* @param HasScopeInterface|HasScopesInterface $entity
*/
public function resolveScope($entity, ?array $options = [])
{
if ($entity instanceof HasScopeInterface) {
return $entity->getScope();
} elseif ($entity instanceof HasScopesInterface) {
return $entity->getScopes();
} else {
throw new \UnexpectedValueException("should be an instanceof %s or %s",
HasScopesInterface::class, HasScopeInterface::class);
}
return -256;
}
public function isConcerned($entity, ?array $options = []): bool
@@ -35,8 +25,28 @@ class DefaultScopeResolver implements ScopeResolverInterface
return $entity instanceof HasScopeInterface || $entity instanceof HasScopesInterface;
}
public static function getDefaultPriority(): int
/**
* @param HasScopeInterface|HasScopesInterface $entity
*/
public function resolveScope($entity, ?array $options = [])
{
return -256;
if ($entity instanceof HasScopeInterface) {
return $entity->getScope();
}
if ($entity instanceof HasScopesInterface) {
return $entity->getScopes();
}
throw new UnexpectedValueException(
'should be an instanceof %s or %s',
HasScopesInterface::class,
HasScopeInterface::class
);
}
public function supports($entity, ?array $options = []): bool
{
return $entity instanceof HasScopeInterface || $entity instanceof HasScopesInterface;
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Resolver;
use Twig\TwigFilter;
@@ -7,6 +14,7 @@ use Twig\TwigFilter;
final class ResolverTwigExtension extends \Twig\Extension\AbstractExtension
{
private CenterResolverManagerInterface $centerResolverDispatcher;
private ScopeResolverDispatcher $scopeResolverDispatcher;
public function __construct(CenterResolverManagerInterface $centerResolverDispatcher, ScopeResolverDispatcher $scopeResolverDispatcher)
@@ -24,9 +32,19 @@ final class ResolverTwigExtension extends \Twig\Extension\AbstractExtension
];
}
/**
* @param $entity
*
* @return bool
*/
public function isScopeConcerned($entity, ?array $options = [])
{
return $this->scopeResolverDispatcher->isConcerned($entity, $options);
}
/**
* @param mixed $entity
* @param array|null $options
*
* @return Center|Center[]|null
*/
public function resolveCenter($entity, ?array $options = [])
@@ -36,17 +54,7 @@ final class ResolverTwigExtension extends \Twig\Extension\AbstractExtension
/**
* @param $entity
* @param array|null $options
* @return bool
*/
public function isScopeConcerned($entity, ?array $options = [])
{
return $this->scopeResolverDispatcher->isConcerned($entity, $options);
}
/**
* @param $entity
* @param array|null $options
*
* @return array|\Chill\MainBundle\Entity\Scope|\Chill\MainBundle\Entity\Scope[]
*/
public function resolveScope($entity, ?array $options = [])

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Resolver;
use Chill\MainBundle\Entity\Scope;
@@ -16,9 +23,21 @@ final class ScopeResolverDispatcher
$this->resolvers = $resolvers;
}
public function isConcerned($entity, ?array $options = []): bool
{
foreach ($this->resolvers as $resolver) {
if ($resolver->supports($entity, $options)) {
return $resolver->isConcerned($entity, $options);
}
}
return false;
}
/**
* @param $entity
* @return Scope|Scope[]|iterable
*
* @return iterable|Scope|Scope[]
*/
public function resolveScope($entity, ?array $options = [])
{
@@ -30,15 +49,4 @@ final class ScopeResolverDispatcher
return null;
}
public function isConcerned($entity, ?array $options = []): bool
{
foreach ($this->resolvers as $resolver) {
if ($resolver->supports($entity, $options)) {
return $resolver->isConcerned($entity, $options);
}
}
return false;
}
}

View File

@@ -1,5 +1,12 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\Resolver;
use Chill\MainBundle\Entity\Scope;
@@ -9,27 +16,32 @@ use Chill\MainBundle\Entity\Scope;
*/
interface ScopeResolverInterface
{
/**
* Return true if this resolve is able to decide "something" on this entity.
*/
public function supports($entity, ?array $options = []): bool;
/**
* Will return the scope for the entity
*
* @return Scope|array|Scope[]
*/
public function resolveScope($entity, ?array $options = []);
/**
* Return true if the entity is concerned by scope, false otherwise.
*/
public function isConcerned($entity, ?array $options = []): bool;
/**
* get the default priority for this resolver. Resolver with an higher priority will be
* queried first.
*/
public static function getDefaultPriority(): int;
/**
* Return true if the entity is concerned by scope, false otherwise.
*
* @param mixed $entity
*/
public function isConcerned($entity, ?array $options = []): bool;
/**
* Will return the scope for the entity.
*
* @param mixed $entity
*
* @return array|Scope|Scope[]
*/
public function resolveScope($entity, ?array $options = []);
/**
* Return true if this resolve is able to decide "something" on this entity.
*
* @param mixed $entity
*/
public function supports($entity, ?array $options = []): bool;
}

View File

@@ -1,36 +1,23 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@champs-libres.coop>
/**
* Chill is a software for social workers
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
use function array_fill_keys;
use function array_key_exists;
class RoleProvider
{
/**
*
* @var ProvideRoleInterface[]
*/
private $providers = array();
private $providers = [];
/**
* an array where keys are the role, and value is the title
@@ -40,12 +27,13 @@ class RoleProvider
*
* @var array|null
*/
private $rolesTitlesCache = null;
private $rolesTitlesCache;
/**
* Add a role provider
* Add a role provider.
*
* @internal This function is called by the dependency injector: it inject provider
*
* @param \Chill\MainBundle\Security\ProvideRoleInterface $provider
*/
public function addProvider(ProvideRoleInterface $provider)
@@ -58,7 +46,7 @@ class RoleProvider
$roles = [];
foreach ($this->providers as $provider) {
if ($provider->getRoles() !== NULL) {
if ($provider->getRoles() !== null) {
$roles = array_merge($roles, $provider->getRoles());
}
}
@@ -71,7 +59,7 @@ class RoleProvider
$roles = [];
foreach ($this->providers as $provider) {
if ($provider->getRolesWithoutScope() !== NULL) {
if ($provider->getRolesWithoutScope() !== null) {
$roles = array_merge($roles, $provider->getRolesWithoutScope());
}
}
@@ -79,46 +67,18 @@ class RoleProvider
return $roles;
}
/**
* initialize the array for caching role and titles
*
*/
private function initializeRolesTitlesCache()
{
// break if already initialized
if ($this->rolesTitlesCache !== null) {
return;
}
foreach ($this->providers as $provider) {
if ($provider instanceof ProvideRoleHierarchyInterface) {
foreach ($provider->getRolesWithHierarchy() as $title => $roles) {
foreach($roles as $role) {
$this->rolesTitlesCache[$role] = $title;
}
}
} else {
if ($provider->getRoles() !== null) {
$this->rolesTitlesCache = \array_merge(
$this->rolesTitlesCache,
\array_fill_keys($provider->getRoles(), null)
);
}
}
}
}
/**
* Get the title for each role.
*
* @param string $role
*
* @return string the title of the role
*/
public function getRoleTitle($role)
{
$this->initializeRolesTitlesCache();
if (! \array_key_exists($role, $this->rolesTitlesCache)) {
if (!array_key_exists($role, $this->rolesTitlesCache)) {
// this case might happens when the role is not described in
// `getRolesWithHierarchy`
return null;
@@ -127,4 +87,31 @@ class RoleProvider
return $this->rolesTitlesCache[$role];
}
/**
* initialize the array for caching role and titles.
*/
private function initializeRolesTitlesCache()
{
// break if already initialized
if (null !== $this->rolesTitlesCache) {
return;
}
foreach ($this->providers as $provider) {
if ($provider instanceof ProvideRoleHierarchyInterface) {
foreach ($provider->getRolesWithHierarchy() as $title => $roles) {
foreach ($roles as $role) {
$this->rolesTitlesCache[$role] = $title;
}
}
} else {
if ($provider->getRoles() !== null) {
$this->rolesTitlesCache = \array_merge(
$this->rolesTitlesCache,
array_fill_keys($provider->getRoles(), null)
);
}
}
}
}
}

View File

@@ -1,16 +1,23 @@
<?php
/**
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Security\UserProvider;
use Doctrine\ORM\NoResultException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\EntityManagerInterface;
use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NoResultException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
class UserProvider implements UserProviderInterface
{
@@ -25,11 +32,12 @@ class UserProvider implements UserProviderInterface
{
try {
$user = $this->em->createQuery(sprintf(
"SELECT u FROM %s u "
. "WHERE u.usernameCanonical = UNACCENT(LOWER(:pattern)) "
. "OR "
. "u.emailCanonical = UNACCENT(LOWER(:pattern))",
User::class))
'SELECT u FROM %s u '
. 'WHERE u.usernameCanonical = UNACCENT(LOWER(:pattern)) '
. 'OR '
. 'u.emailCanonical = UNACCENT(LOWER(:pattern))',
User::class
))
->setParameter('pattern', $username)
->getSingleResult();
} catch (NoResultException $e) {
@@ -46,12 +54,12 @@ class UserProvider implements UserProviderInterface
public function refreshUser(UserInterface $user): UserInterface
{
if (!$user instanceof User) {
throw new UnsupportedUserException("Unsupported user class: cannot reload this user");
throw new UnsupportedUserException('Unsupported user class: cannot reload this user');
}
$reloadedUser = $this->em->getRepository(User::class)->find($user->getId());
if (NULL === $reloadedUser) {
if (null === $reloadedUser) {
throw new UsernameNotFoundException(sprintf('User with ID "%s" could not be reloaded.', $user->getId()));
}
@@ -60,6 +68,6 @@ class UserProvider implements UserProviderInterface
public function supportsClass($class): bool
{
return $class === User::class;
return User::class === $class;
}
}