- Documentation >
- Permissions >
- Custom Policies
Custom Policies
The content Repository uses Roles and Policies to give Users access to different functions of the system.
Any bundle can expose available Policies via a PolicyProvider
which can be added to IbexaCoreBundle's service container extension.
PolicyProvider
A PolicyProvider
object provides a hash containing declared modules, functions and Limitations.
- Each Policy provider provides a collection of permission modules.
- Each module can provide functions (for example, in
content/read
, "content" is the module, and "read" is the function)
- Each function can provide a collection of Limitations.
First level key is the module name which is limited to characters within the set A-Za-z0-9_
, value is a hash of
available functions, with function name as key. Function value is an array of available Limitations, identified
by the alias declared in LimitationType
service tag. If no Limitation is provided, value can be null
or an empty array.
| [
"content" => [
"read" => ["Class", "ParentClass", "Node", "Language"],
"edit" => ["Class", "ParentClass", "Language"]
],
"custom_module" => [
"custom_function_1" => null,
"custom_function_2" => ["CustomLimitation"]
],
]
|
Limitations need to be implemented as Limitation types and declared as services identified with ibexa.permissions.limitation_type
tag.
Name provided in the hash for each Limitation is the same value set in the alias
attribute in the service tag.
For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 | <?php declare(strict_types=1);
namespace App\Security;
use Ibexa\Bundle\Core\DependencyInjection\Configuration\ConfigBuilderInterface;
use Ibexa\Bundle\Core\DependencyInjection\Security\PolicyProvider\PolicyProviderInterface;
class MyPolicyProvider implements PolicyProviderInterface
{
public function addPolicies(ConfigBuilderInterface $configBuilder)
{
$configBuilder->addConfig([
"custom_module" => [
"custom_function_1" => null,
"custom_function_2" => ["CustomLimitation"],
],
]);
}
}
|
Extend existing Policies
While a PolicyProvider
may provide new functions to an existing Policy module,
or additional Limitations to an existing function,
it's however strongly recommended to create your own modules.
It's impossible to remove an existing module, function or limitation from a Policy.
YamlPolicyProvider
An abstract class based on YAML is provided: Ibexa\Bundle\Core\DependencyInjection\Security\PolicyProvider\YamlPolicyProvider
.
It defines an abstract getFiles()
method.
Extend YamlPolicyProvider
and implement getFiles()
to return absolute paths to your YAML files.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | <?php
declare(strict_types=1);
namespace App\Security;
use Ibexa\Bundle\Core\DependencyInjection\Security\PolicyProvider\YamlPolicyProvider;
class MyPolicyProvider extends YamlPolicyProvider
{
/** @returns string[] */
protected function getFiles(): array
{
return [
__DIR__ . '/../Resources/config/policies.yaml',
];
}
}
|
In src/Resources/config/policies.yaml
:
| # src/Resources/config/policies.yaml
custom_module:
custom_function_1: ~
custom_function_2: [CustomLimitation]
|
Translations
Provide translations for your custom policies in the forms
domain.
For example, translations/forms.en.yaml
:
| role.policy.custom_module: 'Custom module'
role.policy.custom_module.all_functions: 'Custom module / All functions'
role.policy.custom_module.custom_function_1: 'Custom module / Function #1'
role.policy.custom_module.custom_function_2: 'Custom module / Function #2'
|
You can also implement TranslationContainerInterface
to provide those translations in your policy provider class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 | <?php declare(strict_types=1);
namespace App\Security;
use Ibexa\Bundle\Core\DependencyInjection\Configuration\ConfigBuilderInterface;
use Ibexa\Bundle\Core\DependencyInjection\Security\PolicyProvider\PolicyProviderInterface;
class MyPolicyProvider implements PolicyProviderInterface, TranslationContainerInterface
{
public function addPolicies(ConfigBuilderInterface $configBuilder)
{
$configBuilder->addConfig([
"custom_module" => [
"custom_function_1" => null,
"custom_function_2" => ["CustomLimitation"],
],
]);
}
public static function getTranslationMessages(): array
{
return [
(new Message('role.policy.custom_module', 'forms'))->setDesc('Custom module'),
(new Message('role.policy.custom_module.all_functions', 'forms'))->setDesc('Custom module / All functions'),
(new Message('role.policy.custom_module.custom_function_1', 'forms'))->setDesc('Custom module / Function #1'),
(new Message('role.policy.custom_module.custom_function_2', 'forms'))->setDesc('Custom module / Function #2'),
];
}
}
|
Then, extract this translation to generate the English translation file translations/forms.en.xlf
:
| php bin/console translation:extract en --domain=forms --dir=src --output-dir=translations
|
PolicyProvider
integration into IbexaCoreBundle
For a PolicyProvider
to be active, you have to register it in the src/Kernel.php
:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 | <?php
declare(strict_types=1);
namespace App;
use App\Security\MyPolicyProvider;
use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel as BaseKernel;
class Kernel extends BaseKernel
{
use MicroKernelTrait;
protected function build(ContainerBuilder $container): void
{
// Retrieve "ibexa" container extension
/** @var \Ibexa\Bundle\Core\DependencyInjection\IbexaCoreExtension $ibexaExtension */
$ibexaExtension = $container->getExtension('ibexa');
// Add the policy provider
$ibexaExtension->addPolicyProvider(new MyPolicyProvider());
}
}
|
Custom Limitation type
For a custom module function, you can use existing limitation types or create custom ones.
The base of a custom limitation is a class to store values for the usage of this limitation in roles, and a class to implement the limitation's logic.
The value class extends Ibexa\Contracts\Core\Repository\Values\User\Limitation
and says for which limitation it's used:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | <?php
declare(strict_types=1);
namespace App\Security\Limitation;
use Ibexa\Contracts\Core\Repository\Values\User\Limitation;
class CustomLimitationValue extends Limitation
{
public function getIdentifier(): string
{
return 'CustomLimitation';
}
}
|
The type class implements Ibexa\Contracts\Core\Limitation\Type
.
accept
, validate
and buildValue
implement the value class usage logic.
evaluate
challenges a limitation value against the current user, the subject object and other context objects to return if the limitation is satisfied or not. evaluate
is, among others, used by PermissionResolver::canUser
(to check if a user that has access to a function can use it in its limitations) and PermissionResolver::lookupLimitations
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83 | <?php
declare(strict_types=1);
namespace App\Security\Limitation;
use Ibexa\Contracts\Core\Limitation\Type;
use Ibexa\Contracts\Core\Repository\Exceptions\NotImplementedException;
use Ibexa\Contracts\Core\Repository\Values\Content\Query\CriterionInterface;
use Ibexa\Contracts\Core\Repository\Values\User\Limitation;
use Ibexa\Contracts\Core\Repository\Values\User\UserReference;
use Ibexa\Contracts\Core\Repository\Values\ValueObject;
use Ibexa\Core\Base\Exceptions\InvalidArgumentException;
use Ibexa\Core\Base\Exceptions\InvalidArgumentType;
use Ibexa\Core\FieldType\ValidationError;
class CustomLimitationType implements Type
{
public function acceptValue(Limitation $limitationValue): void
{
if (!$limitationValue instanceof CustomLimitationValue) {
throw new InvalidArgumentType(
'$limitationValue',
CustomLimitationValue::class,
$limitationValue
);
}
}
/** @return \Ibexa\Core\FieldType\ValidationError[] */
public function validate(Limitation $limitationValue): array
{
$validationErrors = [];
if (!array_key_exists('value', $limitationValue->limitationValues)) {
$validationErrors[] = new ValidationError("limitationValues['value'] is missing.");
} elseif (!is_bool($limitationValue->limitationValues['value'])) {
$validationErrors[] = new ValidationError("limitationValues['value'] is not a boolean.");
}
return $validationErrors;
}
public function buildValue(array $limitationValues): CustomLimitationValue
{
$value = false;
if (array_key_exists('value', $limitationValues)) {
$value = $limitationValues['value'];
} elseif (count($limitationValues)) {
$value = (bool)$limitationValues[0];
}
return new CustomLimitationValue(['limitationValues' => ['value' => $value]]);
}
/**
* @param \Ibexa\Contracts\Core\Repository\Values\ValueObject[]|null $targets
*
* @return bool|null
*/
public function evaluate(Limitation $value, UserReference $currentUser, ValueObject $object, array $targets = null): ?bool
{
if (!$value instanceof CustomLimitationValue) {
throw new InvalidArgumentException('$value', 'Must be of type: CustomLimitationValue');
}
if ($value->limitationValues['value']) {
return Type::ACCESS_GRANTED;
}
// If the limitation value is not set to `true`, then $currentUser, $object and/or $targets could be challenged to determine if the access is granted or not; Here or elsewhere. When passing the baton, a limitation can return Type::ACCESS_ABSTAIN
return Type::ACCESS_DENIED;
}
public function getCriterion(Limitation $value, UserReference $currentUser): CriterionInterface
{
throw new NotImplementedException(__METHOD__);
}
public function valueSchema()
{
throw new NotImplementedException(__METHOD__);
}
}
|
The type class is set as a service tagged ibexa.permissions.limitation_type
with an alias to identify it, and to link it to the value.
| services:
# …
App\Security\Limitation\CustomLimitationType:
tags:
- { name: 'ibexa.permissions.limitation_type', alias: 'CustomLimitation' }
|
To provide support for editing custom policies in the Back Office, you need to implement Ibexa\AdminUi\Limitation\LimitationFormMapperInterface
.
mapLimitationForm
adds the limitation field as a child to a provided Symfony form.
getFormTemplate
returns the path to the template to use for rendering the limitation form. Here it use form_label
and form_widget
to do so.
filterLimitationValues
is triggered when the form is submitted and can manipulate the limitation values, such as normalizing them.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 | <?php
declare(strict_types=1);
namespace App\Security\Limitation\Mapper;
use Ibexa\AdminUi\Limitation\LimitationFormMapperInterface;
use Ibexa\AdminUi\Translation\Extractor\LimitationTranslationExtractor;
use Ibexa\Contracts\Core\Repository\Values\User\Limitation;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormInterface;
class CustomLimitationFormMapper implements LimitationFormMapperInterface
{
public function mapLimitationForm(FormInterface $form, Limitation $data): void
{
$form->add('limitationValues', CheckboxType::class, [
'label' => LimitationTranslationExtractor::identifierToLabel($data->getIdentifier()),
'required' => false,
'data' => $data->limitationValues['value'],
'property_path' => 'limitationValues[value]',
]);
}
public function getFormTemplate(): string
{
return '@ibexadesign/limitation/custom_limitation_form.html.twig';
}
public function filterLimitationValues(Limitation $limitation): void
{
}
}
|
Provide a template corresponding to getFormTemplate
.
| {# templates/themes/admin/limitation/custom_limitation_form.html.twig #}
{{ form_label(form.limitationValues) }}
{{ form_widget(form.limitationValues) }}
|
Next, register the service with the ibexa.admin_ui.limitation.mapper.form
tag and set the limitationType
attribute to the Limitation type's identifier:
| App\Security\Limitation\Mapper\CustomLimitationFormMapper:
tags:
- { name: 'ibexa.admin_ui.limitation.mapper.form', limitationType: 'CustomLimitation' }
|
Some abstract Limitation type form mapper classes are provided to help implementing common complex Limitations.
MultipleSelectionBasedMapper
is a mapper used to build forms for Limitations based on a checkbox list, where multiple items can be chosen. For example, it's used to build forms for Content Type Limitation, Language Limitation or Section Limitation.
UDWBasedMapper
is used to build a Limitation form where a Content/Location must be selected. For example, it's used by the Subtree Limitation form.
Value mapper
By default, without a value mapper, the Limitation value is rendered by using the block ez_limitation_value_fallback
of the template vendor/ibexa/admin-ui/src/bundle/Resources/views/themes/admin/limitation/limitation_values.html.twig
.
To customize the rendering, a value mapper eventually transforms the Limitation value and sends it to a custom template.
The value mapper implements Ibexa\AdminUi\Limitation\LimitationValueMapperInterface
.
Its mapLimitationValue
function returns the Limitation value transformed for the needs of the template.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | <?php
declare(strict_types=1);
namespace App\Security\Limitation\Mapper;
use Ibexa\AdminUi\Limitation\LimitationValueMapperInterface;
use Ibexa\Contracts\Core\Repository\Values\User\Limitation;
class CustomLimitationValueMapper implements LimitationValueMapperInterface
{
public function mapLimitationValue(Limitation $limitation): bool
{
return $limitation->limitationValues['value'];
}
}
|
Then register the service with the ibexa.admin_ui.limitation.mapper.value
tag and set the limitationType
attribute to Limitation type's identifier:
| App\Security\Limitation\Mapper\CustomLimitationValueMapper:
tags:
- { name: 'ibexa.admin_ui.limitation.mapper.value', limitationType: 'CustomLimitation' }
|
When a value mapper exists for a Limitation, the rendering uses a Twig block named ez_limitation_<lower_case_identifier>_value
where <lower_case_identifier>
is the Limitation identifier in lower case.
In this example, block name is ez_limitation_customlimitation_value
as the identifier is CustomLimitation
.
This template receives a values
variable which is the return of the mapLimitationValue
function from the corresponding value mapper.
| {# templates/themes/standard/limitation/custom_limitation_value.html.twig #}
{% block ez_limitation_customlimitation_value %}
<span style="color: {{ values ? 'green' : 'red' }};">{{ values ? 'Yes' : 'No' }}</span>
{% endblock %}
|
To have your block found, you have to register its template.
Add the template to the configuration under ezplatform.system.<SCOPE>.limitation_value_templates
:
| ibexa:
system:
default:
limitation_value_templates:
- { template: '@ibexadesign/limitation/custom_limitation_value.html.twig', priority: 0 }
|
Provide translations for your custom limitation form in the ibexa_content_forms_policies
domain.
For example, translations/ibexa_content_forms_policies.en.yaml
:
| policy.limitation.identifier.customlimitation: 'Custom limitation'
|
Custom Limitation check
Check if current user has this custom limitation set to true from a custom controller:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 | <?php declare(strict_types=1);
namespace App\Controller;
use Ibexa\Contracts\AdminUi\Controller\Controller;
use Ibexa\Contracts\AdminUi\Permission\PermissionCheckerInterface;
use Ibexa\Contracts\Core\Repository\PermissionResolver;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CustomController extends Controller
{
// ...
/** @var PermissionResolver */
private $permissionResolver;
/** @var PermissionCheckerInterface */
private $permissionChecker;
public function __construct(
// ...,
PermissionResolver $permissionResolver,
PermissionCheckerInterface $permissionChecker
)
{
// ...
$this->permissionResolver = $permissionResolver;
$this->permissionChecker = $permissionChecker;
}
// Controller actions...
public function customAction(Request $request): Response {
// ...
if ($this->getCustomLimitationValue()) {
// Action only for user having the custom limitation checked
}
}
private function getCustomLimitationValue(): bool {
$customLimitationValues = $this->permissionChecker->getRestrictions($this->permissionResolver->hasAccess('custom_module', 'custom_function_2'), CustomLimitationValue::class);
return $customLimitationValues['value'] ?? false;
}
public function performAccessCheck()
{
parent::performAccessCheck();
$this->denyAccessUnlessGranted(new Attribute('custom_module', 'custom_function_2'));
}
}
|