PostIgniter在post控制器钩子中重定向循环

时间:2013-04-12 19:21:08

标签: php codeigniter redirect oauth hook

这是我的控制器:

<?php
  class Check_Login {
    var $CI;
    var $class;
    var $allowed_klasses = array('user', 'testing', 'home', 'lesson_assets', 's3_handler', 'ajax', 'api', 'pages', 'invite', 'mail', 'partner', 'renew', 'store', 'news', 'breathe','popup','subscription', 'lessons');

    public function __construct() {
      $this->CI =& get_instance();

      if(!isset($this->CI->session)) {
        $this->CI->load->library('session');
      }

      if(!nash_logged_in()) {
        $this->CI->session->sess_destroy();
        redirect('/');
      }

      $this->_set_accessed_klass();
    }

    public function auth_check() {
      if($this->CI->session->userdata('id')) {
        $query = $CI->db->query("SELECT authentication_token FROM users WHERE id = ".$this->CI->session->userdata('id')." AND authentication_token IS NOT NULL");
        if(!in_array($this->class, $this->allowed_klasses)) {
          if($query->num_rows() == 0){
            redirect('/user/logout');
          }
        }else{
          return;
        }
      }else{
        return;
      }
    }

    private function _set_accessed_klass() {
      $this->class = $this->CI->router->fetch_class();
    }
  }

我所指的行也是:

if(!nash_logged_in()) {
        $this->CI->session->sess_destroy();
        redirect('/');
      }

基本上,该应用使用nash_logged_in()方法检查我们的OAuth系统,以查看用户是否真正“登录”。发生这种情况时会发生重定向循环。

nash_logged_in方法只返回TRUE或FALSE的JSON密钥。有什么理由我会遇到这个重定向循环吗?

nash_logged_in方法:

if(!function_exists('nash_logged_in')) {
  function nash_logged_in(){
    $url = NASH_OAUTH_URL . '/api/v1/loggedin.json';
    $json = file_get_contents($url);
    $data = json_decode($json);
    return $data->loggedin;
  }
}

2 个答案:

答案 0 :(得分:0)

如果nash_logged_in()没有返回布尔值false或整数0或null,则该语句将被评估为true,因此您的重定向。

在这里发布nash_logged_in(),看看那里发生了什么。

答案 1 :(得分:0)

您不需要为此方法使用钩子

  

帖子控制器挂钩

您可以扩展CI_Controller并在需要进行身份验证的子类的__constructor中运行身份验证库。

你当前的控制器有点凌乱,对我来说它看起来像一个库,而不是一个控制器,如果你在你的控制器中完成这一切,你不需要重新实例化超级对象!

但是,我的建议是将所有内容移到库中(因为有许多依赖它的控制器/类)。

您的代码中的某些元素对我没有意义,可能是因为我无法从您发布的代码中看到更大的图片。

这可能会为你提供一些食物,不管这是我接近它的方式。

<强>应用/库/ authentication.php

class Authentication
{

    protected $allowedClasses = array ( ) ;
    protected $userId         = null ;
    protected $nashURL ;

    const NASH_OAUTH_URL = '' ;

    public function __construct ()
    {
        $this->nashURL = static::NASH_OAUTH_URL . '/api/v1/loggedin.json' ;

        //check for a user id in session
        //this may not be set yet!!
        $this->userId = (isset ( $this->session->userdata ( 'id' ) ))
            ? $this->session->userdata ( 'id' )
            : null ;

        /** Load dependancies * */
        $this->load->model ( 'Authentication_Model' ) ;
        $this->load->library ( 'Session' ) ;

    }

    /**
     * nashCheckLoginViaCurl
     * @return boolean
     */
    protected function nashCheckLoginViaCurl ()
    {
        if ( function_exists ( 'curl_init' ) )
        {
            return show_error ( "Enabled CURL please!" , 500 ) ;
        }

        $curl = curl_init () ;
        curl_setopt_array ( $curl ,
                            array (
            CURLOPT_URL => $this->nashURL ,
            /** CHECK CURL DOCS FOR FULL LIST OF OPTIONS - FILL THE REST YOURSELF * */
        ) ) ;

        if ( curl_errno ( $curl ) )
        {
            return false ;
        }

        $info     = curl_getinfo ( $curl ) ;
        $responce = curl_exec ( $curl ) ;
        curl_close ( $curl ) ;

        //Check and make sure responce is a BOOLEAN and not a STRING
        //we will typecast below just incase
        $responce = json_decode ( $responce ) ;

        return ($info[ 'http_code' ] == '200' and ( bool ) $responce->loggedin === true)
            ? true
            : false ;

    }

    /**
     * verifyAccess
     * @param CI_Controller $class (Dependancy Injection)
     * @return Mixed
     *
     */
    public function verifyAccess ( CI_Controller $class )
    {
        //Is there a userId in the session
        //ie: is user logged In
        if ( is_null ( $this->userId ) or ! ( int ) $this->userId )
        {
            return false ;
        }

        //grab list of allowed classes
        $this->allowedClasses = $this->listAllowedClasses () ;

        //check to see if $class is in list of allowed classes
        if ( ! in_array ( $class , $this->allowedClasses ) )
        {
            return false ;
        }
        //check to see if nashCheckLoginViaCurl returned true
        if ( ! $this->nashCheckLoginViaCurl () )
        {
            $this->logout () ;
            return false ;
        }

        //return boolean or $authentication_token based on DB query
        return $this->Authentication_Model->isUserIdRegistered ( $this->userId ) ;

    }

    /**
     * logout
     * @return void
     */
    public function logout ()
    {
        $this->session->unset_userdata ( array ( 'id' => 0 ) ) ;
        $this->session->sess_destroy () ;
        $this->session->sess_start () ;
        return redirect ( '/' ) ;

    }

    /**
     * listAllowedClasses
     * MAYBE USE A CONFIG FILE FOR THIS?
     * @return array
     */
    protected function listAllowedClasses ()
    {
        return array (
            'user' , 'testing' , 'home' , 'lesson_assets' , 's3_handler' , 'ajax' ,
            'api' ,
            'pages' , 'invite' , 'mail' , 'partner' , 'renew' , 'store' , 'news' ,
            'breathe' ,
            'popup' , 'subscription' , 'lessons'
            ) ;

    }

    /**
     * Load CI Super object object
     *
     * @param string $object
     * @return object
     */
    public function __get ( $object )
    {
        return get_instance ()->$object ;

    }

}

<强>应用/模型/ authentication_model.php

class Authentication_Model extends CI_Model
{

    public function isUserIdRegistered ( $uid )
    {
        $this->db->select ( 'authentication_token' )
            ->from ( 'users' )
            ->where ( 'id' , $uid )
            ->where ( 'authentication_token IS NOT' , 'NULL' )
            ->limit ( 1 ) ;

        $query = $this->db->get () ;

        return ( $query->num_rows () > 0 )
            ? $query->result ()
            : FALSE ;

    }

}

<强>应用/核心/ MY_Controller.php

class MY_Controller extends CI_Controller
{

    protected $authentication_token ;

    public function __construct ()
    {
        parent::__construct () ;
        $this->load->library ( 'authentication' ) ;

    }

    protected function _verifyAccess ( $class )
    {
        $authorized = $this->authentication->verifyAccess ( strtolower ( $class ) ) ;

        if ( ! $authorized )
        {
            //kill further script execution by returning
            //redirect url
            return redirect ( 'login' ) ;
        }
        else
        {
            $this->authentication_token = $authorized ;
        }
        return ; //return control back to the controller who called me

    }

}

* 测试不同的控制器 - 模拟后控制器挂钩*

class Some_Controller extends MY_Controller
{

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

        $this->_verifyAccess ( __CLASS__ ) ;

    }

}

-

class Another_Controller extends MY_Controller
{

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

        $this->_verifyAccess ( __CLASS__ ) ;

    }

}