Skip to content

Instantly share code, notes, and snippets.

@chabibnr
Created March 5, 2019 10:18
Show Gist options
  • Save chabibnr/8bb0c3131899e32e0cf8cd76888fa121 to your computer and use it in GitHub Desktop.
Save chabibnr/8bb0c3131899e32e0cf8cd76888fa121 to your computer and use it in GitHub Desktop.
Simple Rest
<?php
/**
* Class ApiController
*
* File Location : application/core/ApiController.php
*
* @property CI_Input $input
* @property CI_Output $output
*/
class ApiController extends CI_Controller {
protected $identity;
const TOKEN_KEY = 'token';
const TOKEN_PREFIX = 'token ';
public function __construct() {
parent::__construct();
}
/**
* @return bool
*/
public function is_guest(){
return $this->get_identity() === null;
}
public function get_identity(){
if($this->identity === null && (($token = $this->get_token()) != null)){
/*
* todo: query builder get user by token
* example :
* $row = $this->db->get_where('user',array(
* 'active' => 0,
* 'token' => $token
* ));
* if($row->num_rows() > 0){
* $this->identity = $row->row();
* }
*/
/*
* todo: delete ini hanya contoh hapus kalau tidak perlu
*/
if($token === '1234') {
$this->identity = (object)array(
'user_id' => 1,
'name' => 'user'
);
}
}
return $this->identity;
}
/**
* @return mixed|null
*/
protected function get_token(){
$headers = $this->input->request_headers();
$token = isset($headers[static::TOKEN_KEY]) ? $headers[static::TOKEN_KEY] : null;
return !is_null($token) && !empty($token) ? str_replace(static::TOKEN_PREFIX,'', $token) : null;
}
protected function response($response, $code = 200){
$this->output
->set_status_header($code)
->set_content_type('application/json')
->set_output(json_encode($response));
}
protected function unauthorized(){
return $this->response(array(
'message' => 'Authorize failed'
), 401);
}
}
<?php
/*
* File Location : application/controllers/Main.php
*/
require_once APPPATH.'core/ApiController.php';
class Main extends ApiController {
public function __construct() {
parent::__construct();
$this->get_identity();
}
public function tes(){
if($this->is_guest()) {
$this->unauthorized();
}else{
$this->response(array(
'status' => 'success',
'data' => $this->get_identity()
));
}
}
}
GET http://localhost/ci/index.php/main/tes
Accept: */*
Cache-Control: no-cache
token: token 1234
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment