Rest Web Service Codeigniter Bagian Keempat (API KEY)

Setelah kita membuat database untuk menyimpan data hasil monitoring maupun untuk menyimpan perintah untuk dieksekusi perangkat keras yang terhubung. Sekarang yang kita butuhkan adalah bagaimana menentukan hardware yang bisa mengirim data monitoring dan yang tidak. Untuk itu dibutuhkan API KEY untuk mendeteksi hardware yang terhubung ke aplikasi kita.

Pertama-tama kita harus buat tabel “key” untuk menyimpan API KEY dan tabel “logs” untuk menyimpan logs.

CREATE TABLE `keys` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `key` varchar(40) NOT NULL,
  `level` int(2) NOT NULL,
  `ignore_limits` int(1) NOT NULL DEFAULT '0',
  `is_private_key` int(1) NOT NULL DEFAULT '0',
  `ip_addresses` text,
  `date_created` int(11) NOT NULL
);
CREATE TABLE `logs` (
  `id` int(11) NOT NULL,
  `uri` varchar(255) NOT NULL,
  `method` varchar(6) NOT NULL,
  `params` text,
  `api_key` varchar(40) NOT NULL,
  `ip_address` varchar(45) NOT NULL,
  `time` int(11) NOT NULL,
  `rtime` float DEFAULT NULL,
  `authorized` varchar(1) NOT NULL,
  `response_code` smallint(3) DEFAULT '0'
);

Setelah kita tambahkan table di atas, jangan lupa mengubah settingan pada “config/rest.php”.

<?php

$config['allow_auth_and_keys'] = TRUE;

Tabel dan config sudah, selanjutnya kita buat model untuk tabel “key”.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Model_key extends CI_Model{

    function create($id,$key){
        $data = array('user_id' => $id,
        'key'=>$key,
        'level'=>2,//isi terserah ynag penting angka karena tipe data int
        'date_created'=>date('Ymd'));
        $query = $this->db->insert('keys', $data);
        return $query;
    }
    function verifyCreate($id,$key){
        $this->db->where('user_id', $id);
        $this->db->where('key', $key);
        $query = $this->db->get('keys');
        return $query;
    }
    function getByUser($user){
        $this->db->where('user_id', $user);
        $this->db->limit('1');
        $query = $this->db->get('keys');
        return $query;
    }
}

Karena kita sudah menambahkan keamanan berupa api key, maka kita harus mengedit tabel-tabel yang telah kita buat sebelumnya, yaitu tabel monitor_client dan unit_client menjadi seperti berikut :

CREATE TABLE `unit_client` (
  `id_unit` int(11) NOT NULL,
  `unit` varchar(16) DEFAULT NULL,
  `api_key` varchar(40) NOT NULL,
  `status` int(11) NOT NULL,
  `unit_create` datetime DEFAULT NULL,
  `unit_update` datetime DEFAULT NULL
);
CREATE TABLE `monitor_client` (
  `id_monitor` int(11) NOT NULL,
  `unit_id` int(11) DEFAULT NULL,
  `output` varchar(12) DEFAULT NULL,
  `api_key` varchar(40) NOT NULL,
  `monitor_created` datetime DEFAULT NULL
);

Kita tambah beberapa function di model_unit.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Model_unit extends CI_Model{

    public function create($unit, $user,$api,$status){
        $data = array('unit'=>$unit,
        'user_id'=>$user,
        'api_key'=>$api,
        'status'=>$status,
        'unit_create'=>date('Y-m-d H-i-s'),
        'unit_update'=>date('Y-m-d H-i-s'));
        $query = $this->db->insert('unit_client', $data);
        return $query;
    }
    public function update($id_unit, $unit,$status){
        $data = array('unit'=>$unit,
        'status'=>$status,
        'unit_update'=>date('Y-m-d H-i-s'));
        $this->db->where('id_unit', $id_unit);
        $query = $this->db->update('unit_client', $data);
        return $query;
    }
    public function read($id){
        $this->db->where('id_unit', $id);
        $query = $this->db->get('unit_client');
        return $query;
    }
    public function verifyUnit($id,$apikey){//,$apikey
        $this->db->where('id_unit', $id);
        $this->db->where('api_key', $apikey);
        $query = $this->db->get('unit_client');
        return $query;
    }
    public function delete($id){
        $this->db->where('id_unit', $id);
        $query = $this->db->delete('unit_client');
        return $query;
    }
    public function getAll(){
        $query = $this->db->get('unit_client');
        return $query;
    }

}

Dan jangan lupa, model_monitor juga.

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Model_monitor extends CI_Model{

    public function create($unit,$output,$apikey){//simpan data monitoring
        $data = array('unit_id' => $unit,
        'output'=>$output,
        'api_key'=>$apikey,
        'monitor_created'=>date('Y-m-d H-i-s'));
        $query = $this->db->insert('monitor_client', $data);
        return $query;
    }
    public function getByUnitId($id){//ambil data berdasarkan unit id
        $this->db->where('unit_id', $id);
        $query = $this->db->get('monitor_client');
        return $query;
    }
    public function getByApiKey($key){//ambil data berdasarkan api key
        $this->db->where('api_key', $key);
        $this->db->order_by('monitor_created','desc');
        $query = $this->db->get('monitor_client');
        return $query;
    }
    public function deleteByUnitId($id){//hapus berdasarkan unit id
        $this->db->where('unit_id', $id);
        $query = $this->db->delete('monitor_client');
        return $query;
    }
    public function getLastByUnitId($unit){//ambil data terakhir berdasarkan unit id 
        $this->db->where('unit_id', $unit);
        $this->db->limit(1);
        $this->db->order_by('id_monitor','desc');
        $query = $this->db->get('monitor_client');
        return $query;
    }
    function getByUnitIdReport($id){//ambil 200 data monitoring terakhir
        $this->db->where('unit_id', $id);
        $this->db->order_by('monitor_created','desc');
        $this->db->limit(200);
        $query = $this->db->get('monitor_client');
        return $query;
    }

}

Yang terakhir kita ubah file controller Monitoring.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';//lokasi library rest

class Monitoring extends REST_Controller{
    public function __construct(){
      parent::__construct();
      $this->load->model(array('model_monitor',
        'model_unit'));
    }

    function unit_get(){
        //$data = array('respon : '.$this->get('id'));
        if($this->get('id')!=null){
            if($this->model_monitor->getLastOrder($this->get('id'),$this->get('key'))->num_rows()!=null){
                foreach ($this->model_monitor->getLastOrder($this->get('id'),$this->get('key'))->result() as $unit) {
                    $data = array($unit->output);
                    $this->response($data);
                }
            }else{
                $this->response([
                    'status' => FALSE,
                    'message' => 'No order found',
                    'output' => null
                ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
            }
        }
    }
    function unit_put(){
        if ($this->model_unit->verifyUnit($this->put('id'),$this->put('key'))->num_rows()==null) {//
            $this->set_response(array('status'=>'error'));
        }else{
            $intruksi = $this->model_monitor->create($this->put('id'),$this->put('output'),$this->put('key'));
            if ($intruksi==FALSE) {
                $this->set_response(array('status'=>'error'));
            }else{
                $this->set_response(REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
            }
        }
    }
    function unit_post(){
        $data = array('respon : '.$this->post('id'));
        $this->response($data);
    }
    function unit_delete(){
        $data = array('respon : '.$this->delete('id'));
        $this->response($data);
    }

}

Selamat mencoba, selanjutnya akan kita buat sistem registrasi untuk mendapatkan API KEY-nya. 😀

4 thoughts on “Rest Web Service Codeigniter Bagian Keempat (API KEY)

Tinggalkan Balasan

This site uses Akismet to reduce spam. Learn how your comment data is processed.