fix folder name

This commit is contained in:
2021-03-18 13:37:13 +01:00
parent a2f6773f5a
commit eaa0ad925f
1578 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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\Authorization;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* Voter for Chill software.
*
* This abstract Voter provide generic methods to handle object specific to Chill
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
abstract class AbstractChillVoter extends Voter implements ChillVoterInterface
{
protected function supports($attribute, $subject)
{
@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);
return \in_array($attribute, $this->getSupportedAttributes($attribute))
&& \in_array(\get_class($subject), $this->getSupportedClasses());
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
@trigger_error('This voter should implements the new `voteOnAttribute` '
. 'methods introduced by Symfony 3.0, and do not rely on '
. 'isGranted method', E_USER_DEPRECATED);
return $this->isGranted($attribute, $subject, $token->getUser());
}
}

View File

@@ -0,0 +1,308 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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\Authorization;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\HasCenterInterface;
use Chill\MainBundle\Entity\HasScopeInterface;
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
use Symfony\Component\Security\Core\Role\Role;
use Chill\MainBundle\Entity\Scope;
use Chill\MainBundle\Security\RoleProvider;
use Doctrine\ORM\EntityManagerInterface;
use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\RoleScope;
/**
* Helper for authorizations.
*
* Provides methods for user and entities information.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class AuthorizationHelper
{
/**
*
* @var RoleHierarchyInterface
*/
protected $roleHierarchy;
/**
* The role in a hierarchy, given by the parameter
* `security.role_hierarchy.roles` from the container.
*
* @var string[]
*/
protected $hierarchy;
/**
*
* @var EntityManagerInterface
*/
protected $em;
public function __construct(
RoleHierarchyInterface $roleHierarchy,
$hierarchy,
EntityManagerInterface $em
) {
$this->roleHierarchy = $roleHierarchy;
$this->hierarchy = $hierarchy;
$this->em = $em;
}
/**
* Determines if a user is active on this center
*
* @param User $user
* @param Center $center
* @return bool
*/
public function userCanReachCenter(User $user, Center $center)
{
foreach ($user->getGroupCenters() as $groupCenter) {
if ($center->getId() === $groupCenter->getCenter()->getId()) {
return true;
}
}
return false;
}
/**
*
* 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 HasCenterInterface $entity the entity may also implement HasScopeInterface
* @param string|Role $attribute
* @return boolean true if the user has access
*/
public function userHasAccess(User $user, HasCenterInterface $entity, $attribute)
{
$center = $entity->getCenter();
if (!$this->userCanReachCenter($user, $center)) {
return false;
}
$role = ($attribute instanceof Role) ? $attribute : new Role($attribute);
foreach ($user->getGroupCenters() as $groupCenter){
//filter on center
if ($groupCenter->getCenter()->getId() === $entity->getCenter()->getId()) {
$permissionGroup = $groupCenter->getPermissionsGroup();
//iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role allow to reach the required role
if ($this->isRoleReached($role,
new Role($roleScope->getRole()))){
//if yes, we have a right on something...
// perform check on scope if necessary
if ($entity instanceof HasScopeInterface) {
$scope = $entity->getScope();
if ($scope === NULL) {
return true;
}
if ($scope->getId() === $roleScope
->getScope()->getId()) {
return true;
}
} else {
return true;
}
}
}
}
}
return false;
}
/**
* Get reachable Centers for the given user, role,
* and optionnaly Scope
*
* @param User $user
* @param Role $role
* @param null|Scope $scope
* @return Center[]
*/
public function getReachableCenters(User $user, Role $role, Scope $scope = null)
{
$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,
new Role($roleScope->getRole()))) {
if ($scope === null) {
$centers[] = $groupCenter->getCenter();
break 1;
} else {
if ($scope->getId() == $roleScope->getScope()->getId()){
$centers[] = $groupCenter->getCenter();
break 1;
}
}
}
}
}
return $centers;
}
/**
* Return all reachable scope for a given user, center and role
*
* @deprecated Use getReachableCircles
*
* @param User $user
* @param Role $role
* @param Center $center
* @return Scope[]
*/
public function getReachableScopes(User $user, Role $role, Center $center)
{
return $this->getReachableCircles($user, $role, $center);
}
/**
* Return all reachable circle for a given user, center and role
*
* @param User $user
* @param Role $role
* @param Center $center
* @return Scope[]
*/
public function getReachableCircles(User $user, Role $role, Center $center)
{
$scopes = array();
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) {
//check that the role is in the reachable roles
if ($this->isRoleReached($role,
new Role($roleScope->getRole()))) {
$scopes[] = $roleScope->getScope();
}
}
}
}
return $scopes;
}
/**
*
* @param Role $role
* @param Center $center
* @param Scope $circle
* @return Users
*/
public function findUsersReaching(Role $role, Center $center, Scope $circle = null)
{
$parents = $this->getParentRoles($role);
$parents[] = $role;
$parentRolesString = \array_map(function(Role $r) { return $r->getRole(); }, $parents);
$qb = $this->em->createQueryBuilder();
$qb
->select('u')
->from(User::class, 'u')
->join('u.groupCenters', 'gc')
->join('gc.permissionsGroup', 'pg')
->join('pg.roleScopes', 'rs')
->where('gc.center = :center')
->andWhere($qb->expr()->in('rs.role', $parentRolesString))
;
$qb->setParameter('center', $center);
if ($circle !== null) {
$qb->andWhere('rs.scope = :circle')
->setParameter('circle', $circle)
;
}
return $qb->getQuery()->getResult();
}
/**
* Test if a parent role may give access to a given child role
*
* @param Role $childRole The role we want to test if he is reachable
* @param Role $parentRole The role which should give access to $childRole
* @return boolean true if the child role is granted by parent role
*/
protected function isRoleReached(Role $childRole, Role $parentRole)
{
$reachableRoles = $this->roleHierarchy
->getReachableRoles([$parentRole]);
return in_array($childRole, $reachableRoles);
}
/**
* Return all the role which give access to the given role. Only the role
* which are registered into Chill are taken into account.
*
* @param Role $role
* @return Role[] the role which give access to the given $role
*/
public function getParentRoles(Role $role)
{
$parentRoles = [];
// transform the roles from role hierarchy from string to Role
$roles = \array_map(
function($string) {
return new Role($string);
},
\array_keys($this->hierarchy)
);
foreach ($roles as $r) {
$childRoles = $this->roleHierarchy->getReachableRoleNames([$r->getRole()]);
if (\in_array($role, $childRoles)) {
$parentRoles[] = $r;
}
}
return $parentRoles;
}
}

View File

@@ -0,0 +1,62 @@
<?php
/*
* Copyright (C) 2018 Julien Fastré <julien.fastre@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\Authorization;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Role\Role;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class ChillExportVoter extends Voter
{
const EXPORT = 'chill_export';
/**
*
* @var AuthorizationHelper
*/
protected $authorizationHelper;
public function __construct(AuthorizationHelper $authorizationHelper)
{
$this->authorizationHelper = $authorizationHelper;
}
protected function supports($attribute, $subject): bool
{
return $attribute === self::EXPORT;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
if (!$token->getUser() instanceof User) {
return false;
}
$centers = $this->authorizationHelper
->getReachableCenters($token->getUser(), new Role($attribute));
return count($centers) > 0;
}
}

View File

@@ -0,0 +1,30 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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\Authorization;
/**
* Provides methods for compiling voter and build admin role fields.
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ChillVoterInterface
{
}

View File

@@ -0,0 +1,118 @@
<?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\Entity\User;
use Symfony\Component\EventDispatcher\Event;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverEvent extends Event
{
/**
*
* @var User
*/
protected $user;
/**
*
* @var string
*/
protected $token;
/**
*
* @var string
*/
protected $ip;
/**
*
* @var boolean
*/
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';
/**
*
* @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)
{
$this->user = $user;
$this->token = $token;
$this->ip = $ip;
$this->safelyGenerated = $safelyGenerated;
}
/**
*
* @return User|null
*/
public function getUser()
{
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

@@ -0,0 +1,83 @@
<?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\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' ]
],
PasswordRecoverEvent::ASK_TOKEN_INVALID_FORM => [
[ 'onAskTokenInvalidForm' ]
],
PasswordRecoverEvent::ASK_TOKEN_SUCCESS => [
[ '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());
}
}

View File

@@ -0,0 +1,170 @@
<?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\Redis\ChillRedis;
use Psr\Log\LoggerInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class PasswordRecoverLocker
{
/**
* The maximum of invalid token globally (across all ip)
*/
const MAX_INVALID_TOKEN_GLOBAL = 50;
/**
* The maximum of invalid token by ip
*/
const MAX_INVALID_TOKEN_BY_IP = 10;
/**
* TTL to keep invalid token recorded
*/
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;
/**
*
* @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++) {
$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;
}
}
$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");
}
}
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");
}
}
/**
*
* @param string $usage 'invalid_token_global' or ...
* @param int $number
*/
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");
}
}
}

View File

@@ -0,0 +1,102 @@
<?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;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
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
];
/**
*
* @var PasswordRecoverLocker
*/
protected $locker;
/**
*
* @var RequestStack
*/
protected $requestStack;
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;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
{
switch ($attribute) {
case self::TRY_TOKEN:
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)) {
return false;
}
return true;
case self::ASK_TOKEN:
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)) {
return false;
}
if ($subject instanceof User) {
if (TRUE === $this->locker->isLocked('ask_token_success_by_user', $subject)) {
return false;
}
}
return true;
}
}
}

View File

@@ -0,0 +1,127 @@
<?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;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class RecoverPasswordHelper
{
/**
*
* @var TokenManager
*/
protected $tokenManager;
/**
*
* @var UrlGeneratorInterface
*/
protected $urlGenerator;
/**
*
* @var Mailer
*/
protected $mailer;
protected $routeParameters;
const RECOVER_PASSWORD_ROUTE = 'password_recover';
public function __construct(
TokenManager $tokenManager,
UrlGeneratorInterface $urlGenerator,
Mailer $mailer,
array $routeParameters
) {
$this->tokenManager = $tokenManager;
$this->urlGenerator = $urlGenerator;
$this->mailer = $mailer;
$this->routeParameters = $routeParameters;
}
/**
*
* @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 = [])
{
$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(
$this->tokenManager->generate($user, $expiration),
$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 = [],
$force = false,
array $additionalUrlParameters = [],
$emailSubject = 'Recover your password'
) {
$content = $this->mailer->renderContentToUser(
$user,
$template,
\array_merge([
'user' => $user,
'url' => $this->generateUrl($user, $expiration, true, $additionalUrlParameters)
],
$templateParameters
));
$this->mailer->sendNotification(
$user,
[ $emailSubject ],
[
'text/plain' => $content,
],
null,
$force);
}
}

View File

@@ -0,0 +1,103 @@
<?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\Entity\User;
use Psr\Log\LoggerInterface;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class TokenManager
{
/**
*
* @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;
public function __construct($secret, LoggerInterface $logger)
{
$this->secret = $secret;
$this->logger = $logger;
}
public function generate(User $user, \DateTimeInterface $expiration)
{
$token = \random_bytes(self::TOKEN_LENGTH);
$username = $user->getUsernameCanonical();
if (empty($username)) {
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
];
}
public function verify($hash, $token, User $user, $timestamp)
{
$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')) {
$this->logger->info('receiving a password recover token with expired '
. 'validity');
return false;
}
$expected = \hash('sha1', $token.$username.$timestamp.$this->secret);
if ($expected !== $hash) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,42 @@
<?php
/*
* Copyright (C) 2017 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;
/**
* Give a hierarchy for the role.
*
* This hierarchy allow to sort roles, which is useful in UI
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ProvideRoleHierarchyInterface extends ProvideRoleInterface
{
/**
* Return an array of roles, where keys are the hierarchy, and values
* an array of roles.
*
* Example:
*
* ```
* [ 'Title' => [ 'CHILL_FOO_SEE', 'CHILL_FOO_UPDATE' ] ]
* ```
*
* @return array where keys are the hierarchy, and values an array of roles: `[ 'title' => [ 'CHILL_FOO_SEE', 'CHILL_FOO_UPDATE' ] ]`
*/
public function getRolesWithHierarchy();
}

View File

@@ -0,0 +1,53 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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;
/**
* Declare role
*
* The role are added to the configuration at compile time.
*
* The implemented object must be declared as a service and tagged as
*
* <pre>
* my_role_declaration:
* # ...
* tags:
* - { name: chill.role }
* </pre>
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
interface ProvideRoleInterface
{
/**
* return an array of role provided by the object
*
* @return string[] array of roles (as string)
*/
public function getRoles();
/**
* return roles which doesn't need
*
* @return string[] array of roles without scopes
*/
public function getRolesWithoutScope();
}

View File

@@ -0,0 +1,136 @@
<?php
/*
* Copyright (C) 2015 Julien Fastré <julien.fastre@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;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class RoleProvider
{
/**
*
* @var ProvideRoleInterface[]
*/
private $providers = array();
/**
* an array where keys are the role, and value is the title
* for the given role.
*
* Null when not initialized.
*
* @var array|null
*/
private $rolesTitlesCache = null;
/**
* 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)
{
$this->providers[] = $provider;
}
/**
*
* @return string[] the roles as string
*/
public function getRoles()
{
$roles = array();
foreach ($this->providers as $provider) {
if ($provider->getRoles() !== NULL) {
$roles = array_merge($roles, $provider->getRoles());
}
}
return $roles;
}
/**
*
* @return string[] the roles as string
*/
public function getRolesWithoutScopes()
{
$roles = array();
foreach ($this->providers as $provider) {
if ($provider->getRolesWithoutScope() !== NULL) {
$roles = array_merge($roles, $provider->getRolesWithoutScope());
}
}
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)) {
// this case might happens when the role is not described in
// `getRolesWithHierarchy`
return null;
}
return $this->rolesTitlesCache[$role];
}
}

View File

@@ -0,0 +1,83 @@
<?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\UserProvider;
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 Symfony\Component\Security\Core\Exception\UnsupportedUserException;
/**
*
*
* @author Julien Fastré <julien.fastre@champs-libres.coop>
*/
class UserProvider implements UserProviderInterface
{
/**
*
* @var EntityManagerInterface
*/
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function loadUserByUsername($username): UserInterface
{
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))
->setParameter('pattern', $username)
->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
throw new UsernameNotFoundException(sprintf('Bad credentials.', $username));
}
return $user;
}
public function refreshUser(UserInterface $user): UserInterface
{
if (!$user instanceof User) {
throw new UnsupportedUserException("Unsupported user class: cannot reload this user");
}
$reloadedUser = $this->em->getRepository(User::class)->find($user->getId());
if (NULL === $reloadedUser) {
throw new UsernameNotFoundException(sprintf('User with ID "%s" could not be reloaded.', $user->getId()));
}
return $reloadedUser;
}
public function supportsClass($class): bool
{
return $class === User::class;
}
}