Skip to content

Commit

Permalink
updated token to return claims
Browse files Browse the repository at this point in the history
  • Loading branch information
eluhr committed Jan 9, 2023
1 parent 8138285 commit 88cb5fa
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 2 deletions.
10 changes: 9 additions & 1 deletion src/components/BaseTokenManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,14 @@ public function setToken(UnencryptedToken $token): void
*/
public function getRoles(): array
{
return $this->getToken()->claims()->get($this->rolesClaimName, []);
return $this->getClaim($this->rolesClaimName, []);
}

/**
* @inheritdoc
*/
public function getClaim(string $name, $default = null): mixed
{
return $this->getToken()->claims()->get($name, $default);
}
}
10 changes: 10 additions & 0 deletions src/exceptions/InvalidTokenmanagerComponent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace dmstr\tokenManager\exceptions;

class InvalidTokenManagerComponent extends \Exception
{
protected $message = 'Token manager is not instance of TokenManagerInterface';
}
10 changes: 10 additions & 0 deletions src/interfaces/TokenManagerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,14 @@ public function setToken(UnencryptedToken $token): void;
* @return array
*/
public function getRoles(): array;

/**
* List of permissions assigned to user via token
*
* @param string $name
* @param $default
*
* @return mixed
*/
public function getClaim(string $name, $default = null): mixed;
}
9 changes: 8 additions & 1 deletion src/rbac/TokenRoleRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
namespace dmstr\tokenManager\rbac;

use dmstr\tokenManager\components\TokenManager;
use dmstr\tokenManager\exceptions\InvalidTokenManagerComponent;
use dmstr\tokenManager\exceptions\LoadTokenException;
use dmstr\tokenManager\interfaces\TokenManagerInterface;
use yii\base\InvalidConfigException;
use yii\rbac\Rule;
use Yii;
Expand All @@ -16,13 +18,18 @@ class TokenRoleRule extends Rule
/**
* @inheritdoc
*
* @throws InvalidConfigException
* @throws InvalidConfigException|InvalidTokenManagerComponent
*/
public function execute($user, $item, $params)
{
try {
/** @var TokenManager $tokenManager */
$tokenManager = Yii::$app->get($this->tokenManager);
// check if token manager not is instance of TokenManagerInterface
if (!$tokenManager instanceof TokenManagerInterface) {
throw new InvalidTokenManagerComponent();
}

$roles = $tokenManager->getRoles();
} catch (LoadTokenException $exception) {
Yii::error($exception->getMessage());
Expand Down

0 comments on commit 88cb5fa

Please sign in to comment.