PHP code example of clement / yii-rest-rbac

1. Go to this page and download the library: Download clement/yii-rest-rbac library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

clement / yii-rest-rbac example snippets


'modules' => [
    "admin" => [
        "class" => "clement\\rest\Module",
        'layout' => 'left-menu',//yii2-admin的导航菜单
    ],
],
"aliases" => [
        "@clement/rest" => "@vendor/clement/yii-rest-rbac",
    ],
'components' => [
    'jwt' => [
        'class' => 'clement\rest\auth\Jwt',
        'key' => 'xxx', // 你自己的想使用的key,注意保密
            ],
    'user' => [
        'identityClass' =>'xxxx\User',//自己的User model
        'enableAutoLogin' => true,
        'enableSession' =>false,
        'loginUrl' => null,   // api ++
    ],
    "authManager" => [
        "class" => 'clement\\rest\components\DbManager',
        'defaultRoles' => ['游客'], //添加此行代码,指定默认规则为 '未登录用户'
    ],
    /**
     * 根据需要设置有无,具体的参照 yii-rest-rbac原理文档
     *
     */
     'as access' => [
         'class' => 'clement\\rest\components\AccessControl',
         'allowActions' => [
             '*',//根据自己的情况设置
         ]


    const GET_ACCESS_TOKEN = 'generate_access_token';

    public function init()
    {
        parent::init();
        $this->on(self::GET_ACCESS_TOKEN, [$this, 'onGenerateAccessToken']);
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            $this->trigger(self::GET_ACCESS_TOKEN);
            return $this->_user;
        } else {
            return null;
        }
    }

    /**
    * 登录校验成功后,为用户生成新的token
    * 如果token失效,则重新生成token
    */
    public function onGenerateAccessToken()
    {
        if (!User::isAccessTokenValid($this->_user->access_token)) {
            $this->_user->generateAccessToken();
            $this->_user->save(false);
        }
    }

use clement\rest\auth\APIAuth;
use clement\rest\components\AccessControl;
class BaseController extends ActiveController
{
    /**
     * 设置返回头部的allow部分
     * @param array $collection allow的方法集合
     */
    public function ResponseOptions($collection = [])
    {
        $collectionOptions = ['GET', 'POST', 'HEAD', 'OPTIONS'];
        if(!empty($collection)){
            $collectionOptions = $collection;
        }
        Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $collectionOptions));

    }
    public function behaviors()
    {
        $behaviors = parent::behaviors();        

        // add CORS filter
        // 处理跨域请求,注意设置生产版本的 Origin
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['*'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 86400,
            ]
        ];
        // 设置认证的方式
        $behaviors['authenticator'] = [
           'class' => APIAuth::className(),
           'except' => ['OPTIONS'],
        ];
        // 设置权限验证方式
        $behaviors['access'] = [
                      'class' => AccessControl::className(),
                  ];
        return $behaviors;
    }
}

    /**
     *
     * 使用jwt token 验证,并设置login signup不需要验证
     */

    public function behaviors()
    {
        $behaviors =  ArrayHelper::merge(
            parent::behaviors(), [
                'authenticator' => [
                    'optional' => ['login','signup']
                ],

            ]
        );
        return $behaviors;
    }


// 命名空间注意修改
namespace xxxx\controllers;

use Yii;
use  yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use clement\rest\components\Helper;
use clement\rest\components\MenuHelper;
use yii\web\User; // 注意不要使用其他的
use \base\BaseController;
class UserInfoController extends BaseController
{
    public $modelClass = 'xxxx\User'; // 上面修改的User,即认证的User类
    protected function verbs()
    {
        return  ArrayHelper::merge(
            parent::verbs(),
            [

                //关于options的严谨方法,需对options 处理
                'info' => ['GET','OPTIONS'],

            ]
        );
    }
    public function actionInfo(){
        $request = \Yii::$app->request;
        if($request->getIsOptions()){
            return $this->ResponseOptions( $this->verbs()['info']);
        }
        $user = Yii::$app->getUser();
        $userId = $user instanceof User ? $user->getId() : $user;
        $res['userInfo']['menus'] = MenuHelper::getAssignedMenu($userId);
        $res['userInfo']['resources'] = Helper::getPermissionByUser($userId);

        return $res;

    }
}