<?php
namespace App\Models;
use CodeIgniter\Model;
use Config\Semangka;
use Exception;
class ApiModel extends Model
{
protected $table = 'sm_api_keys';
protected $primaryKey = 'apikey_id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $allowedFields = [
'apikey_key',
'apikey_limits',
'apikey_ipaddress',
'apikey_locked',
];
protected $useTimestamps = true;
protected $createdField = 'apikey_created';
protected $updatedField = 'apikey_modified';
protected $validationRules = [];
protected $validationMessages = [];
public function __construct()
{
$this->db = \Config\Database::connect();
$this->apiLogModel = new ApiLogModel();
$this->request = service('request');
}
/**
* Check API Key
*
* @param string $apiKey API Key
*/
public function checkApi(string $apiKey)
{
$builder = $this->db->table($this->table);
$builder->select('*');
$builder->where('apikey_key', $apiKey);
$apiData = $builder->get();
$resultData = $apiData->getResultArray();
$numRowsData = count($resultData);
$counterApiTerpakai = $this->apiLogModel->countApi($resultData[0]['apikey_key'], Semangka::$limitApiBy);
$arrIpAddr = explode(',', $resultData[0]['apikey_ipaddress']);
if ($numRowsData === 0) {
throw new Exception('API Key tidak terdapat di database');
} elseif ($resultData[0]['apikey_locked'] === 1 || $resultData[0]['apikey_locked'] === '1') {
throw new Exception('API Key yang digunakan terkunci');
} elseif (! in_array($this->request->getIPAddress(), $arrIpAddr, true)) {
throw new Exception('API Key belum didaftarkan untuk server Anda');
} elseif ($resultData[0]['apikey_limits'] > 0 && $counterApiTerpakai >= $resultData[0]['apikey_limits']) {
throw new Exception('API Key sudah melewati batas limit ' . Semangka::$limitApiBy);
} else {
// Save Log
$dataInsert = [
'apilogs_key' => $resultData[0]['apikey_key'],
'apilogs_uri' => uri_string(true),
'apilogs_params' => json_encode($this->request->getVar()),
'apilogs_ipaddr' => $this->request->getIPAddress(),
'apilogs_created' => now(Semangka::$timezone),
];
$this->apiLogModel->saveLogs($dataInsert);
// Result
return $resultData[0];
}
}
}