rest api didn't terminate with set_response
i am uthis rest api. what i know the $this->set_response terminate execution and return the result with status code . but when i try to do this in constructor it's ignore it and continue 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=$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 return
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
Don't do token checking in your controller. Do it in REST_Controller and make it globally for all controllers. You don't want to repeat your self in every controller's contstruct. All REST_Controller checking and settings are done until it loads your construct method.
Read REST_Controller's code it's really simple and written well and you will figured how to implement your token thing.
@farukgaric i need the token in specific controllers .
i solved it by using $this->response() instead of $this->set_response()