PHPackages                             carrooi/security - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. carrooi/security

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

carrooi/security
================

Modular security system for Nette framework

3.0.0(9y ago)61.1k1[2 issues](https://github.com/Carrooi/Nette-Security/issues)MITPHPPHP &gt;5.6

Since Jan 18Pushed 9y ago2 watchersCompare

[ Source](https://github.com/Carrooi/Nette-Security)[ Packagist](https://packagist.org/packages/carrooi/security)[ RSS](/packages/carrooi-security/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (9)Versions (10)Used By (0)

Carrooi/Security
================

[](#carrooisecurity)

[![Build Status](https://camo.githubusercontent.com/029fb9fe9543cbb1269f89a0f54aa3eb89d8caea57b08dc00d0af8e66399b9f9/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f436172726f6f692f4e657474652d53656375726974792e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/Carrooi/Nette-Security)[![Donate](https://camo.githubusercontent.com/7f8b0c0980ad316210d1ec0c7d3298ace87d2f7c0eb6911977c0644951af5bd2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f646f6e6174652d50617950616c2d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=FQUQ9LVAKADK8)

Extensible authorization built on top of [nette/security](https://github.com/nette/security).

This package came in handy if you want to create modular website and keep all pieces decoupled with "custom" checking for privileges.

Now you can really easily check if eg. given user is author of some book and so on..

This idea comes from [nette/addons](https://github.com/nette/web-addons.nette.org/blob/master/app/model/Authorizator.php)website.

Installation
------------

[](#installation)

```
$ composer require carrooi/security
$ composer update

```

Then just enable nette extension in your config.neon:

```
extensions:
	authorization: Carrooi\Security\DI\SecurityExtension
```

Configuration
-------------

[](#configuration)

```
extendsions:
	authorization: Carrooi\Security\DI\SecurityExtension

authorization:
	default: true

	resources:
		book:
			default: false

			actions:
				view: true
				add:
					loggedIn: true
				edit:
					roles: [admin]
				delete:
					roles: [admin]
```

Well, there is nothing modular.... Yet.... We just say that resource `book` has `view` action which is accessible to everyone, `add` to logged users and `edit` with `delete` actions to users with `admin` role.

There are also two `default` options. With the first one we say that each `->isAllowed()` call on unknown action will automatically return `true`. But the second `default` will overwrite this option for all `book` actions to `false`.

That means that eg. `->isAllowed('book', 'detail')` will return `false`, but `->isAllowed('user', 'detail')` `true`.

Other resources and actions
---------------------------

[](#other-resources-and-actions)

If `default` option is not enough, you can create default resource or default action with asterisk.

```
authorization:

	resources:
		favorites:
			actions:
				*:
					loggedIn: true
```

Custom resource authorizator
----------------------------

[](#custom-resource-authorizator)

Now lets create the same authorization for books by hand.

```
services:

	- App\Model\Books

authorization:
	resources:
		book: App\Model\Books
```

**`App\Model\Books` must be registered service.**

```
namespace App\Model;

use Carrooi\Security\Authorization\IResourceAuthorizator;
use Carrooi\Security\User\User;

/**
 * @author David Kudera
 */
class Books implements IResourceAuthorizator
{

	/**
	 * @return array
	 */
	public function getActions()
	{
		return [
			'view', 'add', 'edit', 'delete',
		];
	}

	/**
	 * @param \Carrooi\Security\User\User $user
	 * @param string $action
	 * @param mixed $data
	 * @return bool
	 */
	public function isAllowed(User $user, $action, $data = null)
	{
		if ($action === 'view') {
			return true;
		}

		if ($action === 'add' && $user->isLoggedIn()) {
			return true;
		}

		if (in_array($action, ['edit', 'delete']) && $user->isInRole('admin')) {
			return true;
		}

		return false;
	}

}
```

You can also return `*` from `getActions()` method to tell that the authorizator can accept any action.

Use objects as resources
------------------------

[](#use-objects-as-resources)

In previous code you may noticed unused argument `$data` in `isAllowed` method. Imagine that you want to allow all users to update or delete their own books. First thing you need to do, is register some kind of "translator" from objects to resource names (lets say mappers).

```
authorization:
	targetResources:
		App\Model\Book: book
```

Now every time you pass `App\Model\Book` object as resource, it will be automatically translated to `book` resource, which will be then processed with your `App\Model\Books` service registered in previous example.

```
namespace App\Presenters;

use Nette\Application\BadRequestException;
use Nette\Application\ForbiddenRequestException;

/**
 * @author David Kudera
 */
class BooksPresenter extends BasePresenter
{

	// ...

	/**
	 * @param int $id
	 * @throws \Nette\Application\BadRequestException
	 * @throws \Nette\Application\ForbiddenRequestException
	 */
	public function actionEdit($id)
	{
		$this->book = $this->books->findOneById($id);
		if (!$this->book) {
			throw new BadRequestException;
		}
		if (!$this->getUser()->isAllowed($this->book, 'edit')) {
			throw new ForbiddenRequestException;
		}
	}

}
```

```
// ...
class Books implements IResourceAuthorizator
{

	// ...
	public function isAllowed(User $user, $action, $data = null)
	{
		// ...

		if (
			in_array($action, ['edit', 'delete']) &&
			$data instanceof Book &&
			(
				$user->isInRole('admin') ||
				$data->getAuthor()->getId() === $user->getId()
			)
		) {
			return true;
		}

		return false;
	}

}
```

Or you can write "magic" `isAllowed` methods:

```
class Books implements IResourceAuthorizator
{

	public function isAllowed(User $user, $action, $data = null)
	{
		return false;
	}

	public function isEditAllowed(User $user, $data = null)
	{
		return true;
	}

}
```

Linking to presenter
--------------------

[](#linking-to-presenter)

```
class BasePresenter extends Nette\Application\UI\Presenter
{

	use Carrooi\Security\Authorization\TPresenterAuthorization;

	public function checkRequirements($element)
	{
		if ($element instanceof Nette\Reflection\Method) {
			if (!$this->checkMethodRequirements($element)) {
				throw new Nette\Application\ForbiddenRequestException;
			}
		}
	}

}
```

Now you can simply use annotations for setting current resource and action

```
class BookPresenter extends BasePresenter
{

	/**
	 * @resource(book)
	 * @action(view)
	 */
	public function actionDefault()
	{

	}

}
```

Securing presenter components and signals
-----------------------------------------

[](#securing-presenter-components-and-signals)

You can restrict any component or signal to some action. With that no one can access for example edit form from add action.

```
class BasePresenter extends Nette\Application\UI\Presenter
{

	use Carrooi\Security\Authorization\TPresenterAuthorization;

	public function checkRequirements($element)
	{
		// ...
	}

	protected function createComponent($name)
	{
		$this->checkComponentRequirements($name);
        return parent::createComponent($name);
	}

}
```

```
class BookPresenter extends BasePresenter
{

	/**
	 * @action(edit)
	 */
	protected function createComponentEditForm()
	{

	}

	/**
	 * @action(default, detail)
	 */
	protected function createComponentFavoriteButton()
	{

	}

	/**
	 * @action(*)
	 */
	protected function createComponentReadLaterButton()
	{

	}

}
```

**Keep in mind that actions at components or signals are presenter actions, not actions at your authorization configuration.**

Now `editForm` component can be rendered only on `edit` action, `favoriteButton` only on `default` or `detail` actions and `readLaterButton` anywhere.

Same `@action` annotations can be used also for signals.

Presenter security modes
------------------------

[](#presenter-security-modes)

By default this package will try to check action, render, handle and createComponent methods. But if you'll omit some annotations, nothing will happen and that method will be allowed. This can be changed by turning on strict mode.

```
authorization:
	actions: strict
	signals: strict
	components: strict
```

Other options are `true` or `false`, where `true` is default value.

Compiler extension
------------------

[](#compiler-extension)

Your own DI compiler extensions can implement interface `Carrooi\Security\DI\ITargetResourcesProvider` for resource mappers.

```
namespace App\DI;

use Carrooi\Security\DI\ITargetResourcesProvider;
use Nette\DI\CompilerExtension;

/**
 * @author David Kudera
 */
class AppExtension extends CompilerExtension implements ITargetResourcesProvider
{

	/**
	 * @return array
	 */
	public function getTargetResources()
	{
		return [
			'App\Model\Book' => 'book',
		];
	}

}
```

Extending User class
--------------------

[](#extending-user-class)

Be carefull if you want to extend `Nette\Security\User` class, because `carrooi\security` already extends that class for it's own needs.

Changelog
---------

[](#changelog)

- 2.0.0

    - Allow resources to have many custom authorizators [\#9](https://github.com/Carrooi/Nette-Security/issues/9) (**BC break**)
- 1.2.1

    - Throw an exception when using not registered resource object [\#8](https://github.com/Carrooi/Nette-Security/issues/8)
- 1.2.0

    - Add support for interfaces at target authorizators [\#5](https://github.com/Carrooi/Nette-Security/issues/5)
    - Refactored tests [\#2](https://github.com/Carrooi/Nette-Security/issues/2)
    - Remove support for magic presenter resource getters [\#7](https://github.com/Carrooi/Nette-Security/issues/7)
    - Fix magic resource authenticator with private `isAllowed` [\#4](https://github.com/Carrooi/Nette-Security/issues/4)
- 1.1.0

    - Add support for magic resource authenticator methods `isAllowed`
- 1.0.3

    - Add lazy register resource authorizators - prevents circular references in some cases
- 1.0.2

    - Looking if given object for authorization is subclass of some registered target resource
- 1.0.1

    - Added default resources and actions (asterisk)
- 1.0.0

    - Initial commit

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance13

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~106 days

Recently: every ~157 days

Total

9

Last Release

3287d ago

Major Versions

1.2.1 → 2.0.02015-08-31

2.0.0 → 3.0.02017-05-17

### Community

Maintainers

![](https://www.gravatar.com/avatar/838c6933d498fdb2a31f251ed45006a6ef97935ea2a27f38dab7738038939fc9?d=identicon)[david\_kudera](/maintainers/david_kudera)

---

Top Contributors

[![davidkudera](https://avatars.githubusercontent.com/u/1174072?v=4)](https://github.com/davidkudera "davidkudera (23 commits)")

---

Tags

nettesecurityauthorizationcarrooi

### Embed Badge

![Health badge](/badges/carrooi-security/health.svg)

```
[![Health](https://phpackages.com/badges/carrooi-security/health.svg)](https://phpackages.com/packages/carrooi-security)
```

###  Alternatives

[lusitanian/oauth

PHP 7.2 oAuth 1/2 Library

1.1k23.2M121](/packages/lusitanian-oauth)[nette/security

🔑 Nette Security: provides authentication, authorization and a role-based access control management via ACL (Access Control List)

3839.3M279](/packages/nette-security)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
