Yii2 extension implementing authorization chain
, (*1)
What is it for?
For applications with hierarhical access roles system., (*2)
Any examples? It's not clear
You have an application - API. You have two roles here:
- admin - they can watch statistics and edit clients;
- client - they can see own statistics and set settings., (*3)
You need to allow admins to authorize as clients without knowing their passwords
just from admin interface. And you need to allow admins to get back to their own
privilegis/account without re-logining. And of course you need to log all changes
made by admins as clients properly, so you always knew who actually made some changes., (*4)
Install
``` bash
$ composer require daydiff/yii2-auth-chain, (*5)
## Usage
Register application component:
``` php
'components' => [
'authChain' => [
'class' => 'Daydiff\AuthChain\Service'
],
]
You need to declare a member class implementing \Daydiff\AuthChain\MemberInterface, (*6)
//Member.php
namespace app\foo\bar;
class Member implements \Daydiff\AuthChain\MemberInterface
{
private $id;
private $login;
/**
* @inheritdoc
*/
function getId()
{
return $this->id;
}
/**
* @inheritdoc
*/
function getLogin()
{
return $this->login;
}
/**
* @inheritdoc
*/
function setId($id)
{
$this->id = $id;
return $this;
}
/**
* @inheritdoc
*/
function setLogin($login)
{
$this->login = $login;
return $this;
}
}
In your action used to authorize as client:, (*7)
``` php
public function actionAuthAs($id)
{
$user = \Yii::$app->getIdentity()->getUser();
$member = new app\foo\bar\Member();
$member->setId($user->id)
->setLogin($user->login);
\Yii::$app->authChain->push($member);, (*8)
//and then you do authorization work
}, (*9)
When you need to know who user actually is:
``` php
$member = \Yii::$app->authChain->last();
$realUserId = $member->getId();