How to hide website for unregistered users?


I am developing website with yii. This website will be accessible only for logged in users.

And the question is how to deny access to website for guests. There will be one or two controllers which actions will be available for unregistered users. It is possible to achive this using access control filter but I do not want to make it in each controller, I would like to find one place where I can handle this.


You can use access control filter in a controller class, and all your controllers extend that class.

I solved this in Controller.php (the default, extended CController)

Here is how:

First I coded the user login-logout stuff using UserIdentity.php, etc. Then I declare Controller->init(); From now on, every time init() runs, Yii::app()->user->id contains the id of the currently logged in user. Here, in the init() I always load the user and it’s related data from the database like this:

$this->userData = Users::model()->findByPk(Yii::app()->user->id);

Works fine. If $this->userData === null, there is no user logged in, otherwise $this->userData is the ActiveRecord with current user’s data.

In the main controller, there is an action actionRestricted. This modifies the default layout to a special one, possibly the css also.

Here’s how I implemented:

  1. (note that siteSettings is a custom class, it doesn’t has much sense here). This code fragment should be included in Controller->init()

	// Read the site settings

	$this->siteSettings = new AppSiteSettings;

	// site access

	if (!$this->siteSettings->get('allow_access')) {

		if (Yii::app()->user->isGuest) {

			if (isset($_GET['backdoor'])) //the secret access






	// Load the user

	$this->userData = AR_Users::model()->findByPk(Yii::app()->user->id);

	if ($this->userData !== null) {

		//update last_active

		$this->userData->last_active = time();


		// log out regular users if login isn't allowed

		if ($this->userData->admin_level < EDITOR)

			if (!$this->siteSettings->get('allow_access')) {





When allow_access == false, regardless of the url, users will see always the restricted page. If the url contains ?backdoor at the end, the login page will appear. For private-like pages you may want to redirect always to login page.

The restricted action is very simple:

	public function actionRestricted() {




The above solution may be not the most professional but works fine…