Restricting Site Access with Kohana Auth Module

Posted on

Overview

Have you ever needed to block off access to any of your pages… Like the administration panel of a website? Today I’m going to show you the simple code to do this. We are going to need to enable a module but that’s really easy.

What do we need?

First of all, ask yourself what you want to do. So, I want to restrict access to my admin pages. Ok, now that we know what we want to do… How do we do it? First we have to check if the user is logged in. In order to check if they are logged in, we need to be able to work with the Kohana 3 Auth Module.
Open up the application/bootstrap.php file and on about line 71 you are going un-comment that line

70
71
72
Kohana::modules(array(
	   'auth'       => MODPATH.'auth',       // Basic authentication
	// 'cache'      => MODPATH.'cache',      // Caching with multiple backends

This simply makes these classes available for use.

How to do it

Lets say we have a simple page or even a functionality that we don’t want a guest (a user who is not logged in) to see/use. First I will show you how to check if the user is logged in. The code below is pulled directly from one of the projects I’m working on.
Basically what is happening here is as follows starting on line 5. We instantiate the Auth module and call the method logged_in(). This basically checks to see if the user has an open session by checking for a session key.
Based on weather or not the user is logged in, we will take an action – so in this case if the user is NOT logged in, we will let the user stay on this page and use the register form. If they were logged in, this page would just redirect to their user account dashboard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function action_register(){
		$this->template = "template/layouts/2-col";
		parent::before();
 
		if(Auth::instance()->logged_in()){
			Request::instance()->redirect("account/dashboard");
		}
 
		if($_POST){
			Model::factory("user");
			$post = Validate::factory($_POST)
					->filter(true, "trim")
					//email rules
					->rule('email', 'email')
					->rule('email', 'not_empty')
					//password rules
					->rule('password', 'not_empty');
 
			if($post->check()){
				Request::instance()->redirect("account/dashboard");
			}
 
			$errors = $post->errors("register/form");
		}
 
		$this->template->title = "My Page Title";
		$this->template->firstCols = array(View::factory("template/blocks/who-we-are"));
		$this->template->secondCols = array(View::factory("template/account/register")->bind("post", $post)->bind("errors", $errors));
	}

It’s actually pretty simple to restrict access isn’t it?

In this next part, I’ll show you how to restrict access based on specific privileges granted to the user. The code below is almost identical to the snippet above accept for a key difference – we are asking if the user is logged in as an admin. If so, then let them see the page, else, the get redirected to an admin log in screen.

1
2
3
4
5
6
7
8
9
10
function action_register(){
		$this->template = "template/layouts/2-col";
		parent::before();
 
		if(Auth::instance()->logged_in("admin")){
			Request::instance()->redirect("admin/dashboard");
		}else{
			Request::instance()->redirect("admin/login"); 
                }
	}

Conclusion

We went over what module we needed to work with user authentication and how to check if a user is logged in and what parts of the site they could access. Of course this is a very basic tutorial but really this is all there is to it. I didn’t show you how to register or log in the the user but we will save that for another day. I hope you find this useful. Thanks

  • http://www.google.com/profiles/Zetastate Corey

    Thanks man. That was quick. I am starting to get the hang of this.

    By the way, I think your feed is pooched. I didn’t get an update that you had posted, I just checked back to get the rewrite for the .htaccess from the first post and noticed you had another one up.

  • http://www.google.com/profiles/Zetastate Corey

    Ok, quick MVC general question. I could conceivably make one controller for all my views in a website. What is the convention? Is there a 1 to 1 relationship with views and controllers (other than headers and footers, etc)?

    I am trying to wrap my mind around the presentation and logic remove. When I started writing HTML it was in Notepad and it was all done in tables. On the surface with MVC it almost seems like more work to make a controller and a view than it is to just make a page. I have a feeling that something will click (like it usually does) and I will get it, but I feel like I need a MVC for dummies book.

  • http://zackperdue.com Zack Perdue

    Ok, i think i can help you. First of all, you dont absolutely need a model. but we will come back to that.
    You must have at least a controller. The controllers are in essence – i guess you could call them directories and sub pages. The name of the class would be a directory and any actions (methods) inside the controller would be child pages of that “directory”.
    The controllers basically organize what happens for each page – like form posts and which templates to use.
    Ex. domain.com/user/login
    the “user” part is actually the name of the controller and inside that controller is the action “login” so you could have all your user actions in the user controller… (login, register, logout, forgot password, dashboard) anything along those lines. The login action would call the “view” that holds the form for any login actions (email, password fields). Now for the model part.

    The model controls more functions and actions as in controlling how data is handled. You would use a model to communicate with the database. A user model can have corresponding actions in a controller as user login. And in your controller you would actually use the functions inside your user model to do the actual login bit.

    I hope this sheds a little light on the MVC model for you. 🙂

  • http://zackperdue.com Zack Perdue

    Hmm, you are just not getting updates from my feed? Make sure you are following my feedburner feed.