views:

114

answers:

2

I have a problem creating authentication part for my application.

Below is the simplified version of my controllers.

The idea is that the MY_controller checks if session with user data exists. If it doesn’t, then redirects to the index page where you have to log in.

MY_controller.php

class MY_Controller extends Controller {

function __construct()
{
parent::__construct();

$this->load->helper('url');
$this->load->library('session');

if($this->session->userdata('user') == FALSE) {
redirect('index');

} else {
redirect('search');
}

}

} 

order.php - main controller

class Orders extends MY_Controller {

function __construct()
{
parent::__construct();

$this->load->helper('url');
$this->load->library('session');
}

function index()
{
// Here would be the code that validates information input by user.
// If validation is successful, it creates user session.


$this->load->view('header.html', $data); // load header
$this->load->view('index_view', $data); // load body
$this->load->view('footer.html', $data); // load footer
}

function search()
{
//different page
} 

what is happening is that the browser is telling me that “The page isn’t redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete.”

It seems like the redirect() is being looped. I looked at a few other examples of user auth and they were build using similar technique.

+1  A: 

When a user is already logged in, it appears you want to redirect them to /search/. The redirect occurs, and the constructor is called again, which recognizes that the user is already logged in, so it redirects them to /search/... you get the idea.

I would start by separating your login logic into it's own controller that doesn't extend from MY_Controller.

Dolph
Yeah, I will try to separate it.
marcin_koss
A: 

Also, note that when not logged in your controller redirects to 'index'. If the Index controller is also based on My_Controller, then it will redirect back to itself (until the user logs in and then Dolph Mathews' answer comes true).

You need to provide a 'safe zone' with no checking/redirecting that provides users with a login form (and note that your login controller/method has to have open access too!)

I tend to pop a gateway method into My_Controller, which is called only by private controllers/methods as required (in the constructor of completely private controllers). I'm sure there must be a better way though, perhaps like a gateway function in your My_Controller (as yours is done) but that filters for the URI path (e.g. allows index; index/login; index/logout etc)

Kurucu
Well, I figured out how to do it already. I created a separate login controller which only does user authentication. In the construct of all the other controllers I put a simpel code to check if a session with user login is set. If not -> redirect to login controller. Works like a charm.
marcin_koss