Merge branch 'dev' of bitbucket.org:jubilian/nhance into dev

This commit is contained in:
VENKATESHWARAN 2026-01-21 09:45:12 +05:30
commit 92ef523f51
51 changed files with 1461 additions and 360 deletions

View File

@ -108,3 +108,5 @@ CORS_MAX_AGE=7200
CORS_DEBUG=true
APP_SIGNATURE =
TOKENTIMEOUT =
JWT_SECRET =

157
app/Config/Acl.php Normal file
View File

@ -0,0 +1,157 @@
<?php
namespace Config;
class Acl
{
public array $rules = [
// ===================== PUBLIC / AUTH =====================
'#^/login#' => ['public' => true],
'#^/logout#' => ['public' => true],
'#^/auth#' => ['public' => true],
'#^/oauth2callback#' => ['public' => true],
'#^/loginPos#' => ['public' => true],
'#^/getVerifyPosMobileNo#' => ['public' => true],
'#^/getVerifiedPosUserData#' => ['public' => true],
'#^/swagger#' => ['roles' => [ADMIN_ROLE_ID]],
'#^/fedeploy#' => ['roles' => [ADMIN_ROLE_ID]],
// ===================== PUBLIC DOWNLOADS / FORMS =====================
'#^/download-#' => ['public' => true],
'#^/claim-form-download#' => ['public' => true],
'#^/claims-feedback-form#' => ['public' => true],
'#^/autobookstackLogin#' => ['public' => true],
// ===================== DASHBOARD =====================
'#^/dashboard#' => [
'roles' => [ ADMIN_ROLE_ID,HEAD_ROLE_ID, MANAGER_ROLE_ID, STAFF_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => []
],
// ===================== USER MANAGEMENT =====================
'#^/user#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID],
'teams' => []
],
// ===================== CLIENT =====================
'#^/client#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => []
],
// ===================== EMPLOYEE / ENROLLMENT =====================
'#^/employee#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [ENROLLMENT_TEAM_ID]
],
// ===================== MASTERS =====================
'#^/master#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => []
],
'#^/util#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
// ===================== POLICY TRANSACTION / BDS =====================
'#^/policy_tranction#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
'#^/bds_upload#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
// ===================== REPORTS =====================
'#^/bdsReport#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
// ===================== PAYOUT / COMMISSION =====================
'#^/payout#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
'#^/commission#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [FINANCE_TEAM_ID,POS_TEAM_ID]
],
// ===================== CLAIMS / TICKETS =====================
'#^/ticket#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [CLAIMS_TEAM_ID]
],
'#^/claim_mis#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [CLAIMS_TEAM_ID]
],
// ===================== LEADS / SALES =====================
'#^/leads#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [BUSINESS_SUPPORT_TEAM_ID, SALES_TEAM_ID]
],
'#^/rfq#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID],
'teams' => [SALES_TEAM_ID]
],
'#^/sales#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID],
'teams' => [SALES_TEAM_ID]
],
// ===================== CMS / CONTENT =====================
'#^/add_image_index#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
'#^/frontend_content#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
'#^/FAQ#' => [
'roles' => [ HEAD_ROLE_ID,ADMIN_ROLE_ID, MANAGER_ROLE_ID, ACCOUNT_MANAGER_ROLE_ID,STAFF_ROLE_ID],
'teams' => []
],
// ===================== LOGS =====================
'#^/logs#' => [
'roles' => [ADMIN_ROLE_ID],
'teams' => []
],
// ===================== INTERNAL TEST =====================
'#^/test#' => [
'roles' => [ADMIN_ROLE_ID],
'teams' => []
],
// ===================== API (JWT / SIGNED) =====================
'#^/api#' => ['public' => true],
'#^/employeeRest#' => ['public' => true],
'#^/clientApi#' => ['public' => true],
// ===================== WEBHOOKS / 3RD PARTY =====================
'#^/dispatchWebhookData#' => ['public' => true],
'#^/retrieveWebhookData#' => ['public' => true],
// '#^/ICICI#' => ['public' => true],
// '#^/Vidal#' => ['public' => true],
// '#^/MediAssist#' => ['public' => true],
// ===================== CLI =====================
'#^/cli/#' => ['public' => true],
// ===================== DEFAULT DENY (ZERO TRUST) =====================
'#^/#' => [
'roles' => [ADMIN_ROLE_ID],
'teams' => []
],
];
}

View File

@ -101,6 +101,6 @@ class Autoload extends AutoloadConfig
* @phpstan-var list<string>
*/
public $helpers = ['uuid','session','utility', 'form', 'url', 'oauth', 'fileupload',
'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper','exception','sms_helper'
'excel_import_export', 'file', 'drive','ExcelSanitizeHelper', 'api_helper','exception','sms_helper','sanitizeInputArrayAdvanced'
];
}

View File

@ -18,6 +18,7 @@ use App\Filters\VerifyAppSignature;
use App\Filters\Cors;
use App\Filters\SecurityInputFilter;
use App\Filters\GlobalPostFileUploadGuard;
use App\Filters\AclFilter;
use App\Filters\AuthJWT;
@ -47,6 +48,7 @@ class Filters extends BaseConfig
'Cors' => Cors::class,
'SecurityInputFilter' => SecurityInputFilter::class,
'GlobalPostFileUploadGuard' => GlobalPostFileUploadGuard::class,
'AclFilter' => AclFilter::class,
];
/**
@ -60,7 +62,8 @@ class Filters extends BaseConfig
'before' => [
'HttpRequestLog' => ['except' => 'cli/*'],
'Cors',
'SecurityInputFilter',
'AclFilter' => ['except' => ['login', 'logout', 'auth/*', 'oauth2callback','claim-form-download', 'claims-feedback-form', 'autobookstackLogin','employeeRest/*','processjob']],
'SecurityInputFilter' => ['except' => ['notification/create','/ticket/crud_mail_template/*','test_mail','leads/sendMail'] ],
'GlobalPostFileUploadGuard'
// 'csrf',
// 'invalidchars',

View File

@ -600,6 +600,8 @@ $routes->group("employeeRest", ['filter' => ['appSignature'] ], function ($route
$routes->group("employeeRest", ["filter" => ['appSignature' , 'authJWT']], function ($routes) {
$routes->post('logout', 'RestAuthenticationController::logout');
$routes->post("ecardRequest", "ApiServiceController::ecardRequest");
$routes->get("getWellnessURL", "ApiServiceController::getWellnessURL");
@ -760,7 +762,7 @@ $routes->post("retrieveWebhookDataClaim","ClientWebHooksController::pullData_cla
//Third party ICICILombard Api Call
$routes->get('generateAuthToken','ICICILombardController::generateAuthToken');
$routes->get('generateAuthToken','FhplApiController::generateAuthToken');
$routes->get('createEnrollmentBatch','ICICILombardController::createEnrollmentBatch');
$routes->get('getEnrollmentBatchStatus','ICICILombardController::getEnrollmentBatchStatus');
$routes->get('fetchUHIDDetails','ICICILombardController::fetchUHIDDetails');

View File

@ -264,9 +264,9 @@ class AppContentManagementController extends AdminController
if (!empty($id)) {
if($returnType === 'web'){
$row = $this->faqModel->find($id);
$row = $this->faqModel->find((int)$id);
}else{
$row = $this->faqModel->where('is_active', 1)->find($id);
$row = $this->faqModel->where('is_active', 1)->find((int)$id);
}
$data['faq_list'] = $row ? [$row] : [];

View File

@ -101,10 +101,10 @@ class BDSReportController extends AdminController
SELECT
ins.id,
ins.name AS insurers,
COALESCE(SUM(CASE WHEN pt.action_type = 'inception' AND pt.insurer_id = ins.id AND ptp.policy_category = $insurerCategory THEN 1 ELSE 0 END), 0) AS Policies,
COALESCE(SUM(CASE WHEN ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS Premium,
COALESCE(SUM(CASE WHEN stmt.co_share_id = pt_co.id AND ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN stmt.reward + stmt.actual_bp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.actual_tp_brokerage_amt ELSE 0 END), 0) AS Revenue,
COALESCE(SUM(CASE WHEN ptp.policy_category = $insurerCategory AND pt_co.insurer_id = ins.id THEN pt_co.exp_amt ELSE 0 END), 0) AS Expected_amt
COALESCE(SUM(CASE WHEN pt.action_type = 'inception' AND pt.insurer_id = ins.id AND ptp.policy_category = :insurerCategory: THEN 1 ELSE 0 END), 0) AS Policies,
COALESCE(SUM(CASE WHEN ptp.policy_category = :insurerCategory: AND pt_co.insurer_id = ins.id THEN (pt_co.cop_amt + pt_co.cotp_amt + pt_co.cotep_amt + pt_co.non_comm_per_amt) ELSE 0 END), 0) AS Premium,
COALESCE(SUM(CASE WHEN stmt.co_share_id = pt_co.id AND ptp.policy_category = :insurerCategory: AND pt_co.insurer_id = ins.id THEN stmt.reward + stmt.actual_bp_brokerage_amt + stmt.actual_tep_brokerage_amt + stmt.actual_tp_brokerage_amt ELSE 0 END), 0) AS Revenue,
COALESCE(SUM(CASE WHEN ptp.policy_category = :insurerCategory: AND pt_co.insurer_id = ins.id THEN pt_co.exp_amt ELSE 0 END), 0) AS Expected_amt
FROM
insurers ins
LEFT JOIN
@ -112,16 +112,17 @@ class BDSReportController extends AdminController
LEFT JOIN
co_share_stmt_details stmt ON pt_co.id = stmt.co_share_id AND stmt.is_active = 1
LEFT JOIN
policy_transaction pt ON pt_co.pt_id = pt.id AND pt.is_active = 1 AND pt.policy_issue_date >= '$fromDate' AND pt.policy_issue_date <= '$toDate'
policy_transaction pt ON pt_co.pt_id = pt.id AND pt.is_active = 1 AND pt.policy_issue_date >= :fromDate: AND pt.policy_issue_date <= :toDate:
LEFT JOIN
policy_type ptp ON pt.policy_type_id = ptp.id AND ptp.policy_category = $insurerCategory AND ptp.is_active = 1
policy_type ptp ON pt.policy_type_id = ptp.id AND ptp.policy_category = :insurerCategory: AND ptp.is_active = 1
WHERE
ins.is_active = 1 AND (ptp.policy_category = $insurerCategory OR ptp.policy_category IS NULL)
ins.is_active = 1 AND (ptp.policy_category = :insurerCategory: OR ptp.policy_category IS NULL)
GROUP BY
ins.id;
";
$data['insurer_wise_data'] = $this->insurerModel->query($sql)->getResultArray();
$binds = ['insurerCategory'=>$insurerCategory,'fromDate'=>$fromDate,'toDate'=>$toDate];
$data['insurer_wise_data'] = $this->insurerModel->query($sql,$binds)->getResultArray();
// log_message('error',$this->insurerModel->getLastQuery());
// log_message('error',json_encode($data));
} catch (\Exception $e) {
@ -146,15 +147,16 @@ class BDSReportController extends AdminController
COALESCE(SUM(co.reward + co.actual_bp_brokerage_amt + co.actual_tep_brokerage_amt + co.actual_tp_brokerage_amt), 0) AS Revenue,
COALESCE(SUM(pt_co.exp_amt), 0) AS Expected_amt
FROM policy_type AS pot
LEFT JOIN policy_transaction AS pt ON pot.id = pt.policy_type_id AND pt.is_active = 1 AND pt.action_type = 'inception' and pt.policy_issue_date >= '$fromDate' and pt.policy_issue_date <= '$toDate'
LEFT JOIN policy_transaction AS pt ON pot.id = pt.policy_type_id AND pt.is_active = 1 AND pt.action_type = 'inception' and pt.policy_issue_date >= :fromDate: and pt.policy_issue_date <= :toDate:
LEFT JOIN pt_co_share_details AS pt_co ON pt.id = pt_co.pt_id AND pt_co.is_active = 1
LEFT JOIN co_share_stmt_details AS co ON pt_co.id = co.co_share_id AND co.is_active = 1
WHERE pot.is_active = 1
AND pot.policy_category = $insurerCategory
AND pot.policy_category = :insurerCategory:
GROUP BY pot.bap;
";
$data['bap_wise_data'] = $this->policyTypeModel->query($sql)->getResultArray();
$binds = ['insurerCategory'=>$insurerCategory,'fromDate'=>$fromDate,'toDate'=>$toDate];
$data['bap_wise_data'] = $this->policyTypeModel->query($sql,$binds)->getResultArray();
} catch (\Exception $e) {
$data['message'] = 'No Data Found';
$this->myLogger->logme('error', $e->getMessage());

View File

@ -0,0 +1,48 @@
<?php
namespace App\Controllers;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\BaseController;
class ClaimsUploadController extends BaseController
{
use ResponseTrait;
protected $db;
public function __construct()
{
$this->db = \Config\Database::connect();
}
public function uploadDump()
{
$file = $this->request->getFile('file');
if (!$file || !$file->isValid()) {
return $this->respond([
'status' => 'failed',
'message' => 'Invalid file'
], 400);
}
$data = [
'client_id' => $this->request->getPost('client_id'),
'tpa_id' => $this->request->getPost('tpa_id'),
'client_policy_id' => $this->request->getPost('client_policy_id'),
'from_date' => $this->request->getPost('from_date'),
'to_date' => $this->request->getPost('to_date'),
'upload_file' => $file->getRandomName(),
// 'uploaded_by' => user_id()
];
$file->move(WRITEPATH . 'uploads/claims_dump', $data['upload_file']);
$this->db->table('claims_dump_uploads')->insert($data);
return $this->respond([
'status' => 'success',
'message' => 'Claims dump uploaded'
]);
}
}

View File

@ -665,7 +665,7 @@ class ClientController extends AdminController
$headerData['tab_name'] = 'Client Deposit';
$headerData['page_name'] = 'Clients';
$data['clientName'] = $this->clientModel->where('id', $id)->find();
$data['clientName'] = $this->clientModel->where('id', (int)$id)->find();
$data['clientData'] = $this->clientPolicyModel->getinsurerswithclientid($id, $policyId);
$data['depositsummary'] = $this->clientPolicyModel->getDepositlistsummary($id);
@ -736,14 +736,102 @@ class ClientController extends AdminController
public function saveDeposit()
{
$rules = [
'amount' => [
'rules' => 'required|numeric|greater_than_equal_to[0]',
'errors' => [
'required' => 'Amount is required',
'numeric' => 'Amount must be a valid number',
'greater_than_equal_to' => 'Amount cannot be negative',
]
],
'client_id' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Client ID is required',
'is_natural_no_zero' => 'Client ID must be a positive integer',
]
],
'insurer_id' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Insurer ID is required',
'is_natural_no_zero' => 'Insurer ID must be a positive integer',
]
],
'cd_ac_pk' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Account PK is required',
'is_natural_no_zero' => 'Account PK must be a positive integer',
]
],
'cd_ac_no' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Account number is required',
'is_natural_no_zero' => 'must be a positive integer',
]
],
'sub_type_id' => [
'rules' => 'required|is_natural_no_zero',
'errors' => [
'required' => 'Sub type ID is required',
'is_natural_no_zero' => 'Sub type ID must be a positive integer',
]
],
'description' => [
'rules' => 'required|string|min_length[3]|max_length[255]',
'errors' => [
'required' => 'Description is required',
'string' => 'Description must be text',
'min_length' => 'Description must be at least 3 characters',
'max_length' => 'Description must not exceed 255 characters',
]
],
'transaction_type' => [
'rules' => 'required|in_list[Credit,Debit]',
'errors' => [
'required' => 'Transaction type is required',
'in_list' => 'Transaction type must be either credit or debit',
]
],
];
if (! $this->validate($rules)) {
return $this->response
->setStatusCode(400)
->setJSON([
'status' => 'error',
'message' => 'Input validation failed',
'errors' => $this->validator->getErrors()
]);
}
//sanitize the post params
$post_data = $this->request->getPost();
$sanitized_post_data = sanitizeInputArrayAdvanced($post_data);
// Retrieve form data from POST request
$loggedInUserID = get_session_userid();
// print_rr($sanitized_post_data);die();
$client_id = $sanitized_post_data['client_id'];
$insurer_id = $sanitized_post_data['insurer_id'];
$record_date = $sanitized_post_data['record_date'];
$cd_ac_pk = $sanitized_post_data['cd_ac_pk'];
$cd_ac_no = $sanitized_post_data['cd_ac_no'];
$client_id = $this->request->getPost('client_id');
$insurer_id = $this->request->getPost('insurer_id');
$record_date = $this->request->getPost('record_date');
$cd_ac_pk = $this->request->getPost('cd_ac_pk');
$cd_ac_no = $this->request->getPost('cd_ac_no');
// $CD_Account_Number = $this->CDMasterModel
// ->where('client_id', $client_id)
@ -761,16 +849,16 @@ class ClientController extends AdminController
}
$data = [
'amount' => $this->request->getPost('amount'),
'sub_type_id' => $this->request->getPost('sub_type_id'),
'client_id' => $this->request->getPost('client_id'),
'amount' => $sanitized_post_data['amount'],
'sub_type_id' => $sanitized_post_data['sub_type_id'],
'client_id' => $sanitized_post_data['client_id'],
'client_policy_id' => null,
'cd_ac_no' => $cd_ac_no ?? null,
'cd_ac_pk' => $cd_ac_pk ?? null,
'endorsement_no' => null,
'insurer_id' => $this->request->getPost('insurer_id'),
'description' => $this->request->getPost('description'),
'transaction_type' => $this->request->getPost('transaction_type') ?: 'Credit',
'insurer_id' => $sanitized_post_data['insurer_id'],
'description' => $sanitized_post_data['description'],
'transaction_type' => $sanitized_post_data['transaction_type'] ?: 'Credit',
'updated_by' => 1,
'record_date' => $record_date
];
@ -1371,7 +1459,7 @@ class ClientController extends AdminController
$rr_unit_count2 = 0;
$total_count = 0;
$list_of_branch_units = $this->clientBranchModel->find($id);
$list_of_branch_units = $this->clientBranchModel->find((int)$id);
$units = json_decode($list_of_branch_units['units']);
if (!is_array($units) || empty($units)) {
@ -1395,7 +1483,7 @@ class ClientController extends AdminController
if ($total_count > 0) {
$units = (string) $this->request->getPost('units'); // Assuming 'units' is an array
$list_of_branch_units = $this->clientBranchModel->find($id);
$list_of_branch_units = $this->clientBranchModel->find((int)$id);
$branch_units = json_decode($list_of_branch_units['units'], true);
$units = json_decode($units);
@ -3762,9 +3850,9 @@ class ClientController extends AdminController
// $policy_status = $this->clientPolicyModel->where('id', $client_policy_id )->set('policy_status', 1)->update();
$json_data = '';
$open_for_enrollment = $this->clientPolicyModel->where('id', $client_policy_id)->set('open_for_enrollment', $open_for_enrollment_update_value)->update();
$open_for_enrollment = $this->clientPolicyModel->where('id', (int)$client_policy_id)->set('open_for_enrollment', $open_for_enrollment_update_value)->update();
if ($open_for_enrollment) {
$open_for_enrollment_1 = $this->clientPolicyModel->where('id', $client_policy_id)->find();
$open_for_enrollment_1 = $this->clientPolicyModel->where('id', (int)$client_policy_id)->find();
$open_for_enrollment_value = $open_for_enrollment_1[0]['open_for_enrollment'];
$client_policy_id_value = $client_policy_id;

View File

@ -443,7 +443,7 @@ class DashboardController extends AdminController
foreach ($client_policy_data as $client_policy) {
// Fetch client data
$client_data = $this->clientModel->find($client_policy['client_id']);
$client_data = $this->clientModel->find((int)$client_policy['client_id']);
// Fetch notification settings
$notification_data = $this->notificationModel

View File

@ -487,13 +487,18 @@ class EmpDataServiceController extends BaseController
WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2
ELSE `client_policy`.`policy_type_id`
END
WHERE `client_policy`.`id` = '".$export_data['client_policy_id']."'
AND `insurer_excel_export_template`.`event_name` = '".$export_data['event_type']."'
WHERE `client_policy`.`id` = :client_policy_id:
AND `insurer_excel_export_template`.`event_name` = :event_name:
AND `insurer_excel_export_template`.`is_active` = 1
AND `insurer_excel_export_template`.`type_name` = '".$export_data['actions']."'
AND `insurer_excel_export_template`.`type_name` = :type_name:
LIMIT 1";
$query = db_connect()->query($sql);
$binds = [
'client_policy_id' => (int)$export_data['client_policy_id'],
'event_name' => $export_data['event_type'],
'type_name' => $export_data['actions'],
];
$query = db_connect()->query($sql,$binds);
$template_json = $query->getRowArray();
// dd(db_connect()->getLastQuery());
@ -1095,13 +1100,15 @@ class EmpDataServiceController extends BaseController
WHEN `client_policy`.`policy_type_id` IN (2, 3, 4, 5) THEN 2
ELSE `client_policy`.`policy_type_id`
END
WHERE `client_policy`.`id` = '".$export_data['client_policy_id']."'
WHERE `client_policy`.`id` = :client_policy_id:
AND `insurer_excel_export_template`.`event_name` = 'all'
AND `insurer_excel_export_template`.`is_active` = 1
AND `insurer_excel_export_template`.`type_name` = '".$export_data['actions']."'
AND `insurer_excel_export_template`.`type_name` = :type_name:
LIMIT 1";
$query = db_connect()->query($sql);
$binds = ['client_policy_id' => (int)$export_data['client_policy_id'],
'type_name' => $export_data['actions']];
$query = db_connect()->query($sql,$binds);
$template_json = $query->getRowArray();
@ -1931,7 +1938,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'Inception Update TPA and UHID -- Function called');
$file_id = $params['file_id'];
$file = $this->batchFileModel->find($file_id);
$file = $this->batchFileModel->find((int)$file_id);
// dd($file);
if (!$file) {
@ -1940,10 +1947,10 @@ class EmpDataServiceController extends BaseController
'status' => 'failed-4',
];
$this->batchFileModel->where('id', $file_id)->set($data)->update();
$this->batchFileModel->where('id', (int)$file_id)->set($data)->update();
$this->myLogger->logme('error', 'Inception Update TPA and UHID -- The Physical file not found -- File id : {data}', ['data' => $file_id]);
$file_data = $this->getDataByFileId($file_id, 'failure');
$file_data = $this->getDataByFileId((int)$file_id, 'failure');
$this->setPullNotification($file_data);
return ['status' => 'error', 'message' => 'Inception Update TPA and UHID -- The Physical file not found']; // Return error code if file not found
@ -1958,17 +1965,17 @@ class EmpDataServiceController extends BaseController
$user_id = $file['created_by'];
$policy_issue_date = $file['policy_issue_date'];
$insurer_id = $this->clientPolicyModel->where('id', $client_policy_id)->first();
$insurer_id = $this->clientPolicyModel->where('id', (int)$client_policy_id)->first();
$CD_Account_Number = $this->CDMasterModel
->where('client_id', $client_id)
->where('insurer_id', $insurer_id['insurer_id'])
->where('client_id', (int)$client_id)
->where('insurer_id', (int)$insurer_id['insurer_id'])
->first();
$get_policy_type = $this->clientPolicyModel
->select('client_policy.*, policy_type.policy_type')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id', 'left')
->where('client_policy.id', $client_policy_id)
->where('client_policy.id', (int)$client_policy_id)
->first();
// dd($get_policy_type);
@ -2500,7 +2507,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'importCorrectionUpdateEndorsementID called');
$file_id = $params['file_id'];
$file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id);
if (!$file) {
@ -3135,7 +3142,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'SI Enhancement Update Endorsement ID -- Function called');
$file_id = $params['file_id'];
$file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id);
if (!$file) {
@ -3709,7 +3716,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'Deletion Update Endorsement ID -- Function called');
$file_id = $params['file_id'];
$file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id);
if (!$file) {
@ -4193,7 +4200,7 @@ class EmpDataServiceController extends BaseController
$this->myLogger->logme('error', 'importCorrectionUpdateEndorsementID called');
$file_id = $params['file_id'];
$file_id = (int)$params['file_id'];
$file = $this->batchFileModel->find($file_id);
if (!$file) {
@ -4454,11 +4461,12 @@ class EmpDataServiceController extends BaseController
SELECT SUM(rata_premimum + gst) AS total_sum
FROM employee_polices
JOIN employees ON employees.id = employee_polices.employee_id
WHERE employees.unit = '{$unit}'
AND employee_polices.id = '{$pk}'
WHERE employees.unit = :unit:
AND employee_polices.id = :pk:
";
$amount = $this->employeePolicyModel->query($query)->getRow();
$binds = ['unit' => $unit,'pk' => $pk];
$amount = $this->employeePolicyModel->query($query,$binds)->getRow();
if ($amount && $amount->total_sum > 0) {
if ($si_adjustment == 2) {

View File

@ -177,7 +177,7 @@ class EmployeeController extends AdminController
// die();
// $file_id = $this->request->getGet();
// echo $file_id;die();
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// print_r($result);die();
if (!isset($file)) {
return $this->respond(['dataStatus' => false, 'code' => 404, 'message' => 'no data found'], 200);
@ -412,7 +412,7 @@ class EmployeeController extends AdminController
if (in_array($role_id, [2, 3])) {
// If the user is a Account Manager or Manager, filter by user_id
$query->where('cr.user_id', $user_id);
$query->where('cr.user_id', (int)$user_id);
}
// ->where('files.created_by', get_session_userid())
$data['fileList'] = $query->groupBy("files.id")->orderBy('files.created_at', 'desc')
@ -463,7 +463,7 @@ class EmployeeController extends AdminController
if (in_array($role_id, [2, 3])) {
// If the user is a Account Manager or Manager, filter by user_id
$query2->where('cr.user_id', $user_id);
$query2->where('cr.user_id', (int)$user_id);
}
// ->where('files.created_by', get_session_userid())
$data['batch_list'] = $query2->groupBy("batch_files.id")->orderBy('batch_files.id', 'desc')
@ -1167,7 +1167,7 @@ class EmployeeController extends AdminController
public function downloadFullExcelErrorFile($file_id, $rowIndex = 1, $colIndex = 1)
{
// Get file data from the database
$file_data = $this->fileModel->find($file_id);
$file_data = $this->fileModel->find((int)$file_id);
$error = json_decode($file_data['reason']);
// echo '<pre>';
@ -1779,7 +1779,7 @@ class EmployeeController extends AdminController
$this->myLogger->logme('error', 'File id for truncate : -- FILE ID : {data} --', ['data' => $file_id]);
//get the files data
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$client_id = $file['client_id'];
$client_policy_id = $file['policy_id'];
@ -1837,9 +1837,11 @@ class EmployeeController extends AdminController
$query = "
UPDATE employee_polices
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employee_polices.file_id = $file_id
WHERE employee_polices.file_id == :file_id:
";
$db->query($query);
$binds = ["file_id" => $file_id];
$db->query($query,$binds);
$affectedRows = $db->affectedRows();
$this->myLogger->logme('error', '---- employee_polices table update query : {data} ----', ['data' => $query]);
$this->myLogger->logme('error', '---- employee_polices table updated - Affected Rows : {data} ----', ['data' => $affectedRows]);
@ -1931,12 +1933,13 @@ class EmployeeController extends AdminController
$dependent_policies = '(' . implode(',', $dependent_policies) . ')';
$query = "
UPDATE employee_polices
JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in $emp_codes
JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in :emp_codes:
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employee_polices.client_policy_id in $dependent_policies
WHERE employee_polices.client_policy_id in :dependent_policies:
";
// print_r($query); die;
$db->query($query);
$binds = ["emp_codes" => $emp_codes , "dependent_policies" => $dependent_policies];
$db->query($query,$binds);
$affectedRows = $db->affectedRows();
// dd($affectedRows);
@ -2060,7 +2063,7 @@ class EmployeeController extends AdminController
{
$file_id = $this->request->uri->getSegment(3);
// $file_id = 747;
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$client_id = $file['client_id'];
$client_policy_id = $file['policy_id'];
$loggedInUserID = get_session_userid();
@ -2124,10 +2127,11 @@ class EmployeeController extends AdminController
$query = "
UPDATE employee_polices
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employee_polices.file_id = $file_id
WHERE employee_polices.file_id = :file_id:
";
$db->query($query);
$binds = ["file_id" => $file_id];
$db->query($query,$binds);
$affectedRows = $db->affectedRows();
$this->myLogger->logme('error', 'employee_polices table update query : {data}', ['data' => $query]);
$this->myLogger->logme('error', 'employee_polices table updated - Affected Rows : {data}', ['data' => $affectedRows]);
@ -2189,11 +2193,12 @@ class EmployeeController extends AdminController
$dependent_policies = '(' . implode(',', $dependent_policies) . ')';
$query = "
UPDATE employee_polices
JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in $emp_codes
JOIN employees ON employees.id = employee_polices.employee_id and employees.emp_code in :emp_codes:
SET employee_polices.status = 'truncated', employee_polices.is_active = 0
WHERE employee_polices.client_policy_id in $dependent_policies
WHERE employee_polices.client_policy_id in :dependent_policies:
";
$db->query($query);
$binds = ["emp_codes" => $emp_codes , "dependent_policies" => $dependent_policies];
$db->query($query,$binds);
$affectedRows = $db->affectedRows();
// dd($affectedRows);
@ -2422,7 +2427,7 @@ class EmployeeController extends AdminController
public function hasPolicyConfigCompleted()
{
$client_policy_id = $this->request->uri->getSegment(3);
$policy_details = $this->clientPolicyModel->find($client_policy_id);
$policy_details = $this->clientPolicyModel->find((int)$client_policy_id);
$insurer_details = $this->insurerModel->where('id', $policy_details['insurer_id'])->first();
$policy_terms = isset($policy_details['policy_terms']) ? true : false;

View File

@ -1018,7 +1018,7 @@ class EmployeeMultiEventServiceController extends BaseController
$this->myLogger->logme('error', 'Excel Multievent File Formate Validation function START: ' . json_encode(['params' => $params]));
helper('excel_util_helper');
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
if (!isset($file)) {
//file not found in DB
@ -1182,7 +1182,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper');
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
if (!isset($file)) {
//file not found in DB
@ -1291,7 +1291,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper');
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
if (!isset($file)) {
//file not found in DB
@ -1387,7 +1387,7 @@ class EmployeeMultiEventServiceController extends BaseController
// dd($params);
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action'];
// dd($file);
@ -1604,7 +1604,7 @@ class EmployeeMultiEventServiceController extends BaseController
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action'];
// Kint::dump($file);
@ -1805,7 +1805,7 @@ class EmployeeMultiEventServiceController extends BaseController
{
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action'];
// dd($file);
$return = [];
@ -1910,7 +1910,7 @@ class EmployeeMultiEventServiceController extends BaseController
// $this->setPullNotification($this->getFileMetaDataByFileId($file_id, 'success'));
} else if (isset($params['client_policy_id'])) //handle data from enrollment to inception
{
$client_policy_id = $params['client_policy_id'];
$client_policy_id = (int)$params['client_policy_id'];
//get client id
$client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id'];
// dd($client_id);
@ -1956,7 +1956,7 @@ class EmployeeMultiEventServiceController extends BaseController
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action'];
// dd($file);
@ -1975,7 +1975,7 @@ class EmployeeMultiEventServiceController extends BaseController
$endorsement_data = [];
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'], $file['policy_id']);
$insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms[0]->insurer_id));
$insurer = ($insurer->find((int)$policy_terms[0]->insurer_id));
// kint::dump($insurer);
//make closure funciton which is going to use only by this method
@ -2095,7 +2095,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action'];
@ -2173,7 +2173,7 @@ class EmployeeMultiEventServiceController extends BaseController
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$file['action'] = $params['action'];
// $file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
@ -2470,7 +2470,7 @@ class EmployeeMultiEventServiceController extends BaseController
{
try {
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// $error_data = json_decode($file['reason'], true);
$error_data = $res;
// dd($error_data);
@ -2632,7 +2632,7 @@ class EmployeeMultiEventServiceController extends BaseController
// dd($this->request);
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file_id = (int)$params['file_id'];
$file = $this->fileModel->find($file_id);
// dd($file);
$return = [];

View File

@ -2220,7 +2220,7 @@ class EmployeeRestController extends AdminController
// dd($client_policy_id);
$client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id'];
$client_id = ($this->clientPolicyModel->select('client_id')->find((int)$client_policy_id))['client_id'];
// get policy and rack details
$policy_terms = $this->clientPolicyModel->getPolicyDetails($client_id, $client_policy_id);
$policy_type = $policy_terms[0]->is_addon;
@ -3274,7 +3274,7 @@ class EmployeeRestController extends AdminController
// Check if the update was successful
if ($db->affectedRows() > 0) {
// Fetch the updated employee data
$updated_employee = $this->employeeModel->find($id);
$updated_employee = $this->employeeModel->find((int)$id);
return $this->respond(['status' => 'success', 'code' => 200, 'data' => $updated_employee], 200);
} else {
log_message('error', 'Update failed. No rows affected.');
@ -3650,15 +3650,16 @@ class EmployeeRestController extends AdminController
from employees emp
left join employees empl on empl.id = $insured_emp_id and empl.is_active = 1 and empl.emp_status = 'active'
left join employee_polices emp_pol on empl.id = emp_pol.employee_id and emp_pol.client_policy_id = $client_policy_id and emp_pol.is_active = 1
left join employees empl on empl.id = :insured_emp_id: and empl.is_active = 1 and empl.emp_status = 'active'
left join employee_polices emp_pol on empl.id = emp_pol.employee_id and emp_pol.client_policy_id = :client_policy_id: and emp_pol.is_active = 1
left join client_policy cp on cp.id = emp_pol.client_policy_id and cp.is_active = 1
left join client_rm cl_rm on cl_rm.client_id = empl.client_id and cl_rm.is_active = 1 and cl_rm.level = 3
where emp.id = $employee_id and emp.is_active = 1 and emp.emp_status = 'active'
where emp.id = :employee_id: and emp.is_active = 1 and emp.emp_status = 'active'
limit 1 ";
$emp_ticket_data = $this->employeeModel->query($sql)->getResultArray();
$binds = ['insured_emp_id'=>$insured_emp_id,'client_policy_id'=>(int)$client_policy_id,'employee_id'=>$employee_id ];
$emp_ticket_data = $this->employeeModel->query($sql,$binds)->getResultArray();
// print_r(db_connect()->getLastQuery()); die;
if (!empty($emp_ticket_data)) {
@ -4614,7 +4615,7 @@ class EmployeeRestController extends AdminController
];
// Check if record exists
$record = $this->hrFileUploadModel->find($id);
$record = $this->hrFileUploadModel->find((int)$id);
if (!$record) {
return $this->failNotFound("Record with ID {$id} not found.");
}
@ -4640,7 +4641,7 @@ class EmployeeRestController extends AdminController
$file_id = $this->request->getGet('id') ?? $id;
// Find record
$record = $this->hrFileUploadModel->where('id', $file_id)->find();
$record = $this->hrFileUploadModel->where('id', (int)$file_id)->find();
// print_rr( $record);die;

View File

@ -784,7 +784,7 @@ class EmployeeServiceController extends AdminController
//get file name
// check_dob_diff('4-APr-1990');die();
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if(!isset($file))
@ -1062,7 +1062,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if(!isset($file))
@ -1322,7 +1322,7 @@ class EmployeeServiceController extends AdminController
{
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if(!isset($file))
@ -1424,7 +1424,7 @@ class EmployeeServiceController extends AdminController
{
$client_policy_id = $params['client_policy_id'];
//get client id
$client_id = ($this->clientPolicyModel->select('client_id')->find($client_policy_id))['client_id'];
$client_id = ($this->clientPolicyModel->select('client_id')->find((int)$client_policy_id))['client_id'];
// dd($client_id);
// get policy and rack details
@ -1470,7 +1470,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
@ -1489,7 +1489,7 @@ class EmployeeServiceController extends AdminController
$endorsement_data = [];
$policy_terms = $this->clientPolicyModel->getPolicyDetails($file['client_id'],$file['policy_id']);
$insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms[0]->insurer_id));
$insurer = ($insurer->find((int)$policy_terms[0]->insurer_id));
// kint::dump($insurer);
//make closure funciton which is going to use only by this method
$endorsement = function($data,$file,$row) use ($insurer){
@ -1621,7 +1621,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$file_name_with_path = WRITEPATH."/uploads/excel/".$file['file_name'];
@ -1700,7 +1700,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$file_name_with_path = WRITEPATH . "/uploads/excel/" . $file['file_name'];
@ -2028,7 +2028,7 @@ class EmployeeServiceController extends AdminController
{
try {
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
$error_data = json_decode($file['reason']);
// dd($error_data);
// return $error_data;
@ -2187,7 +2187,7 @@ class EmployeeServiceController extends AdminController
helper('excel_util_helper');
//get file name
$file_id = $params['file_id'];
$file = $this->fileModel->find($file_id);
$file = $this->fileModel->find((int)$file_id);
// dd($file);
$return = [];
if(!isset($file))

View File

@ -0,0 +1,73 @@
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\BatchFileModel;
use App\Models\EmployeePolicyModel;
use App\Models\TpaApiDataModel;
use App\Models\ClientPolicyModel;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\API\ResponseTrait;
use App\Controllers\Jobs;
class FhplApiController extends BaseController
{
use ResponseTrait;
protected $db;
protected $fhplTpaId;
public function __construct()
{
$this->db = \Config\Database::connect();
$this->fhplTpaId = getenv('FHPL_PRIMARY_KEY_CONSTANT');
}
public function generateAuthToken()
{
$url = env('FHPL_TOKEN_URL'); // example: https://uat.fhpl.net/token
// x-www-form-urlencoded body
$postData = http_build_query([
'UserName' => 'TestApi@fhpl',
'Password' => 'Fhpl@12345',
'grant_type' => 'password',
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'GET', // SAME AS POSTMAN
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => [
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
],
CURLOPT_TIMEOUT => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
return $this->response->setJSON([
'status' => false,
'error' => curl_error($ch),
]);
}
curl_close($ch);
return $this->response->setJSON([
'status' => $httpCode === 200,
'http_code' => $httpCode,
'response' => json_decode($response, true),
]);
}
}

View File

@ -116,7 +116,7 @@ class GoogleDriveController extends BaseController
}
//if not in cache then get it from grdrive
$client = $this->clientModel->find($client_id);
$client = $this->clientModel->find((int)$client_id);
$clientShortName = $client['short_name']; // Assuming short_name is the column for client's short name
}
else if($client_policy_id)

View File

@ -2538,7 +2538,7 @@ class LeadsController extends BaseController
public function calculateMembersDemography($params, $returnType = null)
{
$lead_id = $params['lead_id'];
$lead_data = $this->leadsModel->find($lead_id);
$lead_data = $this->leadsModel->find((int)$lead_id);
$file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name'];
if (!$lead_data) {
@ -2999,7 +2999,7 @@ class LeadsController extends BaseController
// print_r($params); die;
$lead_id = $params['lead_id'];
$lead_id = (int)$params['lead_id'];
$file_type = $params['file_type']; //rfq or qcr
$recipient_type = $params['recipient_type']; //insurer or client or internal or placement
$recipient_mail = $params['recipient_mail']; // - only primary key of contacts
@ -3033,7 +3033,7 @@ class LeadsController extends BaseController
if ($recipient_type === 'placement') {
$lead_data = $this->leadsModel->find($lead_id);
$lead_data = $this->leadsModel->find((int)$lead_id);
$data = [];
@ -5320,7 +5320,7 @@ class LeadsController extends BaseController
public function handleMemberDataGPATotalSumInsurerFromExcel($params)
{
$lead_id = $params['lead_id'];
$lead_data = $this->leadsModel->find($lead_id);
$lead_data = $this->leadsModel->find((int)$lead_id);
// dd($lead_data);
$file_name_with_path = WRITEPATH . "/uploads/lead_files/" . $lead_data['file_name'];
// dd($file_name_with_path);

View File

@ -11,6 +11,8 @@ use CodeIgniter\API\ResponseTrait;
use App\Models\UserModel;
use App\Models\AuthHistoryModel;
use App\Libraries\AuthLogout;
class LoginController extends BaseController
{
use ResponseTrait;
@ -45,7 +47,7 @@ class LoginController extends BaseController
$user_team = $UserModel->getUserTeamsByUserID($user->id);
// dd($user_team);
session()->regenerate(true);
$session_data = [
'isLoggedIn' => True ,
'userid' => $user->id,
@ -56,9 +58,14 @@ class LoginController extends BaseController
$path = getenv('cookie.Path');
$domain = getenv('cookie.Domain');
$https = getenv('ccokie.secure');
setcookie('session_data', json_encode($session_data), time() + 12 * 60 * 60, $path, $domain, $https, true);
// setcookie('session_data', json_encode($session_data), time() + 12 * 60 * 60, $path, $domain, $https, true);
set_session_data($session_data);
// Bind session to device
set_session_data(['fingerprint' => hash('sha256',
($this->request->getUserAgent()->getAgentString() . '|' . ($this->request->getIPAddress()
)))]);
log_message('error', 'Set The UserId : `'. $user->id .'` in Session');
log_message('error', 'User Login Sucessfully');
@ -91,14 +98,23 @@ class LoginController extends BaseController
public function logout()
{
$path = getenv('cookie.Path');
session()->destroy();
// setcookie('session_data', '', time() - 3600, $path);
$path = getenv('cookie.Path');
$domain = getenv('cookie.Domain');
$https = getenv('cookie.secure');
setcookie('session_data',null, time() -3600, $path, $domain, $https, true);
return redirect()->to(base_url('login'));
// $path = getenv('cookie.Path');
// session()->regenerate(true);
// session()->destroy();
// $path = getenv('cookie.Path');
// $domain = getenv('cookie.Domain');
// $https = getenv('cookie.secure');
// setcookie('session_data',null, time() - 42000, $path, $domain, $https, true);
// // return redirect()->to(base_url('login'));
// return redirect()->to(base_url('login'))
// ->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
// ->setHeader('Pragma', 'no-cache')
// ->setHeader('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
return AuthLogout::logout();
}
public function getUserDeviceInfo($userId, $type_of_user)

View File

@ -1197,7 +1197,7 @@ class MasterController extends AdminController
// print_r($id);die;
foreach ($policies as $policy) {
// Retrieve the insurer information
$insurer = $this->insurerModel->find($policy['insurer_id']);
$insurer = $this->insurerModel->find((int)$policy['insurer_id']);
// print_r($insurer);die;
// Add the insurer information to the editData array

View File

@ -147,7 +147,7 @@ class PayoutController extends BaseController
$summary_data = $this->invoiceModel->utrSummary($invoice_id);
if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){
$sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?";
db_connect()->query($sql, [$invoice_id]);
db_connect()->query($sql, [(int)$invoice_id]);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_edit_data, "message" => "UTR successfully updated"], 200);
@ -166,7 +166,7 @@ class PayoutController extends BaseController
$summary_data = $this->invoiceModel->utrSummary($invoice_id);
if($summary_data['invoice_amount'] == $summary_data['total_utr_amount']){
$sql = "UPDATE partner_invoice SET payout_status = 2 WHERE id = ?";
db_connect()->query($sql, [$invoice_id]);
db_connect()->query($sql, [(int)$invoice_id]);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $payout_data, "message" => "UTR added successfully"], 200);

View File

@ -3639,7 +3639,7 @@
helper('excel_util_helper');
//get file info
$file_id = $params['file_id'];
$file = $this->insurerStatements->find($file_id);
$file = $this->insurerStatements->find((int)$file_id);
// dd($file);
$date = new \DateTime($file['month']);
@ -3757,7 +3757,7 @@
try {
//get file info
$file = $this->insurerStatements->find($file_id);
$file = $this->insurerStatements->find((int)$file_id);
// dd($file);
$date = new \DateTime($file['month']);
@ -3910,7 +3910,7 @@
helper('excel_util_helper');
//get file info
$file_id = $params['file_id'];
$file = $this->insurerStatements->find($file_id);
$file = $this->insurerStatements->find((int)$file_id);
// dd($file);
$date = new \DateTime($file['month']);
@ -4075,7 +4075,7 @@
{
$statement_id = $this->request->getUri()->getSegment(4);
$inv_details = $this->insurerStatements->find($statement_id);
$inv_details = $this->insurerStatements->find((int)$statement_id);
$inv_payment_details = $this->invPaymentDetailsModel
->where('statement_id', $statement_id)
->where('is_active', 1)
@ -4212,7 +4212,7 @@
public function getFileErr()
{
$file_id = $this->request->getUri()->getSegment(4);
$file = $this->insurerStatements->find($file_id);
$file = $this->insurerStatements->find((int)$file_id);
return $this->respond(['dataStatus' => true, 'code' => 200, 'data' => $file['reason']], 200);
}

View File

@ -110,6 +110,13 @@ class RestAuthenticationController extends AdminController
if (isset($employeeData['employee_id']))
{
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($employeeData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after'] ])->setStatusCode(429); // Too Many Requests
}
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - verifyEmployeeWithMobileNumber: Employee verified with ID = " . $employeeData['employee_id']);
log_message('error', ' ');
log_message('error', '************************ POST END ********************************');
@ -217,6 +224,12 @@ class RestAuthenticationController extends AdminController
if (isset($employeeData['employee_id'])) {
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($employeeData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after'] ])->setStatusCode(429); // Too Many Requests
}
$builder = $this->employeeModel
->where('email_corporate', $email)
@ -518,6 +531,12 @@ class RestAuthenticationController extends AdminController
if ($HrData) {
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($HrData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after'] ])->setStatusCode(429); // Too Many Requests
}
$sql = "UPDATE level_contacts SET otp = ? WHERE mobile = ? AND contact_type = 'client' AND is_active = 1";
@ -569,6 +588,12 @@ class RestAuthenticationController extends AdminController
if ($HrData) {
//check the resend otp (with in 60 seconds don't allow another otp to send)
$check = canSendOtp($HrData);
if (!$check['allowed']) {
return $this->respond(['status' => false,'message' => 'OTP already sent. Please wait before retrying.','retry_after_seconds' => $check['retry_after'] ])->setStatusCode(429); // Too Many Requests
}
$sql = "
UPDATE level_contacts
SET otp = ?
@ -919,6 +944,12 @@ class RestAuthenticationController extends AdminController
$mpin = $this->request->getJSON()->new_mpin;
$client_id = $this->request->getJSON()->client_id ?? null;
if($old_mpin == $mpin)
{
$result = ['mpin_verification' => false , 'message' => "New MPIN must be different from the old MPIN"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
// if (isset($mobile_number))
// {
// $employeeData = $this->employeeModel->where('mobile', $mobile_number)->where('mpin', $old_mpin)->where('relationship', 'self')->first();
@ -990,11 +1021,11 @@ class RestAuthenticationController extends AdminController
} else {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMpin: Employee not found in the POST. Wrong MPIN");
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - updateMpin: Employee not found in the POST. Old MPIN is incorrect");
log_message('error', ' ');
log_message('error', ' ************************************* POST END **************************************** ');
log_message('error', ' ');
$result = ['mpin_verification' => false , 'message' => "Wrong Mpin"];
$result = ['mpin_verification' => false , 'message' => "Old MPIN is incorrect"];
return $this->respond(['status' => 'failed','code' => 404,'data' => $result],200);
}
@ -1237,7 +1268,7 @@ class RestAuthenticationController extends AdminController
log_message('error', ' ');
log_message('error', ' ************************************* POST END **************************************** ');
log_message('error', ' ');
return $this->respond(['status' => 'success','code' => 200,'data' => "", 'message' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"], 'is_mpin_skipped' => $employeeData['is_mpin_skipped'], 'is_biometric_enabled' => $employeeData['is_biometric_enabled']],200);
return $this->respond(['status' => 'success','code' => 200,'data' => "", 'message' => "Mpin - exist" , 'Mpin' =>$employeeData["mpin"], 'is_mpin_skipped' => $employeeData['is_mpin_skipped'] ?? 0, 'is_biometric_enabled' => $employeeData['is_biometric_enabled'] ?? 0],200);
} else {
$this->myLogger->logme("error", "REST-AUTH-CONTROLLER - checkMpin: Mpin - not found");
log_message('error', ' ');
@ -2289,4 +2320,53 @@ class RestAuthenticationController extends AdminController
}
}
public function logout()
{
$authHeader = $this->request->getHeaderLine('Authorization');
if (!$authHeader) {
return $this->respond([
'status' => false,
'message' => 'Authorization token missing'
], 401);
}
// Validate JWT (your hardened function)
$result = JWTToken::validateJWT($authHeader);
if ($result['status'] !== true) {
return $this->respond([
'status' => false,
'message' => 'Invalid or expired token'
], 401);
}
$decoded = $result['decoded'];
$userId = $decoded['id'] ?? null;
if (!$userId) {
return $this->respond([
'status' => false,
'message' => 'Invalid token payload'
], 401);
}
// Identify user type
if (isset($decoded['emp_code'])) {
$model = new EmployeeModel();
} else {
$model = new LevelContactModel();
}
// Invalidate token server-side
$model->update($userId, [
'token_time_out' => null
]);
return $this->respond([
'status' => true,
'message' => 'Logged out successfully'
], 200);
}
}

View File

@ -128,7 +128,7 @@ class SalesController extends BaseController
public function updateLead($id)
{
try {
if (!$this->leadModel->find($id)) {
if (!$this->leadModel->find((int)$id)) {
return $this->failNotFound('Lead not found');
}
@ -158,7 +158,7 @@ class SalesController extends BaseController
public function deleteLead($id)
{
try {
if (!$this->leadModel->find($id)) {
if (!$this->leadModel->find((int)$id)) {
return $this->failNotFound('Lead not found');
}
@ -228,7 +228,7 @@ class SalesController extends BaseController
}
$contactId = $this->contactModel->getInsertID();
$contact = $this->contactModel->find($contactId);
$contact = $this->contactModel->find((int)$contactId);
return $this->respondCreated([
'status' => 'success',
@ -247,18 +247,18 @@ class SalesController extends BaseController
public function updateContact($id)
{
try {
if (!$this->contactModel->find($id)) {
if (!$this->contactModel->find((int)$id)) {
return $this->failNotFound('Contact not found');
}
$data = $this->request->getJSON(true);
$data['updated_by'] = $this->getUserId();
if (!$this->contactModel->update($id, $data)) {
if (!$this->contactModel->update((int)$id, $data)) {
return $this->fail($this->contactModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
}
$contact = $this->contactModel->find($id);
$contact = $this->contactModel->find((int)$id);
return $this->respond([
'status' => 'success',
@ -277,11 +277,11 @@ class SalesController extends BaseController
public function deleteContact($id)
{
try {
if (!$this->contactModel->find($id)) {
if (!$this->contactModel->find((int)$id)) {
return $this->failNotFound('Contact not found');
}
$this->contactModel->delete($id);
$this->contactModel->delete((int)$id);
return $this->respondDeleted([
'status' => 'success',
@ -299,7 +299,7 @@ class SalesController extends BaseController
public function setPrimaryContact($id)
{
try {
$contact = $this->contactModel->find($id);
$contact = $this->contactModel->find((int)$id);
if (!$contact) {
return $this->failNotFound('Contact not found');
@ -425,7 +425,7 @@ class SalesController extends BaseController
}
$activityId = $this->activityModel->getInsertID();
$activity = $this->activityModel->find($activityId);
$activity = $this->activityModel->find((int)$activityId);
return $this->respondCreated([
'status' => 'success',
@ -444,7 +444,7 @@ class SalesController extends BaseController
public function updateActivity($id)
{
try {
if (!$this->activityModel->find($id)) {
if (!$this->activityModel->find((int)$id)) {
return $this->failNotFound('Activity not found');
}
@ -455,7 +455,7 @@ class SalesController extends BaseController
return $this->fail($this->activityModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
}
$activity = $this->activityModel->find($id);
$activity = $this->activityModel->find((int)$id);
return $this->respond([
'status' => 'success',
@ -474,7 +474,7 @@ class SalesController extends BaseController
public function completeActivity($id)
{
try {
$activity = $this->activityModel->find($id);
$activity = $this->activityModel->find((int)$id);
if (!$activity) {
return $this->failNotFound('Activity not found');
@ -487,7 +487,7 @@ class SalesController extends BaseController
$data = $this->request->getJSON(true);
$data['updated_by'] = $this->getUserId();
$this->activityModel->completeActivity($id, $data);
$this->activityModel->completeActivity((int)$id, $data);
// Create follow-up activity if requested
if (!empty($data['create_followup']) && $data['create_followup'] === true) {
@ -505,7 +505,7 @@ class SalesController extends BaseController
$this->activityModel->insert($followupData);
}
$updatedActivity = $this->activityModel->find($id);
$updatedActivity = $this->activityModel->find((int)$id);
return $this->respond([
'status' => 'success',
@ -524,11 +524,11 @@ class SalesController extends BaseController
public function deleteActivity($id)
{
try {
if (!$this->activityModel->find($id)) {
if (!$this->activityModel->find((int)$id)) {
return $this->failNotFound('Activity not found');
}
$this->activityModel->delete($id);
$this->activityModel->delete((int)$id);
return $this->respondDeleted([
'status' => 'success',
@ -595,7 +595,7 @@ class SalesController extends BaseController
}
$noteId = $this->noteModel->getInsertID();
$note = $this->noteModel->find($noteId);
$note = $this->noteModel->find((int)$noteId);
return $this->respondCreated([
'status' => 'success',
@ -614,7 +614,7 @@ class SalesController extends BaseController
public function updateNote($id)
{
try {
$note = $this->noteModel->find($id);
$note = $this->noteModel->find((int)$id);
if (!$note) {
return $this->failNotFound('Note not found');
@ -632,7 +632,7 @@ class SalesController extends BaseController
return $this->fail($this->noteModel->errors(), ResponseInterface::HTTP_BAD_REQUEST);
}
$updatedNote = $this->noteModel->find($id);
$updatedNote = $this->noteModel->find((int)$id);
return $this->respond([
'status' => 'success',
@ -651,7 +651,7 @@ class SalesController extends BaseController
public function deleteNote($id)
{
try {
$note = $this->noteModel->find($id);
$note = $this->noteModel->find((int)$id);
if (!$note) {
return $this->failNotFound('Note not found');
@ -662,7 +662,7 @@ class SalesController extends BaseController
return $this->failUnauthorized('You are not authorized to delete this note');
}
$this->noteModel->delete($id);
$this->noteModel->delete((int)$id);
return $this->respondDeleted([
'status' => 'success',

View File

@ -238,7 +238,7 @@ class ThzController extends BaseController
$accManagerId = $this->getAcmIdUsingClientId($clientId ?? null);
$accManager = $this->userModel->find($accManagerId);
$accManager = $this->userModel->find((int)$accManagerId);
if (!empty($result['master'])) {
$notes = $this->thzMasterNotesModel->ticketConversationList($thz_id, $returnType);

View File

@ -1292,8 +1292,9 @@ class TicketController extends BaseController
} elseif ($action == 3) {
$table_id = (int)$this->request->getPost('id');
$sql = "update ticket_mail_template set is_active = 0 where id = $table_id ";
$status = $this->ticketMailTemplateModel->query($sql);
$sql = "update ticket_mail_template set is_active = 0 where id = :table_id: ";
$binds = ['table_id'=>$table_id];
$status = $this->ticketMailTemplateModel->query($sql,$binds);
if ($status) {
return $this->respond(['status' => true], 200);
} else {
@ -1774,11 +1775,12 @@ class TicketController extends BaseController
WHERE
th.ticket_id = $ticket_id
th.ticket_id = :ticket_id:
AND th.is_active = 1
ORDER BY
th.created_at DESC";
$data = $this->ticketHistoryModel->query($sql)->getResultArray();
$binds = ['ticket_id'=>(int)$ticket_id];
$data = $this->ticketHistoryModel->query($sql,$binds)->getResultArray();
// dd(db_connect()->getLastQuery());
$priorityType = $this->priorityType;
$relationshipType = $this->relationshipType;

View File

@ -1144,7 +1144,7 @@ class TicketServiceController extends BaseController
{
//get file name
$file_id = $params['file_id'];
$file = $this->claimDumpFileModel->find($file_id);
$file = $this->claimDumpFileModel->find((int)$file_id);
$this->myLogger->logme('error', "Start the claim dump File Data Validataion with the file id : " . $file_id);
// dd($file);
@ -1329,7 +1329,7 @@ class TicketServiceController extends BaseController
{
//get file name
$file_id = $params['file_id'];
$file = $this->claimDumpFileModel->find($file_id);
$file = $this->claimDumpFileModel->find((int)$file_id);
$this->myLogger->logme('error', "Start the claim dump OnBoard Process with the file id : " . $file_id);
// dd($file);

View File

@ -599,7 +599,7 @@ class UserController extends AdminController
// don't forgot same means just unset the key because partner_staff some UNIQUE KEY sets in table thats why
if ($id) {
$existing = $this->partnerStaffModel->find($id);
$existing = $this->partnerStaffModel->find((int)$id);
if ($existing) {
if ($data['email'] === $existing['email']) { unset($data['email']); }
if ($data['mobile'] === $existing['mobile']) { unset($data['mobile']); }
@ -667,7 +667,7 @@ class UserController extends AdminController
return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400);
}
$staff = $this->partnerStaffModel->find($id);
$staff = $this->partnerStaffModel->find((int)$id);
if (!$staff) {
return $this->response->setJSON(['status' => 'error','message' => 'Staff not found'])->setStatusCode(404);
}
@ -783,7 +783,7 @@ class UserController extends AdminController
return $this->response->setJSON(['status' => 'error', 'message' => 'ID is required'])->setStatusCode(400);
}
$files = $this->partnerManagerIncentiveFileModel->find($id);
$files = $this->partnerManagerIncentiveFileModel->find((int)$id);
if (!$files) {
return $this->response->setJSON(['status' => 'error','message' => 'No Records found'])->setStatusCode(404);
}

156
app/Filters/AclFilter.php Normal file
View File

@ -0,0 +1,156 @@
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Config\Acl;
use App\Libraries\AuthLogout;
class AclFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
// ===================== CLI BYPASS =====================
if (is_cli()) {
return;
}
// ===================== PATH NORMALIZATION =====================
$uri = service('uri');
// Raw path: /PHP828APPS/ruc/nhance/index.php/dashboard/view
$fullPath = '/' . ltrim($uri->getPath(), '/');
// Base path: /PHP828APPS/ruc/nhance
$basePath = rtrim(parse_url(base_url(), PHP_URL_PATH), '/');
// Remove base path
if ($basePath && str_starts_with($fullPath, $basePath)) {
$path = substr($fullPath, strlen($basePath));
} else {
$path = $fullPath;
}
// Remove index.php if present
if (str_starts_with($path, '/index.php')) {
$path = substr($path, strlen('/index.php'));
}
// Normalize
$path = '/' . ltrim($path, '/');
// Fallback
if ($path === '') {
$path = '/';
}
// echo'<br>BASH PATH: ' . base_url();
// echo'<br>ACL RAW PATH: ' . $fullPath;
// echo'<br>ACL BASE PATH: ' . $basePath;
// echo'<br>ACL FINAL PATH: ' . $path;
// ===================== LOAD ACL =====================
$acl = new Acl();
$rules = $acl->rules;
// print_rr($rules);die;
// ===================== MATCH RULE =====================
$matchedRule = null;
foreach ($rules as $pattern => $rule) {
// echo "$pattern".'---------<br>';
if (preg_match($pattern, $path)) {
// echo "matched - $pattern";
$matchedRule = $rule;
break; // FIRST MATCH WINS
}
}
// print_r($matchedRule);//die;
// ===================== NO RULE = DENY =====================
if ($matchedRule === null) {
return $this->deny($path, 'No ACL rule matched');
}
// ===================== PUBLIC ROUTE =====================
if (!empty($matchedRule['public'])) {
return; // ALLOW
}
// ===================== AUTH CHECK =====================
if (!check_session()) {
// For API requests return 401 JSON
if ($request->isAJAX() || str_starts_with($path, '/api') || str_starts_with($path, '/employeeRest')) {
return service('response')
->setStatusCode(401)
->setJSON(['error' => 'Unauthorized Resource Access']);
}
// For web redirect to login
return AuthLogout::logout();
}
// ===================== GET USER CONTEXT =====================
$userRole = check_role(); //
$userTeams = user_team(); // must return array of TEAM IDs
$allowedRoles = $matchedRule['roles'] ?? [];
$allowedTeams = $matchedRule['teams'] ?? [];
// ===================== ROLE FIRST =====================
if (!empty($allowedRoles) && in_array((int)$userRole, $allowedRoles, true)) {
return; // ALLOW
}
// ===================== TEAM FALLBACK =====================
if (!empty($allowedTeams) && is_array($userTeams)) {
foreach ($userTeams as $teamId) {
if (in_array($teamId, $allowedTeams, true)) {
return; // ALLOW
}
}
}
// ===================== DENY =====================
return $this->deny($path, 'Role/Team not permitted');
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// nothing
}
// ===================== DENY HANDLER =====================
protected function deny(string $path, string $reason)
{
log_message('error', 'ACL BLOCKED: {user} {path} - {reason}', [
'user' => session()->get('userid') ?? 'guest',
'path' => $path,
'reason' => $reason,
]);
// API / AJAX → JSON
$request = service('request');
if ($request->isAJAX() || str_starts_with($path, '/api') || str_starts_with($path, '/employeeRest')) {
return service('response')
->setStatusCode(403)
->setJSON([
'error' => 'Forbidden',
'message' => 'You do not have permission to access this resource'
]);
}
$response = service('response');
$response->setStatusCode(403);
$response->setBody(view('errors/404', [
'message' => '403 Access denied - You do not have permission to access this resource'
]));
return $response;
// Web → nice 403 page or simple text
return service('response')
->setStatusCode(403)
->setBody('403 Forbidden - Access denied - You do not have permission to access this resource');
}
}

View File

@ -18,67 +18,120 @@ use App\Models\LevelContactModel;
class AuthJWT implements FilterInterface
{
// public function before(RequestInterface $request, $arguments = null)
// {
// $jwt = $request->getHeader('Authorization');
// if ($jwt) {
// if (JWTToken::validateJWT($jwt)) {
// $data = JWTToken::validateJWT($jwt);
// $data = json_decode($data);
// $id = $data->decoded->id;
// if(isset($data->decoded->emp_code)){
// $model = new EmployeeModel();
// $user_data = $model->where('id', $id)->first();
// if($user_data['token_time_out'] > time()){
// $data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
// $model->update($id, $data);
// return true;
// }else{
// // if($user_data['token_time_out'] != "" && $user_data['token_time_out'] != NULL)
// $data =["token_time_out" => ''];
// $model->update($id, $data);
// header('Content-Type: application/json');
// http_response_code(401);
// // $error = json_encode(["status" => 401, "message" => $data->message]);
// $error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
// echo $error;
// exit;
// }
// }else{
// $model = new LevelContactModel();
// $hr_data = $model->where('id', $id)->first();
// if($hr_data['token_time_out'] > time()){
// $data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
// $model->update($id, $data);
// return true;
// }else{
// $data =["token_time_out" => ''];
// $model->update($id, $data);
// header('Content-Type: application/json');
// http_response_code(401);
// // $error = json_encode(["status" => 401, "message" => $data->message]);
// $error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
// echo $error;
// exit;
// }
// }
// }
// } else {
// header('Content-Type: application/json');
// http_response_code(403);
// $error = json_encode(["status" => 403, "message" => "Access Forbidden!"]);
// echo $error;
// exit();
// }
// }
public function before(RequestInterface $request, $arguments = null)
{
$jwt = $request->getHeader('Authorization');
$authHeader = $request->getHeaderLine('Authorization');
if ($jwt) {
if (JWTToken::validateJWT($jwt)) {
$data = JWTToken::validateJWT($jwt);
$data = json_decode($data);
$id = $data->decoded->id;
if(isset($data->decoded->emp_code)){
$model = new EmployeeModel();
$user_data = $model->where('id', $id)->first();
if($user_data['token_time_out'] > time()){
$data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
$model->update($id, $data);
return true;
}else{
// if($user_data['token_time_out'] != "" && $user_data['token_time_out'] != NULL)
$data =["token_time_out" => ''];
$model->update($id, $data);
header('Content-Type: application/json');
http_response_code(401);
// $error = json_encode(["status" => 401, "message" => $data->message]);
$error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
echo $error;
exit;
}
}else{
$model = new LevelContactModel();
$hr_data = $model->where('id', $id)->first();
if($hr_data['token_time_out'] > time()){
$data =["token_time_out" => time() + getenv('TOKENTIMEOUT') ];
$model->update($id, $data);
return true;
}else{
$data =["token_time_out" => ''];
$model->update($id, $data);
header('Content-Type: application/json');
http_response_code(401);
// $error = json_encode(["status" => 401, "message" => $data->message]);
$error = json_encode(["status" => 401, "message" => "Token is Invalid"]);
echo $error;
exit;
}
}
}
} else {
header('Content-Type: application/json');
http_response_code(403);
$error = json_encode(["status" => 403, "message" => "Access Forbidden!"]);
echo $error;
exit();
if (!$authHeader) {
return $this->reject(403, 'Access Forbidden');
}
$result = JWTToken::validateJWT($authHeader);
if ($result['status'] !== true) {
return $this->reject(401, $result['message']);
}
$decoded = $result['decoded'];
$id = $decoded['id'] ?? null;
if (!$id) {
return $this->reject(401, 'Invalid token payload');
}
if (isset($decoded['emp_code'])) {
$model = new EmployeeModel();
} else {
$model = new LevelContactModel();
$id = $decoded['post_hr_id'] ?? null;
}
$user = $model->find($id);
if (!$user || $user['token_time_out'] <= time()) {
$model->update($id, ['token_time_out' => null]);
return $this->reject(401, 'Token expired');
}
// Refresh sliding expiration
$model->update($id, [
'token_time_out' => time() + getenv('TOKENTIMEOUT')
]);
return true;
}
private function reject(int $code, string $message)
{
return service('response')
->setStatusCode($code)
->setJSON(['status' => $code, 'message' => $message])
->send();
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here after the response is sent

View File

@ -5,13 +5,30 @@ use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Libraries\AuthLogout;
class AuthMVC implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (!check_session() && !check_cookie()) {
return redirect()->to(base_url('/login'));
if (!check_session())
{
return AuthLogout::logout();
}
// if (!check_cookie())
// {
// return AuthLogout::logout();
// }
// Fingerprint validation
$fp = hash('sha256',
$request->getUserAgent()->getAgentString() . '|' . $request->getIPAddress()
);
if (session()->get('fingerprint') !== $fp) {
return AuthLogout::logout();
}
}

View File

@ -143,7 +143,7 @@ class Cors implements FilterInterface
// If wildcard present in configuration, allow any origin
if (in_array('*', $this->allowedOrigins, true)) {
$this->log('Origin allowed: wildcard match', ['origin' => $origin]);
// $this->log('Origin allowed: wildcard match', ['origin' => $origin]);
return true;
}
@ -159,10 +159,10 @@ class Cors implements FilterInterface
// 1. Exact match (including scheme and port)
// Example: https://example.com matches https://example.com
if (strcasecmp($allowed, $origin) === 0) {
$this->log('Origin allowed: exact match', [
'origin' => $origin,
'matched_rule' => $allowed
]);
// $this->log('Origin allowed: exact match', [
// 'origin' => $origin,
// 'matched_rule' => $allowed
// ]);
return true;
}
@ -178,11 +178,11 @@ class Cors implements FilterInterface
// Check if origin host ends with the allowed root domain
if ($originHost === $allowedRoot || str_ends_with($originHost, '.' . $allowedRoot)) {
$this->log('Origin allowed: wildcard subdomain match', [
'origin' => $origin,
'matched_rule' => $allowed,
'origin_host' => $originHost
]);
// $this->log('Origin allowed: wildcard subdomain match', [
// 'origin' => $origin,
// 'matched_rule' => $allowed,
// 'origin_host' => $originHost
// ]);
return true;
}
}
@ -191,11 +191,11 @@ class Cors implements FilterInterface
// Example: example.com matches both http://example.com and https://example.com
else {
if (strcasecmp($allowed, $originHost) === 0) {
$this->log('Origin allowed: host match (scheme-less)', [
'origin' => $origin,
'matched_rule' => $allowed,
'origin_host' => $originHost
]);
// $this->log('Origin allowed: host match (scheme-less)', [
// 'origin' => $origin,
// 'matched_rule' => $allowed,
// 'origin_host' => $originHost
// ]);
return true;
}
}
@ -274,6 +274,7 @@ class Cors implements FilterInterface
// Handle allowed headers
if ($isPreflight) {
$response->setHeader('Access-Control-Allow-Methods', ['OPTIONS']);
// For preflight: respect what the browser is asking for
// The browser sends Access-Control-Request-Headers to ask permission
$requestedHeaders = $request->getHeaderLine('Access-Control-Request-Headers');
@ -320,11 +321,11 @@ class Cors implements FilterInterface
// Preflight is sent by browsers before actual cross-origin requests
// to check if the actual request is safe to send
if ($method === 'OPTIONS') {
$this->log('Preflight request received', [
'origin' => $origin,
'method' => $method,
'uri' => (string) $request->getUri()
]);
// $this->log('Preflight request received', [
// 'origin' => $origin,
// 'method' => $method,
// 'uri' => (string) $request->getUri()
// ]);
// Validate origin - reject if not allowed
if (empty($origin) || !$this->isOriginAllowed($origin)) {
@ -346,10 +347,10 @@ class Cors implements FilterInterface
$response->setStatusCode(204);
$response->setBody('');
$this->log('Preflight approved', [
'origin' => $origin,
'allowed_methods' => $this->allowedMethods
]);
// $this->log('Preflight approved', [
// 'origin' => $origin,
// 'allowed_methods' => $this->allowedMethods
// ]);
return $response;
}
@ -392,10 +393,10 @@ class Cors implements FilterInterface
// Add CORS headers to the response
$this->addCorsHeaders($response, $request, $origin, false);
$this->log('CORS headers added to response', [
'origin' => $origin,
'status' => $response->getStatusCode()
]);
// $this->log('CORS headers added to response', [
// 'origin' => $origin,
// 'status' => $response->getStatusCode()
// ]);
}
/**

View File

@ -32,6 +32,7 @@ class SecurityInputFilter implements FilterInterface
'/<\s*object\b/i',
'/<\s*embed\b/i',
'/<\s*applet\b/i',
'/<\s*img\b/i',
// Image-based execution
'/<\s*img\b[^>]*on\w+/i',

View File

@ -59,7 +59,7 @@ class ChatbotHelper
// $policy_id = 0;
// $relationship ='Father';
$EmployeeModel = new EmployeeModel();
$data = $EmployeeModel->find($emp_id);
$data = $EmployeeModel->find((int)$emp_id);
if(isset($data) && isset($data['email_corporate']))
{
$message = SELF::ReimbursementProcessMailTemplate();

View File

@ -4,24 +4,175 @@ namespace App\Helpers;
class HttpRequestHelper
{
public static function getRequestInfo()
public static function getRequestInfo(): array
{
$request = service('request');
$uaString = $request->getHeaderLine('User-Agent');
// Detect platform & browser using robust fallback logic
[$platform, $browser] = self::detectFromUserAgent($uaString);
$data = [
'ip' => $request->getIPAddress(),
'platform' => $request->getUserAgent()->getPlatform(),
'browser' => ($request->getUserAgent()->getBrowser().' '.$request->getUserAgent()->getVersion()),
'method' => $request->getMethod(),
'endpoint' => $request->uri->getPath(),
'getparams' => $request->uri->getSegments(),
'postparams' => $request->getPost()
'ip' => $request->getIPAddress(),
'platform' => $platform,
'browser' => $browser,
'method' => strtoupper($request->getMethod()),
'endpoint' => $request->uri->getPath(),
'getparams' => json_encode($request->uri->getSegments(), JSON_UNESCAPED_UNICODE),
'postparams' => self::sanitizePostForLog($request->getPost()),
];
$data['method'] = (isset($data['method']) ? strtoupper($data['method']) : $data['method']);
$data['getparams'] = is_array($data['getparams']) ? json_encode($data['getparams']) : $data['getparams'];
$data['postparams'] = is_array($data['postparams']) ? json_encode($data['postparams']) : $data['postparams'];
return $data;
}
public static function add($payload)
{return $payload['a'] + $payload['b'];}
/**
* Detect platform & browser from UA string (reliable fallback)
*/
private static function detectFromUserAgent(string $ua): array
{
$uaLower = strtolower($ua);
// =========================
// PLATFORM DETECTION
// =========================
$platform = 'Unknown';
if (str_contains($uaLower, 'windows nt 11') || str_contains($uaLower, 'windows 11')) {
$platform = 'Windows 11';
} elseif (str_contains($uaLower, 'windows nt 10')) {
$platform = 'Windows 10';
} elseif (str_contains($uaLower, 'windows nt 6.3')) {
$platform = 'Windows 8.1';
} elseif (str_contains($uaLower, 'windows nt 6.2')) {
$platform = 'Windows 8';
} elseif (str_contains($uaLower, 'windows nt 6.1')) {
$platform = 'Windows 7';
} elseif (str_contains($uaLower, 'windows nt 6.0')) {
$platform = 'Windows Vista';
} elseif (str_contains($uaLower, 'windows nt 5.1') || str_contains($uaLower, 'windows xp')) {
$platform = 'Windows XP';
} elseif (str_contains($uaLower, 'android')) {
$platform = 'Android';
} elseif (str_contains($uaLower, 'iphone')) {
$platform = 'iOS (iPhone)';
} elseif (str_contains($uaLower, 'ipad')) {
$platform = 'iOS (iPad)';
} elseif (str_contains($uaLower, 'ipod')) {
$platform = 'iOS (iPod)';
} elseif (str_contains($uaLower, 'mac os') || str_contains($uaLower, 'macintosh')) {
$platform = 'Mac OS';
} elseif (str_contains($uaLower, 'cros')) {
$platform = 'Chrome OS';
} elseif (str_contains($uaLower, 'linux')) {
$platform = 'Linux';
} elseif (str_contains($uaLower, 'freebsd')) {
$platform = 'FreeBSD';
} elseif (str_contains($uaLower, 'openbsd')) {
$platform = 'OpenBSD';
} elseif (str_contains($uaLower, 'netbsd')) {
$platform = 'NetBSD';
} elseif (str_contains($uaLower, 'unix')) {
$platform = 'Unix';
} elseif (str_contains($uaLower, 'symbian')) {
$platform = 'Symbian';
} elseif (str_contains($uaLower, 'blackberry')) {
$platform = 'BlackBerry';
} elseif (str_contains($uaLower, 'tizen')) {
$platform = 'Tizen';
} elseif (str_contains($uaLower, 'webos')) {
$platform = 'WebOS';
} elseif (str_contains($uaLower, 'kaios')) {
$platform = 'KaiOS';
} elseif (str_contains($uaLower, 'harmonyos')) {
$platform = 'HarmonyOS';
} elseif (str_contains($uaLower, 'watchos')) {
$platform = 'watchOS';
} elseif (str_contains($uaLower, 'tv os') || str_contains($uaLower, 'tvos')) {
$platform = 'tvOS';
}
// =========================
// BROWSER / CLIENT DETECTION
// =========================
$browser = 'Unknown';
// Bots & tools first
if (preg_match('/googlebot|bingbot|slurp|duckduckbot|baiduspider|yandexbot|sogou|exabot|facebot|ia_archiver/i', $ua)) {
$browser = 'Search Bot';
} elseif (preg_match('/postman/i', $ua)) {
$browser = 'Postman';
} elseif (preg_match('/insomnia/i', $ua)) {
$browser = 'Insomnia';
} elseif (preg_match('/curl/i', $ua)) {
$browser = 'curl';
} elseif (preg_match('/wget/i', $ua)) {
$browser = 'wget';
}
// Real browsers
elseif (preg_match('/edg\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Edge ' . $m[1];
} elseif (preg_match('/opr\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Opera ' . $m[1];
} elseif (preg_match('/vivaldi\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Vivaldi ' . $m[1];
} elseif (preg_match('/brave\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Brave ' . $m[1];
} elseif (preg_match('/chrome\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Chrome ' . $m[1];
} elseif (preg_match('/firefox\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Firefox ' . $m[1];
} elseif (preg_match('/safari\/([\d\.]+)/i', $ua, $m)) {
$browser = 'Safari ' . $m[1];
} elseif (preg_match('/msie\s([\d\.]+)/i', $ua, $m) || preg_match('/trident\/.*rv:([\d\.]+)/i', $ua, $m)) {
$browser = 'Internet Explorer ' . $m[1];
}
// In-app browsers
elseif (preg_match('/fbav|fban/i', $ua)) {
$browser = 'Facebook In-App Browser';
} elseif (preg_match('/instagram/i', $ua)) {
$browser = 'Instagram In-App Browser';
} elseif (preg_match('/linkedinapp/i', $ua)) {
$browser = 'LinkedIn In-App Browser';
} elseif (preg_match('/twitter/i', $ua)) {
$browser = 'Twitter/X In-App Browser';
}
return [$platform, $browser];
}
/**
* Remove sensitive fields before logging POST
*/
private static function sanitizePostForLog(array $post): string
{
if (empty($post)) {
return json_encode([]);
}
$sensitiveKeys = [
'password', 'pass', 'pwd',
'token', 'access_token', 'refresh_token',
'secret', 'api_key', 'authorization',
'otp', 'pin'
];
foreach ($post as $k => $v) {
foreach ($sensitiveKeys as $sk) {
if (stripos($k, $sk) !== false) {
$post[$k] = '***MASKED***';
}
}
}
return json_encode($post, JSON_UNESCAPED_UNICODE);
}
public static function add($payload)
{
return $payload['a'] + $payload['b'];
}
}

View File

@ -18,9 +18,12 @@ use App\Models\LevelContactModel;
class JWTToken
{
private const ALLOWED_ALG = 'HS512';
public static function encode($data =null)
{
$secret_Key ="secret";
$secret_Key = env('JWT_SECRET');
$request_data = (array)$data;
@ -47,30 +50,79 @@ class JWTToken
}
}
public static function validateJWT($jwt)
// public static function validateJWT($jwt)
// {
// $jwtParts = explode(' ', $jwt);
// // print_r($jwtParts);
// if (count($jwtParts) != 2 || $jwtParts[0] == 'Bearer') {
// return false;
// }
// $token = $jwtParts[1];
// try {
// $decoded = JWT::decode($token, new Key(env('JWT_SECRET'), 'HS512'));
// return json_encode(['status' => true, 'message' => 'Token is valid', 'decoded' => (array) $decoded]);
// } catch (ExpiredException $e) {
// return json_encode(['status' => false, 'message' => 'Token has expired']);
// } catch (BeforeValidException $e) {
// return json_encode(['status' => false, 'message' => 'Token is not yet valid']);
// } catch (SignatureInvalidException $e) {
// return json_encode(['status' => false, 'message' => 'Token signature is invalid']);
// } catch (\Exception $e) {
// return json_encode(['status' => false, 'message' => 'An error occurred while decoding the token']);
// }
// }
public static function validateJWT(string $authHeader)
{
$jwtParts = explode(' ', $jwt);
// 1⃣ Validate Authorization header
if (!preg_match('/^Bearer\s(\S+)$/', $authHeader, $matches)) {
return ['status' => false, 'message' => 'Invalid Authorization header'];
}
// print_r($jwtParts);
if (count($jwtParts) != 2 || $jwtParts[0] == 'Bearer') {
return false;
}
$token = $matches[1];
$token = $jwtParts[1];
// 2⃣ Decode JWT header manually
$jwtParts = explode('.', $token);
if (count($jwtParts) !== 3) {
return ['status' => false, 'message' => 'Malformed JWT'];
}
try {
$decoded = JWT::decode($token, new Key("secret", 'HS512'));
return json_encode(['status' => true, 'message' => 'Token is valid', 'decoded' => (array) $decoded]);
} catch (ExpiredException $e) {
return json_encode(['status' => false, 'message' => 'Token has expired']);
} catch (BeforeValidException $e) {
return json_encode(['status' => false, 'message' => 'Token is not yet valid']);
} catch (SignatureInvalidException $e) {
return json_encode(['status' => false, 'message' => 'Token signature is invalid']);
} catch (\Exception $e) {
return json_encode(['status' => false, 'message' => 'An error occurred while decoding the token']);
}
$header = json_decode(base64_decode(strtr($jwtParts[0], '-_', '+/')), true);
// 3⃣ Reject missing or NONE algorithm
if (
empty($header['alg']) ||
$header['alg'] === 'none' ||
$header['alg'] !== self::ALLOWED_ALG
) {
return ['status' => false, 'message' => 'Invalid or unsupported JWT algorithm'];
}
// 4⃣ Enforce signature validation
try {
$decoded = JWT::decode(
$token,
new Key(env('JWT_SECRET'), self::ALLOWED_ALG)
);
return [
'status' => true,
'decoded' => (array) $decoded
];
} catch (ExpiredException $e) {
return ['status' => false, 'message' => 'Token expired'];
} catch (BeforeValidException $e) {
return ['status' => false, 'message' => 'Token not yet valid'];
} catch (SignatureInvalidException $e) {
return ['status' => false, 'message' => 'Invalid token signature'];
} catch (\Exception $e) {
return ['status' => false, 'message' => 'Token validation failed'];
}
}

View File

@ -1128,7 +1128,7 @@ if (!function_exists('premium_calculation_manager_old')) {
//if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage
if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') {
$insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms['insurer_id']));
$insurer = ($insurer->find((int)$policy_terms['insurer_id']));
if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) {
// $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d');
@ -1535,7 +1535,7 @@ if (!function_exists('premium_calculation_manager')) {
//if curent action is dependent addition OR addition then pull insurer master to set whether add one day from employee date of coverage
if ($emp_data['temp']['action'] == 'DA' || $emp_data['temp']['action'] == 'A') {
$insurer = new InsurerModel();
$insurer = ($insurer->find($policy_terms['insurer_id']));
$insurer = ($insurer->find((int)$policy_terms['insurer_id']));
if (isset($insurer['addition_add_day']) && $insurer['addition_add_day'] == true) {
// $emp_data['policy_details']['date_coverage'] = (new DateTime($emp_data['policy_details']['date_coverage']))->modify('+1 day')->format('Y-m-d');
@ -2000,8 +2000,9 @@ if (!function_exists('get_emp_records_from_audit_history')) {
function get_emp_records_from_audit_history($employee_id)
{
$db = db_connect();
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = $employee_id and table_name = 'employees' and field_name in ('name','dob','gender','mobile','email_corporate','relationship') group by field_name order by id asc";
$res = $db->query($query);
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = :employee_id: and table_name = 'employees' and field_name in ('name','dob','gender','mobile','email_corporate','relationship') group by field_name order by id asc";
$binds = ['employee_id'=>(int)$employee_id];
$res = $db->query($query,$binds);
// echo $db->getLastQuery();
$res = $res->getResultArray();
if (count($res)) {
@ -2019,8 +2020,9 @@ if (!function_exists('get_emp_policy_records_from_audit_history')) {
function get_emp_policy_records_from_audit_history($emp_policy_id)
{
$db = db_connect();
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = $emp_policy_id and table_name = 'employee_polices' and field_name in ('basic_cover_si','premium','gst') group by field_name order by id asc";
$res = $db->query($query);
$query = "SELECT min(id) as id,pk,table_name,field_name,old_value FROM auditing_history where pk = :emp_policy_id: and table_name = 'employee_polices' and field_name in ('basic_cover_si','premium','gst') group by field_name order by id asc";
$binds = ['emp_policy_id'=>(int)$emp_policy_id];
$res = $db->query($query,$binds);
// echo $db->getLastQuery();
$res = $res->getResultArray();
if (count($res)) {

View File

@ -0,0 +1,84 @@
<?php
// use Normalizer;
/**
* High security sanitizer
* - Normalizes unicode
* - Removes control chars
* - Removes null bytes
* - Removes invisible unicode tricks
* - Strips dangerous HTML
* - Prevents polyglot payloads
*/
function sanitizeInputArrayAdvanced(array $data, array $htmlAllowedFields = []): array
{
foreach ($data as $k => $v) {
if (is_array($v)) {
$data[$k] = sanitizeInputArrayAdvanced($v, $htmlAllowedFields);
continue;
}
if (!is_string($v)) {
continue;
}
// 1. Unicode normalization (prevents homoglyph attacks)
if (class_exists('Normalizer')) {
$v = \Normalizer::normalize($v, \Normalizer::FORM_C);
}
// 2. Remove NULL bytes & control chars
$v = preg_replace('/[\x00-\x1F\x7F]/u', '', $v);
// 3. Remove invisible unicode chars (zero width, etc)
$v = preg_replace('/[\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{206F}]/u', '', $v);
// 4. Decode HTML entities (so hidden payloads are exposed)
$v = html_entity_decode($v, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// 5. Trim
$v = trim($v);
// 6. If this field is NOT allowed to contain HTML → strip aggressively
if (!in_array($k, $htmlAllowedFields, true)) {
// Remove all tags
$v = strip_tags($v);
// Kill any leftover JS protocol
$v = preg_replace('/(javascript:|data:|vbscript:)/i', '', $v);
} else {
// This is HTML-allowed field → run HTML sanitizer
$v = sanitizeTrustedHtml($v);
}
$data[$k] = $v;
}
return $data;
}
function sanitizeTrustedHtml(string $html): string
{
// Allowed tags for email templates
$allowedTags = '<p><br><b><strong><i><u><em><ul><ol><li><table><thead><tbody><tr><td><th><a><img><div><span><h1><h2><h3><h4><h5><h6>';
// Strip all other tags
$html = strip_tags($html, $allowedTags);
// Remove event handlers like onclick, onerror, etc
$html = preg_replace('/\son\w+="[^"]*"/i', '', $html);
$html = preg_replace("/\son\w+='[^']*'/i", '', $html);
// Remove javascript: and data:
$html = preg_replace('/(javascript:|vbscript:|data:)/i', '', $html);
// Remove iframe, object, embed even if sneaked in
$html = preg_replace('/<(iframe|object|embed|script|style)[^>]*>.*?<\/\1>/is', '', $html);
return $html;
}

View File

@ -21,7 +21,7 @@ if(!function_exists('check_cookie')){
'userProfile' => $value['userProfile'],
'user_team' => $user_team,
];
set_session_data($session_data);
// set_session_data($session_data);
// $this->getUserDeviceInfo($user->id, 'NhanceUser');
// return redirect()->to(base_url('/dashboard/view'));
return true;
@ -33,6 +33,7 @@ if(!function_exists('check_cookie')){
}else{
return false;
}
}
}
if (!function_exists('check_session')) {
@ -40,7 +41,7 @@ if (!function_exists('check_session')) {
{
// $ci =& get_instance();
$session = \Config\Services::session();
return $session->get('isLoggedIn');
return $session->get('isLoggedIn') === true;
}
}
@ -117,7 +118,8 @@ if (!function_exists('check_role')) {
{
// $ci =& get_instance();
$session = \Config\Services::session();
return $session->get('role');
return $role_id = isset(get_session_userdata()->role) ? get_session_userdata()->role : null;
}
}
@ -201,7 +203,6 @@ if (!function_exists('get_chatbot_session_info')) {
}
}

View File

@ -979,6 +979,32 @@ if (!function_exists('generate_ecard_download_link_based_on_tpa')) {
}
}
if (!function_exists('canSendOtp')) {
function canSendOtp(array $row, int $limitSeconds = 60): array
{
// If OTP does not exist → allow
if (empty($row['otp']) || empty($row['updated_at'])) {
return ['allowed' => true];
}
$lastUpdated = strtotime($row['updated_at']);
$currentTime = time();
// Calculate expiry time
$allowedAfter = $lastUpdated + $limitSeconds;
// If still within limit → block
if ($currentTime < $allowedAfter) {
return [
'allowed' => false,
'retry_after' => $allowedAfter - $currentTime
];
}
return ['allowed' => true];
}
}
if (!function_exists('checkDuplicateClaim')) {
function checkDuplicateClaim(array $params): bool

View File

@ -0,0 +1,42 @@
<?php
namespace App\Libraries;
use CodeIgniter\HTTP\RedirectResponse;
class AuthLogout
{
public static function logout(): RedirectResponse
{
$session = session();
// Regenerate session ID (kills fixation)
$session->regenerate(true);
// Destroy CI session
$session->destroy();
// Kill PHP session cookie safely
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(
session_name(), // DO NOT hardcode cookie name
null,
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
session_write_close();
// Redirect with anti-cache headers
return redirect()->to(base_url('login'))
->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
->setHeader('Pragma', 'no-cache')
->setHeader('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT');
}
}

View File

@ -409,15 +409,16 @@ class ClientPolicyModel extends Model
JOIN (
SELECT MAX(id) AS max_id
FROM cash_deposit
WHERE is_active = 1 AND client_id = $id
WHERE is_active = 1 AND client_id = :id:
GROUP BY insurer_id, cd_ac_pk
) latest ON latest.max_id = cd.id
JOIN insurers on cd.insurer_id = insurers.id
WHERE cd.is_active = 1 AND cd.client_id = $id AND cdm.is_active = 1
WHERE cd.is_active = 1 AND cd.client_id = :id: AND cdm.is_active = 1
ORDER BY cd.insurer_id;
";
return $this->db->query($sql)->getResult();
$binds = ['id'=>(int)$id];
return $this->db->query($sql,$binds)->getResult();
}
@ -464,10 +465,12 @@ class ClientPolicyModel extends Model
FROM client_policy
JOIN policies ON policies.id = client_policy.policy_id
JOIN policy_type ON policy_type.id = policies.policy_type_id
WHERE policy_type.policy_type = '{$type}'
AND client_policy.client_id = {$client_id}";
WHERE policy_type.policy_type = :type:
AND client_policy.client_id = :client_id:";
$result = $this->db->query($query)->getResult();
$binds = ['type' =>$type,'client_id'=>(int)$client_id];
$result = $this->db->query($query,$binds)->getResult();
return $result;
}

View File

@ -94,10 +94,11 @@ class EmpEndorsementModel extends Model
FROM emp_endorsement
JOIN employee_polices ON employee_polices.id = emp_endorsement.pk
JOIN client_policy ON client_policy.id = employee_polices.client_policy_id
WHERE group_key = '{$group_key}'
WHERE group_key = :group_key:
";
$results = $this->db->query($query)->getResult();
$binds['group_key'] = $group_key;
$results = $this->db->query($query,$binds)->getResult();
return $results;
}
@ -191,10 +192,10 @@ class EmpEndorsementModel extends Model
e1.field_name = 'status'
) ee ON aa.emp_code = ee.emp_code
) AS deletiondata ON a.emp_code = deletiondata.emp_code
WHERE group_key = '{$group_key}';
WHERE group_key = :group_key: ;
";
$results = $this->db->query($query)->getResult();
$binds['group_key'] = $group_key;
$results = $this->db->query($query,$binds)->getResult();
return $results;
}

View File

@ -223,12 +223,13 @@ class EmployeeModel extends Model
emp_code,
COUNT(*) AS family_member_count,
MAX(TIMESTAMPDIFF(YEAR, dob, CURDATE())) AS max_age
FROM employees where emp_code = '{$emp_code}'
FROM employees where emp_code = :emp_code:
GROUP BY emp_code
) AS family_stats
ORDER BY family_member_count DESC, max_age DESC
LIMIT 1;";
$results = $this->db->query($query)->getResultArray();
$binds['emp_code'] = $emp_code;
$results = $this->db->query($query,$binds)->getResultArray();
return $results;
}

View File

@ -430,7 +430,7 @@ class EmployeePolicyModel extends Model
employees.gender AS emp_gender,
employees.relationship AS emp_relationship,
employees.relationship_code AS emp_relationship_code,
'$datas' as event_type_data,
:datas: as event_type_data,
employees.change_event AS change_event,
@ -483,24 +483,30 @@ class EmployeePolicyModel extends Model
batch_files.batch_code as bf
FROM batch_files
LEFT JOIN batch_list ON batch_files.batch_code = batch_list.batch_code
WHERE batch_files.event_type = '{$event}'
WHERE batch_files.event_type = :event:
AND batch_files.actions = 'export'
AND batch_files.insurer_or_tpa = '{$insurer_or_tpa}'
AND batch_files.client_policy_id = '{$client_policy_id}'
AND batch_files.client_policy_id = '{$client_id}'
AND batch_files.insurer_or_tpa = :insurer_or_tpa:
AND batch_files.client_policy_id = :client_policy_id:
AND batch_files.client_policy_id = :client_id:
) as batch_data ON employee_polices.id = batch_data.emp_policy_id
WHERE employee_polices.client_policy_id = '{$client_policy_id}'
AND (employee_polices.{$id} IS NULL OR employee_polices.{$id} = '')
AND employees.client_branch_id = '{$client_branch_id}'
WHERE employee_polices.client_policy_id = :client_policy_id:
AND (employee_polices.:id: IS NULL OR employee_polices.:id: = '')
AND employees.client_branch_id = :client_branch_id:
AND employee_polices.is_active = 1
AND employee_polices.status = 'active'
AND employees.is_active = 1
AND employees.emp_status = 'active'
";
$binds = ["datas" => $datas,"event" => $event
,"insurer_or_tpa" => $insurer_or_tpa
,"client_policy_id" => $client_policy_id
,"client_branch_id" => $client_branch_id
,"client_id" => $client_id,"id" => $id];
// Get the result set
$query = $this->db->query($sql);
$query = $this->db->query($sql,$binds);
if($return_type == 1){
$results = $query->getResultArray();
@ -573,9 +579,9 @@ class EmployeePolicyModel extends Model
employees ON employees.id = emp_endorsement.pk
LEFT JOIN
employee_polices ON employees.id = employee_polices.employee_id
WHERE employees.client_id = '{$client_id}'
AND employee_polices.client_policy_id = '{$client_policy_id}'
AND employees.client_branch_id = '{$client_branch_id}'
WHERE employees.client_id = :client_id:
AND employee_polices.client_policy_id = :client_policy_id:
AND employees.client_branch_id = :client_branch_id:
AND emp_endorsement.actions = 'c'
AND emp_endorsement.status != 'truncated'
AND emp_endorsement.is_active = 1
@ -585,8 +591,10 @@ class EmployeePolicyModel extends Model
AND employees.emp_status = 'active'
$endorsement_condition";
$binds = ["client_policy_id" => $client_policy_id,"client_branch_id" => $client_branch_id,"client_id" => $client_id];
// Execute the raw query
$query = $this->db->query($sql);
$query = $this->db->query($sql,$binds);
// Get the result set
if($return_type == 1){
@ -1284,12 +1292,12 @@ class EmployeePolicyModel extends Model
(
SELECT employees.id
FROM employees
WHERE client_id = '$client_id'
AND client_branch_id = '$client_branch_id'
WHERE client_id = :client_id:
AND client_branch_id = :client_branch_id:
AND is_active = 1
AND emp_status = 'active'
AND emp_code = '$emp_code'
AND name = '$emp_name'
AND emp_code = :emp_code:
AND name = :emp_name:
LIMIT 1
) AS employees_id,
@ -1318,10 +1326,10 @@ class EmployeePolicyModel extends Model
JOIN employee_polices AS ep ON ep.id = ee.pk
JOIN employees AS e ON e.emp_code = ee.emp_code
WHERE
ee.emp_code = '$emp_code'
AND ep.client_policy_id = '$client_policy_id'
AND e.client_branch_id = '$client_branch_id'
AND ee.name = '$emp_name'
ee.emp_code = :emp_code:
AND ep.client_policy_id = :client_policy_id:
AND e.client_branch_id = :client_branch_id:
AND ee.name = :emp_name:
AND ee.field_name IN ('date_of_exit', 'reason_for_exit', 'status', 'claim_status')
AND ep.is_active = 1
AND ep.status = 'active'
@ -1331,10 +1339,15 @@ class EmployeePolicyModel extends Model
ee.group_key
";
$binds = ['client_policy_id' => $client_policy_id,
'client_branch_id' => $client_branch_id,
'client_id' => $client_id,
'emp_name' => $emp_name,
'emp_code' => $emp_code];
// dd($sql);
// Execute the raw SQL query
$query = $this->db->query($sql);
$query = $this->db->query($sql,$binds);
// Fetch and return results
$row = $query->getRowArray();
@ -1358,12 +1371,12 @@ class EmployeePolicyModel extends Model
$query = "UPDATE employee_polices
SET employee_polices.basic_cover_si = '{$basic_cover_si}'
, employee_polices.premium = '{$premium}'
WHERE employee_polices.employee_id = '{$employee_id}'
AND employee_polices.client_policy_id = '{$client_policy_id}'";
$this->query($query);
SET employee_polices.basic_cover_si = :basic_cover_si:
, employee_polices.premium = :premium:
WHERE employee_polices.employee_id = :employee_id:
AND employee_polices.client_policy_id = :client_policy_id:";
$binds = ["client_policy_id"=>$client_policy_id, "employee_id"=>$employee_id,"basic_cover_si"=>$basic_cover_si,"premium"=>$premium];
$this->query($query,$binds);
}

View File

@ -67,7 +67,7 @@ class PolicesModel extends Model
{
$grid_id = $value['policy_grid_id'];
$policyGridModel = new PolicyGridModel();
$grid_type = $policyGridModel->find($grid_id);
$grid_type = $policyGridModel->find((int)$grid_id);
$premium_slab_data[$key]['grid_master'] = $grid_type;
}
$premium_slab_data[$key]['grid_master'] = $grid_type;
@ -78,7 +78,7 @@ class PolicesModel extends Model
{
$additional_grid_id = $additional_premium_slab_data[0]['policy_grid_id'];
$policyGridModel = new PolicyGridModel();
$additional_grid_type = $policyGridModel->find($additional_grid_id);
$additional_grid_type = $policyGridModel->find((int)$additional_grid_id);
}

View File

@ -2421,12 +2421,13 @@
$sql1 = $builder2->getCompiledSelect();
$sql2 = $builder->getCompiledSelect();
$finalSql = "($sql1) UNION ALL ($sql2)
$finalSql = "(:sql1:) UNION ALL (:sql2:)
ORDER BY policy_no DESC, insurer_branch_name ASC, statement_uploaded ASC,
STR_TO_DATE(policy_issue_month, '%b %Y') ASC";
$result = $this->db->query($finalSql)->getResultArray();
$binds = ['sql1'=>$sql1,'sql2'=>$sql1];
$result = $this->db->query($finalSql,$binds)->getResultArray();
// dd($this->db->getLastQuery());
return $result;
}

View File

@ -85,7 +85,6 @@ class ThzMasterNotesModel extends Model
$ticketTypeFilter = "AND thz_master_notes.notes_type = 'External' ";
}
$integer_ticket_id = (int)$thz_id;
$notes_sql = "SELECT
thz_master_notes.*,
@ -103,11 +102,12 @@ class ThzMasterNotesModel extends Model
LEFT JOIN thz_master
ON thz_master.thz_id = thz_master_notes.thz_id
AND LOWER(thz_master_notes.notes_by) = 'user'
WHERE thz_master_notes.thz_id = ". $integer_ticket_id ."
WHERE thz_master_notes.thz_id = :integerTicketId:
$ticketTypeFilter
ORDER BY thz_master_notes.created_at DESC";
$result = $this->db->query($notes_sql)->getResultArray();
$binds = ["integerTicketId" => (int)$thz_id];
$result = $this->db->query($notes_sql,$binds)->getResultArray();
return $result;
}

View File

@ -589,15 +589,17 @@ class TicketMasterModel extends Model
{
$ticket_type_data_1 = "";
$ticket_type_data_2 = "";
$statusBinds = [];
if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
$ticket_type_data_1 = "AND ticket_type = :policy_type:";
$ticket_type_data_2 = "AND master.ticket_type_id = :policy_type:";
$statusBinds['policy_type'] = $policy_type;
}
// Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray();
$statusResult = $this->db->query($statusQuery, $statusBinds)->getResultArray();
// Initialize dynamic query parts
$dynamicSelect = '';
@ -649,7 +651,7 @@ class TicketMasterModel extends Model
JOIN
tpa ON master.tpa_id = tpa.id AND tpa.is_active = 1
WHERE
master.created_at BETWEEN '$start_date' AND '$end_date'
master.created_at BETWEEN :start_date: AND :end_date:
AND master.is_active = 1
$ticket_type_data_2
GROUP BY
@ -657,7 +659,8 @@ class TicketMasterModel extends Model
";
// Execute the query
$result = $this->db->query($sql)->getResultArray();
$binds = ["start_date"=>$start_date,"end_date"=>$end_date];
$result = $this->db->query($sql, $binds)->getResultArray();
// print_rr($result);die();
return $result;
@ -669,15 +672,17 @@ class TicketMasterModel extends Model
if ($policy_type == 1) {
$ticket_type_data_1 = "";
$ticket_type_data_2 = "";
$statusBinds = [];
if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = :policy_type:";
$ticket_type_data_2 = "AND master.ticket_type_id = :policy_type:";
$statusBinds['policy_type'] = $policy_type;
}
// Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray();
$statusResult = $this->db->query($statusQuery,$statusBinds)->getResultArray();
// Initialize dynamic query parts
$dynamicSelect = '';
@ -712,28 +717,31 @@ class TicketMasterModel extends Model
JOIN
user_profiles ON master.acm_id = user_profiles.id AND user_profiles.is_active = 1
WHERE
master.created_at BETWEEN '$start_date' AND '$end_date'
master.created_at BETWEEN :start_date: AND :end_date:
AND master.is_active = 1
$ticket_type_data_2
GROUP BY
user_profiles.id;
";
$result = $this->db->query($sql)->getResultArray();
$binds = ["start_date"=>$start_date,"end_date"=>$end_date];
$result = $this->db->query($sql,$binds)->getResultArray();
return $result;
} else {
$ticket_type_data_1 = "";
$ticket_type_data_2 = "";
$statusBinds = [];
if (!empty($policy_type)) {
$ticket_type_data_1 = "AND ticket_type = $policy_type";
$ticket_type_data_2 = "AND master.ticket_type_id = $policy_type";
$ticket_type_data_1 = "AND ticket_type = :policy_type:";
$ticket_type_data_2 = "AND master.ticket_type_id = :policy_type:";
$statusBinds['policy_type'] = $policy_type;
}
// Fetch claim statuses dynamically
$statusQuery = "SELECT id, claim_status FROM ticket_claim_status WHERE is_active = 1 $ticket_type_data_1";
$statusResult = $this->db->query($statusQuery)->getResultArray();
$statusResult = $this->db->query($statusQuery,$statusBinds)->getResultArray();
// Initialize dynamic query parts
$dynamicSelect = '';
@ -783,15 +791,16 @@ class TicketMasterModel extends Model
JOIN
user_profiles ON master.acm_id = user_profiles.id AND user_profiles.is_active = 1
WHERE
master.created_at BETWEEN '$start_date' AND '$end_date'
master.created_at BETWEEN :start_date: AND :end_date:
AND master.is_active = 1
$ticket_type_data_2
GROUP BY
user_profiles.id;
";
$binds = ["start_date"=>$start_date,"end_date"=>$end_date];
// Execute the query
$result = $this->db->query($sql)->getResultArray();
$result = $this->db->query($sql,$binds)->getResultArray();
return $result;
@ -992,13 +1001,13 @@ class TicketMasterModel extends Model
$sql = " SELECT cp.policy_terms
FROM ticket_master tm
JOIN client_policy cp ON cp.id = tm.client_policy_id
WHERE tm.id = ?
WHERE tm.id = :ticket_id:
AND tm.is_active = 1
AND cp.is_active = 1
";
$binds = [$ticket_id];
$query = $this->db->query($sql, $binds);
$binds = ["ticket_id"=>$ticket_id];
$query = $this->db->query($sql,$binds);
if ($query && $query->getNumRows() > 0) {
$row = $query->getRowArray();

View File

@ -162,7 +162,7 @@
<body>
<section>
<div class="container">
<div class="text">
<div class="text" style="text-align: center;">
<h1><?= isset($message) && !empty($message) ? $message : '404 PAGE NOT FOUND' ?></h1>
</div>
<div><img class="image" src="https://omjsblog.files.wordpress.com/2023/07/errorimg.png" alt=""></div>

View File

@ -18,7 +18,7 @@ Options -Indexes
AddHandler cgi-script .php .pl .py .jsp .asp .sh .cgi
# Block access to any script-like files entirely
<FilesMatch "\.(php|php5|php7|phtml|pl|py|cgi|asp|aspx|sh|rb)$">
<FilesMatch "\.(php|php5|php7|phtml|pl|py|cgi|ap|aspx|sh|rb)$">
ForceType text/plain
#Order allow,deny
Deny from all