1
votes

I am using Codeigniter rest api.

What I know is that $this->set_response terminates execution and returns the result with status code.

But when I try to do this in the constructor, it ignores it and continues to execute the target method.

My Controller

class Posts extends REST_Controller
{
    public $user_id;
    public $ret_arr = [
        'status' => FALSE,
        'message' => ''
    ];
    function __construct()
    {
        // Construct the parent class
        parent::__construct();


        $this->load->model('api/User_model');
        $this->load->model('api/Entity_model');
        $this->load->model('api/Post_model');
        $token = $this->input->get_request_header('token', TRUE);

        if($token!=NULL) {
            $this->get_user_id($token);
        }
        else
        {
            $this->ret_arr['status'] = FALSE;
            $this->ret_arr['message'] = 'Token Not Valid';
            $this->set_response($this->ret_arr, REST_Controller::HTTP_UNAUTHORIZED);

        }

    }
public function get_user_id($token)
    {

        $this->user_id = $this->User_model->check_token($token);

        if ($this->user_id == FALSE||$token==''||$token===null) {
            $this->ret_arr['status'] = FALSE;
            $this->ret_arr['message'] = 'Token Not Valid';

            $this->set_response($this->ret_arr, REST_Controller::HTTP_UNAUTHORIZED);

        }

    }

    public function addpost_post()
    {

        //$post_string = $this->request->body[0];
        //$post = json_decode($post_string, true);
        $post=$this->input->post();
        if (isset($post['post_type']) && $post['post_type'] != '') {
            $text = $this->input->post('text');
            $type = $post['post_type'];


            if ($type == 'text') {
                $this->add_post_text($text);
            } elseif ($type == 'url') {

            } elseif ($type == 'image') {

            } elseif ($type == 'video') {

            }
        } else {
            $this->ret_arr['status'] = FALSE;
            $this->ret_arr['message'] = 'Missing Post Type';
            $this->set_response($this->ret_arr, REST_Controller::HTTP_UNPROCESSABLE_ENTITY);
        }
    }
}  

When I request this URL with no token in header and no data sent it returns

localhost:8080/myProject/api/Posts/addpost

{"status":false,"message":"Missing Post Type"} and status 422

but it must return

{"status":false,"message":"Token Not Valid"} and status 401

UPDATE (SOLVED)

I solved it by using $this->response() instead of $this->set_response()

1

1 Answers

0
votes

Please change our code like describe below.

From

$post=$this->input->post();

TO

$post=$this->post();