Thursday, April 5, 2012

How to stop redirecting to login page

So, I have a login link in the corner of my homepage which I want people to click on to login... pretty simple. Problem is that I cannot seem to view my homepage as I am automatically redirected to the login page. This causes issues when you login since the login returns you to the initial page (the home page) which then transfers you back to the login etc. Inf loop time. So I cannot seem to figure out why it is automatically redirecting my homepage to the login page. Thanks.


app_controller:

    function beforeFilter() {
        $cookie = null;
       
        //debug($this->Auth);
       
        // Change the default field names for the username and password
        $this->Auth->fields = array('username' => 'username', 'password' => 'passwd');
       
        //Set application wide actions which do not require authentication
        //$this->Auth->allow(array('*'));
        $this->Auth->allow('/', 'login', 'logout', 'confirm');
       
        //$this->Auth->allow(array('add'));
       
        // this sets the Login Action
        $this->Auth->loginAction = '/users/login';

        // Where do we go after a successful login?
        $this->Auth->loginRedirect = '/';

        // Where do we go after a successful logout?
        $this->Auth->logoutRedirect = '/';

        // what type of authorization setup are we using
        $this->Auth->authorize = 'controller';

        //What is required to be a valid account?
        $this->Auth->userScope = array('User.confirmed' => '1', 'User.active' => '1');

        // What to say when the login was incorrect.
        $this->Auth->loginError = 'Sorry, login failed.  Either your username/password are incorrect or your account in not active.';
        $this->Auth->authError = 'The page you tried to access is restricted. You have been redirected to the page below.';       
   
        //Do we want to use our custom cookie login? If so this needs to be false.
        $this->Auth->autoRedirect = false;
 
        //If we are not logged in yet, check if there is a cookie to log in by
        if( !$this->__setLoggedUserValues() && ($cookie = $this->Cookie->read( $this->cookieName ) ) ){
                 $this->Auth->login($cookie);
            $this->__setLoggedUserValues();
        }
        else
        {
            //$this->redirect(array('controller' => 'users', 'action' => 'login'));;
        }
}


    function beforeRender() {
        #This will build the menu bar
        $this->__buildMenu();
       
        #If we have an authorized user logged then pass over an array of
        #controllers to which they have index action permission
        if($this->Auth->user()) {
            $controllerList = Configure::listObjects('controller');
            $permittedControllers = array();
            foreach($controllerList as $controllerItem) {
                if($controllerItem <> 'App') {
                    if($this->__permitted($controllerItem, 'index')) {
                        $permittedControllers[] = $controllerItem;
                    }
                }
            }
        }
        $this->set(compact('permittedControllers'));
       
    }



    function isAuthorized() {
        $result = $this->__permitted($this->name,$this->action);
        return $result;
    }


    function __permitted($controllerName,$actionName) {
        //Ensure checks are all made lower case
        $controllerName = low($controllerName);
        $actionName = low($actionName);
       
       
        //If permissions have not been cached to session...
        if(!$this->Session->check('Permissions')){
            //...then build permissions array and cache it
            $permissions = array();

            //everyone gets permission to logout
            $permissions[]='users:logout';

            //Import the User Model so we can build up the permission cache
            App::import('Model', 'User');
            $thisUser = new User;
            $thisUser->Behaviors->attach('Containable');
           
            //Now bring in the current users full record along with groups
            $thisUser->contain('Group');
            $thisGroups = $thisUser->find('first', array(
                'conditions'=>array('User.id'=>$this->Auth->user('id'))
            ));

            foreach($thisGroups['Group'] as $thisGroup) {
                $thisUser->contain('Permission');
                $thisPermissions = $thisUser->Group->find('first', array(
                    'conditions'=>array('Group.id'=>$thisGroup['id'])
                ));
               
                foreach($thisPermissions['Permission'] as $thisPermission) {
                    $permissions[]=$thisPermission['name'];
                }

            }
                //debug($permissions);
                //write the permissions array to session
                $permissions = array_unique($permissions);
                $this->Session->write('Permissions',$permissions);
               
            //}
        }else{
            //...they have been cached already, so retrieve them
            $permissions = $this->Session->read('Permissions');
        }
   
        //Now iterate through permissions for a positive match
        foreach($permissions as $permission) {
            if($permission == '*') {
                Configure::write('debug',2);
                return true;//Super Admin Bypass Found
            }
            if($permission == $controllerName.':*') {
                return true;//Controller Wide Bypass Found
            }
            if($permission == $controllerName.':'.$actionName) {
                return true;//Specific permission found
            }
        }
        return false;
    }


    function __setLoggedUserValues() {
        $user = $this->Auth->user();
        if( $user ) {
            $this->set('User', $user[$this->Auth->userModel]);
            $this->loggedUser = $user[$this->Auth->userModel][$this->Auth->fields['username']];
            if ($user[$this->Auth->userModel]['id'] == 1) {
                Configure::write('debug',2);
            }
           
            return TRUE;
        } else {
            $this->set('User', array());
            return FALSE;
        }
    }






And here is the login function in the user controller:






    function login() {
        //-- code inside this function will execute only when autoRedirect was set to false (i.e. in a beforeFilter).
       
        if ($this->Auth->user()) {
       
            //Write out the cookie if we are supposed to remember the user
            if (!empty($this->data) && $this->data['User']['remember_me']) {
                $cookie = array();
                $cookie['username'] = $this->data['User']['username'];
                $cookie['passwd'] = $this->data['User']['passwd'];
                $cookie['expire'] = strtotime($this->cookieTerm);
                $this->Cookie->write($this->cookieName, $cookie, true, $this->cookieTerm);
                $this->Session->setFlash('Cookie created. It will expire '.$this->Time->niceTime($cookie['expire']));
            }

            $this->redirect($this->Auth->redirect());
        }
       
        //Auto-login from cookie if user data is empty
        if (empty($this->data)) {
            $cookie = $this->Cookie->read($this->cookieName);
            if (!is_null($cookie)) {
                $this->Session->setFlash('Logged in from Cookie. It will expire '.$this->Time->niceTime($cookie['expire']));
                if ($this->Auth->login($cookie)) {
                    $this->__addDomainInfo();
                    //  Clear auth message, just in case we use it.
                    $this->Session->del('Message.auth');
                    $this->redirect($this->Auth->redirect());
                } else { // Delete invalid Cookie
                    $this->Cookie->del($this->cookieName);
                }
            }
        }
    }

--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
 
 
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: