CodeIgniter Forums
Double Insert Data in Filter Before CI4 - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=31)
+--- Thread: Double Insert Data in Filter Before CI4 (/showthread.php?tid=81968)



Double Insert Data in Filter Before CI4 - flux1on - 05-28-2022

app/Config/Service.php

PHP Code:
public static function validationApiKey(string $apiKey)
    {
        $apiModel = new ApiModel();
        $checkApi $apiModel->checkApi($apiKey);

        if ($checkApi) {
            return true;
        }

        return false;
    

app/Helpers/api_helper.php

PHP Code:
<?php

use Config\Services;

function 
getApiFromRequest($authenticationHeader): array
{
    if (null === $authenticationHeader) {
        throw new Exception('API Key tidak diterdapat pada HTTP_AUTHORIZATION');
    }

    // JWT is sent from client in the format Bearer XXXXXXXXX
    $tokenApi explode(' '$authenticationHeader)[1];

    if (Services::validationApiKey($tokenApi)) {
        return [
            'success' => Services::validationApiKey($tokenApi),
            'data'    => $tokenApi,
        ];
    }

    throw new Exception('API Key tidak terdapat di database');


app/Filters/APIAuthFilter.php

PHP Code:
<?php

namespace App\Filters;

use 
CodeIgniter\API\ResponseTrait;
use 
CodeIgniter\Filters\FilterInterface;
use 
CodeIgniter\HTTP\RequestInterface;
use 
CodeIgniter\HTTP\ResponseInterface;
use 
Config\Services;
use 
Exception;

class 
APIAuthFilter implements FilterInterface
{
    use ResponseTrait;

    public function before(RequestInterface $request$arguments null)
    {
        $authenticationHeader $request->getServer('HTTP_AUTHORIZATION');

        try {
            helper('api');

            return getApiFromRequest($authenticationHeader);
        } catch (Exception $e) {
            return Services::response()
                ->setJSON(
                    [
                        'error'  => true,
                        'message' => $e->getMessage(),
                    ]
                )
                ->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
        }
    }

    public function after(RequestInterface $requestResponseInterface $response$arguments null)
    {

    }


app/Models/ApiModel.php

PHP Code:
<?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'] === || $resultData[0]['apikey_locked'] === '1') {
            throw new Exception('API Key yang digunakan terkunci');
        } elseif (! in_array($this->request->getIPAddress(), $arrIpAddrtrue)) {
            throw new Exception('API Key belum didaftarkan untuk server Anda');
        } elseif ($resultData[0]['apikey_limits'] > && $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];
        }
    }


app/Models/ApiLogModel.php

PHP Code:
<?php

namespace App\Models;

use 
CodeIgniter\Model;
use 
Config\Semangka;

class 
ApiLogModel extends Model
{
    protected $table            'sm_api_logs';
    protected $primaryKey      'apilogs_id';
    protected $useAutoIncrement true;
    protected $returnType      'array';
    protected $useSoftDeletes  false;
    protected $allowedFields    = [
        'apilogs_key',
        'apilogs_uri',
        'apilogs_params',
        'apilogs_ipaddr',
    ];
    protected $useTimestamps      true;
    protected $createdField      'apilogs_created';
    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation    false;

    public function __construct()
    {
        $this->db      = \Config\Database::connect();
        $this->builder $this->db->table($this->table);
        $this->request service('request');
    }

    /**
    * @param string $apiKey    API Key
    * @param string $modeLimit Harian / Mingguan / Bulanan / Tahunan
    */
    public function countApi(string $apiKeystring $modeLimit)
    {
        helper('date');

        $this->builder->select('*');
        $this->builder->where('apilogs_key'$apiKey);

        if ($modeLimit === 'Harian') {
            $this->builder->where('DAY(apilogs_created)''DAY(' now(Semangka::$timezone) . ')');
        } elseif ($modeLimit === 'Mingguan') {
            $this->builder->where('WEEK(apilogs_created)''WEEK(' now(Semangka::$timezone) . ')');
        } elseif ($modeLimit === 'Bulanan') {
            $this->builder->where('MONTH(apilogs_created)''MONTH(' now(Semangka::$timezone) . ')');
        } elseif ($modeLimit === 'Tahunan') {
            $this->builder->where('YEAR(apilogs_created)''YEAR(' now(Semangka::$timezone) . ')');
        }

        return $this->builder->countAllResults();
    }

    /**
    * Auto Save Log API
    *
    * @param array $data Data Logs API
    */
    public function saveLogs(array $data = [])
    {
        $this->builder->insert($data);
    }


I have API Key Validation with Filter and if no issue to criteria validation, i want to save logs anyone hit my API. But logs save 2 times. Can i save logs one only if everyone hit one my api?


RE: Double Insert Data in Filter Before CI4 - iRedds - 05-29-2022

You are calling the function twice.
PHP Code:
if (Services::validationApiKey($tokenApi)) {   // <-- here
        
return [
            
'success' => Services::validationApiKey($tokenApi), // <-- and here
            
'data'    => $tokenApi,
        ];
    } 

You need to review all code.


RE: Double Insert Data in Filter Before CI4 - flux1on - 05-29-2022

(05-29-2022, 06:47 PM)iRedds Wrote: You are calling the function twice.
PHP Code:
    if (Services::validationApiKey($tokenApi)) {  // <-- here
        return [
            'success' => Services::validationApiKey($tokenApi), // <-- and here
            'data'    => $tokenApi,
        ];
    

You need to review all code.

Okay thankyou @iRedds, now no double data again in database with

PHP Code:
    // JWT is sent from client in the format Bearer XXXXXXXXX
    $tokenApi explode(' '$authenticationHeader)[1];

    if (Services::validationApiKey($tokenApi)) {
        return true;
    }

    throw new Exception('API Key tidak terdapat di database');