Question

I'm running Kohana 3, and having a hard time understanding the Auth module, or even if it's what I need. Basically I want to create a basic user profile site with basic username/password protection.

How do I take my existing controllers...

class Controller_Profile extends Controller
{
    function action_index( $user_id )
    {
        // User should already be authenticated by here I think
    }
}

...and use them with some sort of authentication system

Was it helpful?

Solution

For Kohana 3 you'll want to do your check in before and not __construct like JIStone suggests.

public function before()
{
    parent::before();

    // This automatically checks for an auto login cookie (thanks kemo).
    if ( ! Auth::instance()->logged_in())
    {
        // Redirect to a login page (or somewhere else).
        $this->request->redirect('');
    }
}

Simple enough to understand. You can put this into a controller and have all the controllers that need authentication to extend that.

OTHER TIPS

If you will be requiring a user to be registered for all pages on the controller you can put a check in your __construct() statement:

function __construct()
{
    //Check roles for Access!!!!
    parent::__construct();
    $this->load_user();
    if( ! $this->is_registered )
    {
        if(request::is_ajax())
            die('This ajax call cannot be completed due to permission issues.');
        // this will redirect from the login page back to this page
        $this->session->set('requested_url', url::current());
        url::redirect('user/login');
    }
}

This is the code we use, but it is Kohana 2, not 3, so you will need to adjust a bit for your purposes.

I have provided a link to a short walkthrough for the installation and basic usage of the Auth Module in Kohana 3

Once you have your Auth process working, you can protect certain controllers by checking for a logged in user and proper authentication role in your before() method, or create a base controller for all your controllers that will need this check. If the user is not logged in, redirect them to the login page, if they do not have the proper access level (or role), then you can show them an "Access Denied" page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top