简体   繁体   English

后控制器挂钩中的CodeIgniter重定向循环

[英]CodeIgniter redirect loop in post controller hook

Here is my Controller: 这是我的控制器:

<?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();
    }
  }

The lines that I am referring too are: 我也指的是:

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

Essentially, the app uses the nash_logged_in() method to check against our OAuth system to see if the user is truly "logged in". 本质上,该应用程序使用nash_logged_in()方法检查我们的OAuth系统,以查看用户是否真正“登录”。 When this happens a redirect loop happens. 发生这种情况时,将发生重定向循环。

The nash_logged_in method simply returns a JSON key of either TRUE or FALSE. nash_logged_in方法仅返回TRUE或FALSE的JSON密钥。 Any reason why I would be running into this redirect loop? 我为什么会遇到此重定向循环的任何原因?

nash_logged_in method: 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;
  }
}

If nash_logged_in() does not return a boolean false or integer 0 or null, then the statement is evaluated as true therefore your redirect. 如果nash_logged_in()没有返回布尔值false或整数0或null,则该语句被评估为true,因此您将进行重定向。

Post nash_logged_in() here to see what's going on there. 在此处发布nash_logged_in()以查看发生了什么。

You wont need to use hooks for this method 您不需要为此使用钩子

post controller hook 控制器后挂钩

You could just extend CI_Controller and run the Authentication library in the __constructor of the child classes that need to be authenticated. 您可以扩展CI_Controller并在需要认证的子类的__constructor中运行Authentication库。

You current controller is a little messy and it looks like a library to me, not a controller, you don't need to re-instantiate the super object if your doing it all in your controller! 您当前的控制器有点混乱,在我看来,它就像一个库,而不是控制器,如果您在控制器中全部完成操作,则无需重新实例化超级对象!

However, my suggestion is to move everything to a library(as there are a number of controllers/classes that depend on it). 但是,我的建议是将所有内容都移到库中(因为有许多依赖于它的控制器/类)。

Some elements of your code don't make sense to me, possibly because I can't see the bigger picture from the code you have posted. 您的代码中的某些元素对我来说没有意义,可能是因为我看不到您发布的代码中的大图。

This might give you some food for though(or not) regardless this is how I would approach it. 无论这是(还是没有),这可能会给您一些食物,无论我如何处理。

application/libraries/authentication.php 应用程序/库/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 ;

    }

}

application/models/authentication_model.php 应用程序/模型/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 ;

    }

}

application/core/MY_Controller.php application / core / 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

    }

}

* Testing Different Controllers - simulate post controller hook * * 测试不同的控制器-模拟后控制器挂钩*

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__ ) ;

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM