• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Best Way to Redirect If User is Not Login?

[eluser]Morgan Cheng[/eluser]
I'd like to have all controller to redirect to my "login/index" controller/action if visitor is not login. I suppose there 2 ways to do it.

1) All functions in all controllers starts with a piece of code to check whether current user has login session data. If not, invoke
2) Have all controller (except login controller) inherits from MY_Controller. In the My_Controller constructor, check whether user is login and do redirect accordingly.

Both solutions look obtrusive since it involves changes to all controllers.

This looks a common requirement. Is there any best practice for that?


There's also the way that I do it, which is if logged in show view #1, if not show view #2, which is the login form.

[eluser]Morgan Cheng[/eluser]
@skunkbad, do you mean you have controller function to load different view based on login status?
But, that would have URL bar show something like "category/goods" while the web page is login page. Will this bring confusion to user?

I believe the user would understand that to access category/goods requires a login...

Do you have a model to handle your login/session stuff? If you do, you could just make a method in that model to redirect if not logged in.
The method could be called require_login, or something similar.

You autoload the model. In each controller that needs the user to be logged-in, you write $this->my_user_status_model->require_login();
And you're done. You will need only that one line in each controller that needs to be logged in. And it's flexible: if a controller does NOT
need to be logged in (like an information page, 'how to sign up', or whatever, you don't call that line.

function change_password()
        // Check if user logged in or not
        if ($this->und_auth->is_logged_in())
                echo "You will change your password here";
            // Redirect to login page

Erkana auth seems to handle things neatly.

function index() {
    //Requires login

You could extend all of your controllers of a MY_Controller. Then just put your validation checks in the constructor of your parent class. Every constructor would automatically have to go through the validation checks to be displayed. It also means that any modifications only require changing one function. It can be a pain to go through and hang all of your controllers of a parent class, but once its done, they shouldn't need any modification.
(I use this method on ticket management app im developing)

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.