Yii2 filter for authclient

In a webapp I’m working on the user is required to login with facebook for certain actions only. So I came up with this code. It’s designed to work with yii2-authclient.

You can change the authclient client for the one or ones you need.

Any ideas to improve the code? Please feel free to share them. Thanks!

ClientAccessRule.php (this is the filter itself)


<?php


namespace app\filters;


use \yii;

use \yii\filters\AccessRule;


/**

 * This class represents a client access rule defined by the [[AccessControl]] action filter

 *

 * @author Nicolas Suarez <nicolas.p.suarez@gmail.com>

 * @since 2.0

 */

class ClientAccessRule extends AccessRule {


	/**

	 * @var array the default configuration of the client.

	 * The client can be any of the specified by yii2-authclient.

	 */

	public $clientConfig;


	/**

	 * Checks whether the Web user is allowed to perform the specified action.

	 * @param Action $action the action to be performed

	 * @param User $user the user object

	 * @param Request $request

	 * @return boolean|null true if the user is allowed, false if the user is denied, null if the rule does not apply to the user

	 */

	public function allows($action, $user, $request) {

		if ($this->matchClient()) {

			return parent::allows($action, $user, $request);

		} else {

                        Yii::$app->user->setReturnUrl(Yii::$app->request->url);

			return null;

		}

	}


	/**

	 * @return boolean whether the user has an active client session

	 */

	public function matchClient() {

		$client = Yii::createObject($this->clientConfig);

		try {

			$client->getUserAttributes();

			return true;

		} catch (yii\base\Exception $e) {

			return false;

		}

	}


}

Example of usage inside a controller:


public function behaviors() {

		return [

			'access' => [

				'class' => AccessControl::className(),

				'rules' => [

					[

						'allow' => true,

						'roles' => ['@'],

					],

				],

			],

			'authclientAccess' => [

				'class' => AccessControl::className(),

				'only' => ['action'],

				'ruleConfig' => ['class' => 'app\filters\ClientAccessRule'],

				'denyCallback' => function () {

			             return $this->redirect(['/site/authclient-login']);

		                 },

				'rules' => [

					[

						'allow' => true,

						'clientConfig' => ['class' => 'yii\authclient\clients\Facebook'],

					],

				],

			],

		];

	}