0

If a user is not logged in I would like to override the existing Controller and call the auth/login one instead keeping the browser URI in tact. (Every user has to be logged in to use the site)

I have tried a pre controller hook, but its too early. The auth library has not been instantiated by this point. The post controller hook is too late as the target controller has been instantiated.

Editing the constructor of the library seems pointless also, as it has already been created.. So i am a little stuck..

Any ideas please? :)..

Thanks

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Lee
  • 5,816
  • 6
  • 45
  • 61

3 Answers3

4

I would override the default controller and extend in each controller. Create a new file: ./app/core/MY_Controller.php with the next code:

class Secure_Controller extends CI_Controller {

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

        /* replace this code with yours */
        if( !$this->session->userdata('logged_in') ) {
            redirect(base_url() . 'login', 'refresh'); // your login url
        }
    }
}

Then, use this code in each controller that you should be accessible by logged users

class Main extends Secure_Controller {
Juan Ramón
  • 615
  • 1
  • 5
  • 19
  • Good answer. This will show how you do it http://philsturgeon.co.uk/news/2010/02/CodeIgniter-Base-Classes-Keeping-it-DRY – Phil Sturgeon Sep 07 '11 at 16:10
  • Thanks for the response. I used this in conjunction with a method called _remap to act as a kind of proxy. Thanks again. – Lee Sep 27 '11 at 13:54
0

Have you considered just saving the URI to flashdata, redirecting the visitor to another controller (login page) and then just putting the referrer into a hidden form field? I'm doing the same thing with one of my sites using Codeigniter and it works fine. The only difference is that the URI is not intact during this process.

Al_
  • 196
  • 3
  • I had considered it thought im not sure "how" sure that is.. If a hacker prevented any redirects from taking place wont the controller just continue and complete.. Does a redirect stop the code igniter execution process? – Lee Aug 16 '11 at 16:03
0

Perhaps the answer to this question will be the same for you ? CodeIgniter only allow access to certain controllers when logged in

(If so, don't forget to replace the "function className()" by "function __construct()" and "parent::Controller();" by "parent::__construct();")

Community
  • 1
  • 1