orisai/auth

Authentication and authorization

2.0.3 2024-06-21 09:02 UTC

This package is auto-updated.

Last update: 2024-10-27 14:13:01 UTC


README

Orisai
Auth

Authentication and authorization

📄 Check out our documentation.

💸 If you like Orisai, please make a donation. Thank you!

This package is inspired by nette/security from David Grudl. Thank you, David!

namespace App\Admin\Article\View;

use Orisai\Auth\Authentication\Identity;
use Orisai\Auth\Authentication\SimpleFirewall;

final class ArticleEditController
{

	private SimpleFirewall $firewall;

	public function __construct(SimpleFirewall $firewall)
	{
		$this->firewall = $firewall;
	}

	public function run(): void
	{
		if (!$this->firewall->isAllowed('administration.entry')) {
			// Not allowed
		}

		$article = /* get article by ID from request */;

		if (!$this->firewall->isAllowed('article.edit', $article)) {
			// Not allowed
		}

		// Is allowed
	}

}

use App\Core\Article\Article;
use Orisai\Auth\Authorization\Policy;
use Orisai\Auth\Authorization\PolicyContext;

/**
 * @implements Policy<Article>
 */
final class ArticleEditPolicy implements Policy
{

	public static function getPrivilege(): string
	{
		return 'article.edit';
	}

	public static function getRequirementsClass(): string
	{
		return Article::class;
	}

	/**
	 * @param Article $requirements
	 */
	public function isAllowed(Identity $identity, object $requirements, PolicyContext $context): bool
	{
		$authorizer = $context->getAuthorizer();

		return $authorizer->hasPrivilege($identity, self::getPrivilege())
			&& $requirements->getAuthor()->getId() === $identity->getId();
	}

}