Added a simple Voter for checking, if a user is allowed, to view/edit/create a part.

This commit is contained in:
Jan Böhmer 2019-03-18 19:05:41 +01:00
parent ab3f5db174
commit 01e1f27b68
10 changed files with 750 additions and 4 deletions

40
config/permissions.yaml Normal file
View file

@ -0,0 +1,40 @@
# In this file the possible permissions are defined.
# This should be compatible with the legacy Part-DB
perms: # Here comes a list with all Permission names (they have a perm_[name] coloumn in DB)
parts: # e.g. this maps to perms_parts in User/Group database
# label: "perm.parts"
operations: # Here are all possible operations are listed => the op name is mapped to bit value
read:
bit: 0
edit:
# label: "perm.part.edit"
bit: 2
create:
bit: 4
move:
bit: 6
delete:
bit: 8
search:
bit: 10
all_parts:
bit: 12
no_price_parts:
bit: 14
obsolete_parts:
bit: 16
unknown_instock_parts:
bit: 18
change_favorite:
bit: 20
show_favorite_parts:
bit: 24
show_last_edit_parts:
bit: 26
show_users:
bit: 28
show_history:
bit: 30

View file

@ -0,0 +1,65 @@
<?php
/**
*
* part-db version 0.1
* Copyright (C) 2005 Christoph Lechner
* http://www.cl-projects.de/
*
* part-db version 0.2+
* Copyright (C) 2009 K. Jacobs and others (see authors.php)
* http://code.google.com/p/part-db/
*
* Part-DB Version 0.4+
* Copyright (C) 2016 - 2019 Jan Böhmer
* https://github.com/jbtronics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
namespace App\Configuration;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class PermissionsConfiguration implements ConfigurationInterface
{
/**
* Generates the configuration tree builder.
*
* @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('permissions');
$rootNode = $treeBuilder->root('permissions');
$rootNode->children()
->arrayNode('perms')
->arrayPrototype()
->children()
->scalarNode('label')->end()
->arrayNode('operations')
->arrayPrototype()
->children()
->scalarNode('name')->end()
->scalarNode('label')->end()
->scalarNode('bit')->end();
return $treeBuilder;
}
}

View file

@ -40,6 +40,7 @@ use App\Services\AttachmentFilenameService;
use App\Services\EntityURLGenerator;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
@ -54,6 +55,8 @@ class PartController extends AbstractController
*/
public function show(Part $part, AttachmentFilenameService $attachmentFilenameService)
{
$this->denyAccessUnlessGranted('read', $part);
$filename = $part->getMasterPictureFilename(true);
return $this->render('show_part_info.html.twig',
@ -72,8 +75,9 @@ class PartController extends AbstractController
*/
public function edit(Part $part, Request $request, EntityManagerInterface $em)
{
$form = $this->createForm(PartType::class, $part);
$this->denyAccessUnlessGranted('edit', $part);
$form = $this->createForm(PartType::class, $part);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
@ -98,6 +102,8 @@ class PartController extends AbstractController
{
$new_part = new Part();
$this->denyAccessUnlessGranted('create', $new_part);
$cid = $request->get('cid', 1);
$category = $em->find(Category::class, $cid);

View file

@ -31,6 +31,7 @@
namespace App\Entity;
use App\Security\Interfaces\HasPermissionsInterface;
use Doctrine\ORM\Mapping as ORM;
/**
@ -40,7 +41,7 @@ use Doctrine\ORM\Mapping as ORM;
* @ORM\Entity()
* @ORM\Table("groups")
*/
class Group extends StructuralDBElement
class Group extends StructuralDBElement implements HasPermissionsInterface
{
/**
@ -59,6 +60,11 @@ class Group extends StructuralDBElement
*/
protected $users;
/** @var PermissionsEmbed
* @ORM\Embedded(class="PermissionsEmbed", columnPrefix="perms_")
*/
protected $permissions;
/**
* Returns the ID as an string, defined by the element class.
@ -69,4 +75,9 @@ class Group extends StructuralDBElement
{
return 'G' . sprintf('%06d', $this->getID());
}
public function getPermissions(): PermissionsEmbed
{
return $this->permissions;
}
}

View file

@ -0,0 +1,334 @@
<?php
/**
*
* part-db version 0.1
* Copyright (C) 2005 Christoph Lechner
* http://www.cl-projects.de/
*
* part-db version 0.2+
* Copyright (C) 2009 K. Jacobs and others (see authors.php)
* http://code.google.com/p/part-db/
*
* Part-DB Version 0.4+
* Copyright (C) 2016 - 2019 Jan Böhmer
* https://github.com/jbtronics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Webmozart\Assert\Assert;
/**
* This entity represents the permission fields a user or group can have.
*
* @ORM\Embeddable()
* @package App\Entity
*/
class PermissionsEmbed
{
/**
* Permission values
*/
public const INHERIT = 0b00;
public const ALLOW = 0b01;
public const DISALLOW = 0b10;
/**
* Permission strings
*/
const STORELOCATIONS = 'storelocations';
const FOOTRPINTS = 'footprints';
const CATEGORIES = 'categories';
const SUPPLIERS = 'suppliers';
const MANUFACTURERS = 'manufacturers';
const DEVICES = 'devices';
const ATTACHMENT_TYPES = 'attachment_types';
const TOOLS = 'tools';
const PARTS = 'parts';
const PARTS_NAME = 'parts_name';
const PARTS_DESCRIPTION = 'parts_description';
const PARTS_INSTOCK = 'parts_instock';
const PARTS_MININSTOCK = 'parts_mininstock';
const PARTS_FOOTPRINT = 'parts_footprint';
const PARTS_COMMENT = 'parts_comment';
const PARTS_STORELOCATION = 'parts_storelocation';
const PARTS_MANUFACTURER = 'parts_manufacturer';
const PARTS_ORDERDETAILS = 'parts_orderdetails';
const PARTS_PRICES = 'parts_prices';
const PARTS_ATTACHMENTS = 'parts_attachments';
const PARTS_ORDER = 'parts_order';
const GROUPS = 'groups';
const USERS = 'users';
const DATABASE = 'system_database';
const CONFIG = 'system_config';
const SYSTEM = 'system';
const DEVICE_PARTS = 'devices_parts';
const SELF = 'self';
const LABELS = 'labels';
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $system;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $groups;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $users;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $self;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $system_config;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $system_database;
/**
* @var int
* @ORM\Column(type="bigint")
*/
protected $parts;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_name;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_description;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_instock;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_mininstock;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_footprint;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_storelocation;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_manufacturer;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_comment;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_order;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_orderdetails;
/**
* @var int
* @ORM\Column(type="smallint")
*/
protected $parts_prices;
/**
* @var int
* @ORM\Column(type="smallint", name="parts_attachements")
*/
protected $parts_attachments;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $devices;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $devices_parts;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $storelocations;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $footprints;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $categories;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $suppliers;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $manufacturers;
/**
* @var int
* @ORM\Column(type="integer", name="attachement_types")
*/
protected $attachment_types;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $tools;
/**
* @var int
* @ORM\Column(type="integer")
*/
protected $labels;
/**
* Returns the bit pair value of the given permission.
* @param string $permission_name The name of the permission, for which the bit pair should be returned.
* @param int $bit_n The (lower) bit number of the bit pair, which should be read.
* @return int The value of the bit pair. Compare to the INHERIT, ALLOW, and DISALLOW consts in this class.
*/
public function getBitValue(string $permission_name, int $bit_n) : int
{
$perm_int = $this->$permission_name;
return static::readBitPair($perm_int, $bit_n);
}
/**
* Returns the value of the operation for the given permission.
* @param string $permission_name The name of the permission, for which the operation should be returned.
* @param int $bit_n The (lower) bit number of the bit pair for the operation.
* @return bool|null The value of the operation. True, if the given operation is allowed, false if disallowed
* and null if it should inherit from parent.
*/
public function getPermissionValue(string $permission_name, int $bit_n) : ?bool
{
$value = $this->getBitValue($permission_name, $bit_n);
if($value == self::ALLOW) {
return true;
} elseif($value == self::DISALLOW) {
return false;
} else {
return null;
}
}
/**
* Reads a bit pair from $data.
* @param $data int The data from where the bits should be extracted from.
* @param $n int The number of the lower bit (of the pair) that should be read. Starting from zero.
* @return int The value of the bit pair.
*/
final protected static function readBitPair(int $data, int $n): int
{
Assert::lessThanEq($n,31, '$n must be smaller than 32, because only a 32bit int is used! Got %s.');
if ($n % 2 !== 0) {
throw new \InvalidArgumentException('$n must be dividable by 2, because we address bit pairs here!');
}
$mask = 0b11 << $n; //Create a mask for the data
return ($data & $mask) >> $n; //Apply mask and shift back
}
/**
* Writes a bit pair in the given $data and returns it.
* @param $data int The data which should be modified.
* @param $n int The number of the lower bit of the pair which should be written.
* @param $new int The new value of the pair.
* @return int The new data with the modified pair.
*/
final protected static function writeBitPair(int $data, int $n, int $new) : int
{
Assert::lessThanEq($n,31, '$n must be smaller than 32, because only a 32bit int is used! Got %s.');
Assert::lessThanEq($new, 3, '$new must be smaller than 3, because a bit pair is written! Got %s.');
if ($n % 2 !== 0) {
throw new \InvalidArgumentException('$n must be dividable by 2, because we address bit pairs here!');
}
$mask = 0b11 << $n; //Mask all bits that should be writen
$newval = $new << $n; //The new value.
$data = ($data & ~$mask) | ($newval & $mask);
return $data;
}
}

View file

@ -131,6 +131,15 @@ abstract class StructuralDBElement extends AttachmentContainingDBElement
return $this->parent_id ?? self::ID_ROOT_ELEMENT; //Null means root element
}
/**
* Get the parent of this element.
* @return StructuralDBElement|null The parent element. Null if this element, does not have a parent.
*/
public function getParent() : ?self
{
return $this->parent;
}
/**
* Get the comment of the element.
*

View file

@ -32,6 +32,8 @@
namespace App\Entity;
use App\Entity\Embeddables\PermissionEntity;
use App\Security\Interfaces\HasPermissionsInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
@ -43,7 +45,7 @@ use Symfony\Component\Validator\Constraints as Assert;
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @ORM\Table("users")
*/
class User extends NamedDBElement implements UserInterface
class User extends NamedDBElement implements UserInterface, HasPermissionsInterface
{
/**
* @ORM\Id()
@ -115,11 +117,16 @@ class User extends NamedDBElement implements UserInterface
/**
* @var Group|null The group this user belongs to.
* @ORM\ManyToOne(targetEntity="Group", inversedBy="users")
* @ORM\ManyToOne(targetEntity="Group", inversedBy="users", fetch="EAGER")
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
*/
protected $group;
/** @var PermissionsEmbed
* @ORM\Embedded(class="PermissionsEmbed", columnPrefix="perms_")
*/
protected $permissions;
/**
* A visual identifier that represents this user.
@ -200,6 +207,11 @@ class User extends NamedDBElement implements UserInterface
}
public function getPermissions() : PermissionsEmbed
{
return $this->permissions;
}
/************************************************
* Getters
************************************************/

View file

@ -0,0 +1,40 @@
<?php
/**
*
* part-db version 0.1
* Copyright (C) 2005 Christoph Lechner
* http://www.cl-projects.de/
*
* part-db version 0.2+
* Copyright (C) 2009 K. Jacobs and others (see authors.php)
* http://code.google.com/p/part-db/
*
* Part-DB Version 0.4+
* Copyright (C) 2016 - 2019 Jan Böhmer
* https://github.com/jbtronics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
namespace App\Security\Interfaces;
use App\Entity\PermissionsEmbed;
interface HasPermissionsInterface
{
public function getPermissions() : PermissionsEmbed;
}

View file

@ -0,0 +1,62 @@
<?php
namespace App\Security\Voter;
use App\Configuration\PermissionsConfiguration;
use App\Entity\Part;
use App\Entity\User;
use App\Services\PermissionResolver;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* A Voter that votes on Part entities.
*
* See parts permissions for valid operations.
*
* @package App\Security\Voter
*/
class PartVoter extends Voter
{
const READ = "read";
protected $resolver;
public function __construct(PermissionResolver $resolver)
{
$this->resolver = $resolver;
}
protected function supports($attribute, $subject)
{
// replace with your own logic
// https://symfony.com/doc/current/security/voters.html
//return ($subject instanceof Part || in_array($subject, ['PERM_parts', 'PERM_parts_name']));
if ($subject instanceof Part)
{
return in_array($attribute, $this->resolver->listOperationsForPermission('parts'), false);
}
return false;
}
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
$user = $token->getUser();
// if the user is anonymous, do not grant access
if (!$user instanceof User) {
return false;
}
if($subject instanceof Part) {
//Null concealing operator means, that no
return $this->resolver->inherit($user, 'parts', $attribute) ?? false;
}
//Deny access by default.
return false;
}
}

View file

@ -0,0 +1,167 @@
<?php
/**
*
* part-db version 0.1
* Copyright (C) 2005 Christoph Lechner
* http://www.cl-projects.de/
*
* part-db version 0.2+
* Copyright (C) 2009 K. Jacobs and others (see authors.php)
* http://code.google.com/p/part-db/
*
* Part-DB Version 0.4+
* Copyright (C) 2016 - 2019 Jan Böhmer
* https://github.com/jbtronics
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
namespace App\Services;
use App\Configuration\PermissionsConfiguration;
use App\Entity\User;
use App\Security\Interfaces\HasPermissionsInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Yaml\Yaml;
class PermissionResolver
{
protected $permission_structure;
/**
*
* PermissionResolver constructor.
* @param ParameterBagInterface $params
*/
public function __construct(ParameterBagInterface $params)
{
//Read the permission config file...
$config = Yaml::parse(
file_get_contents(__DIR__ . '/../../config/permissions.yaml')
);
$configs = [$config];
//... And parse it
$processor = new Processor();
$databaseConfiguration = new PermissionsConfiguration();
$processedConfiguration = $processor->processConfiguration(
$databaseConfiguration,
$configs
);
$this->permission_structure = $processedConfiguration;
}
/**
* Check if a user/group is allowed to do the specified operation for the permission.
*
* See permissions.yaml for valid permission operation combinations.
*
* @param HasPermissionsInterface $user The user/group for which the operation should be checked.
* @param string $permission The name of the permission for which should be checked.
* @param string $operation The name of the operation for which should be checked.
* @return bool|null True, if the user is allowed to do the operation (ALLOW), false if not (DISALLOW), and null,
* if the value is set to inherit.
*/
public function dontInherit(HasPermissionsInterface $user, string $permission, string $operation) : ?bool
{
//Get the permissions from the user
$perm_list = $user->getPermissions();
//Determine bit number using our configuration
$bit = $this->permission_structure['perms'][$permission]['operations'][$operation]['bit'];
return $perm_list->getPermissionValue($permission, $bit);
}
/**
* Checks if a user is allowed to do the specified operation for the permission.
* In contrast to dontInherit() it tries to resolve the inherit values, of the user, by going upwards in the
* hierachy (user -> group -> parent group -> so on). But even in this case it is possible, that the inherit value
* could be resolved, and this function returns null.
*
* In that case the voter should set it manually to false by using ?? false.
*
* @param User $user The user for which the operation should be checked.
* @param string $permission The name of the permission for which should be checked.
* @param string $operation The name of the operation for which should be checked.
* @return bool|null True, if the user is allowed to do the operation (ALLOW), false if not (DISALLOW), and null,
* if the value is set to inherit.
*/
public function inherit(User $user, string $permission, string $operation) : ?bool
{
//Check if we need to inherit
$allowed = $this->dontInherit($user, $permission, $operation);
if ($allowed !== null) {
//Just return the value of the user.
return $allowed;
}
$parent = $user->getGroup();
while($parent != null){ //The top group, has parent == null
//Check if our current element gives a info about disallow/allow
$allowed = $this->dontInherit($parent, $permission, $operation);
if ($allowed !== null) {
return $allowed;
}
//Else go up in the hierachy.
$parent = $parent->getParent();
}
return null; //The inherited value is never resolved. Should be treat as false, in Voters.
}
/**
* Lists the names of all operations that is supported for the given permission.
*
* If the Permission is not existing at all, a exception is thrown.
*
* This function is useful for the support() function of the voters.
*
* @param string $permission The permission for which the
* @return string[] A list of all operations that are supported by the given
*/
public function listOperationsForPermission(string $permission) : array
{
$operations = $this->permission_structure['perms'][$permission]['operations'];
return array_keys($operations);
}
/**
* Checks if the permission with the given name is existing.
*
* @param string $permission The name of the permission which we want to check.
* @return bool True if a perm with that name is existing. False if not.
*/
public function isValidPermission(string $permission) : bool
{
return isset($this->permission_structure['perms'][$permission]);
}
}