Files

205 lines
8.2 KiB
PHP

<?php
// Must be first — ensures any fatal/exception outputs a JSON body, not HTML.
// Errors still go to the server log; display is suppressed so they cannot
// corrupt the JSON response body.
ini_set('display_errors', 0);
ini_set('log_errors', 1);
header('Content-Type: application/json; charset=utf-8');
// Last-resort handler for exceptions an engine does not catch itself. Many
// engines call a manager with no try/catch, so any exception — including the
// managers' own deliberate validation messages — used to end as a PHP fatal
// with an empty 500 body, which the browser could only report as "Server
// error occurred." This mirrors the convention the catching engines already
// use: a manager's Exception carries a user-facing message (400); a database
// or engine fault stays generic (500) and goes to the server log.
set_exception_handler(function (Throwable $e) {
while (ob_get_level() > 0) ob_end_clean();
if (!headers_sent()) header('Content-Type: application/json; charset=utf-8');
if ($e instanceof PDOException) {
error_log('Uncaught PDOException: ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());
http_response_code(500);
$message = 'Database error, please try again.';
} elseif ($e instanceof Exception) {
http_response_code(400);
$message = $e->getMessage();
} else {
// Error / TypeError: a programming fault, not something to show users.
error_log('Uncaught ' . get_class($e) . ': ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine());
http_response_code(500);
$message = 'Server error occurred.';
}
echo json_encode(['success' => 0, 'message' => $message]);
});
require_once __DIR__."/../../config.php";
require_once __DIR__."/../../dbconn.php";
require_once __DIR__."/db_helpers.php";
require_once __DIR__."/app_access.php";
if (!function_exists('require_role')) {
function require_role(string $user_role, array $allowed): void {
if (!in_array($user_role, $allowed, true)) {
http_response_code(403);
exit(json_encode(['success' => 0, 'message' => 'Access denied.']));
}
}
}
if(!empty($_SESSION["login_company_id"])){
// CSRF Validation — add right at the top of the logged-in block
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$csrf_token = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if(empty($csrf_token) || !hash_equals((string)($_SESSION['csrf_token'] ?? ''), $csrf_token)){
http_response_code(403);
exit(json_encode(["message" => "Invalid request"]));
}
}
// validate otp
$sql = "SELECT `password`, license, app_access
FROM user
WHERE user_id = :company_id";
$sth = $pdo1->prepare($sql);
$sth->execute([
":company_id" => $_SESSION["login_user_id"]
]);
db_check($sth, $answer);
$user_row = $sth->fetch(PDO::FETCH_ASSOC) ?: [];
$password = $user_row['password'] ?? '';
/** Generate OTP */
function generateOTP($sercet_key, $time_step = 180, $length = 6){
$counter = floor($_SESSION["otpTime"] / $time_step);
$data = pack("NN", 0, $counter);
$hash = hash_hmac('sha1', $data, $sercet_key, true);
$offset = ord(substr($hash, -1)) & 0x0F;
$value = unpack("N", substr($hash, $offset, 4));
$otp = ($value[1] & 0x7FFFFFFF) % pow(10, $length);
return str_pad(strval($otp), $length, '0', STR_PAD_LEFT);
}
$otp = generateOTP($password);
if( $_SESSION["otp"]!=$otp ){
http_response_code(401);
$answer["message"] = "Your password has been reset, Please logout and login again.";
$answer["code"] = "password_changed";
exit(json_encode($answer));
}
// check company accessibily
$sql = "SELECT * FROM company_map_user WHERE company_id = :login_company_id and user_id = :login_user_id";
$sth = $pdo1->prepare($sql);
$sth->execute([
":login_company_id" => $_SESSION["login_company_id"],
":login_user_id" => $_SESSION["login_user_id"]
]);
db_check($sth, $answer);
$map = $sth->fetchAll(PDO::FETCH_ASSOC);
if( count($map)==0 ){
http_response_code(403);
$answer["message"] = "Your accessibility to this company has been removed.";
$answer["code"] = "access_removed";
exit(json_encode($answer));
}
$user_role = $map[0]['role'] ?? 'viewer';
$_SESSION['login_role'] = $user_role;
// App access (WMS / Accounting), re-read on every request so a change made in
// Setting → Users applies at once. Owners hold it on their own user row;
// invited users per company (same rule as login_confirm.php).
$app_access = (($user_row['license'] ?? 'owner') === 'owner')
? ($user_row['app_access'] ?? 'wms')
: ($map[0]['app_access'] ?? 'wms');
$_SESSION['login_app_access'] = $app_access;
$required_app = app_access_app_for($_SERVER['SCRIPT_NAME'] ?? '');
if ($required_app !== null && !app_access_allows($app_access, $required_app)) {
http_response_code(403);
exit(json_encode(['success' => 0, 'message' => 'Your account does not have access to this module.']));
}
// Single-session enforcement: if a session_token was issued at login, verify
// it still matches the DB. A mismatch means a newer login has taken over.
if (!empty($_SESSION['session_token'])) {
$sth = $pdo1->prepare("SELECT session_token FROM user WHERE user_id = :uid LIMIT 1");
$sth->execute([':uid' => $_SESSION['login_user_id']]);
$db_token = $sth->fetchColumn();
if ($db_token !== $_SESSION['session_token']) {
session_destroy();
http_response_code(401);
exit(json_encode(['success' => 0, 'message' => 'You have been signed in from another device.', 'code' => 'signed_elsewhere']));
}
// Keep session_last_seen fresh (throttled: at most one DB write per 60 s).
// login_confirm.php reads this to detect when PHP GC has expired the session.
if (!isset($_SESSION['_last_seen_updated']) || (time() - $_SESSION['_last_seen_updated']) > 60) {
$pdo1->prepare("UPDATE user SET session_last_seen = NOW() WHERE user_id = :uid AND session_token = :tok")
->execute([':uid' => $_SESSION['login_user_id'], ':tok' => $_SESSION['session_token']]);
$_SESSION['_last_seen_updated'] = time();
}
}
}
// Fail closed — reject any request that arrives without an authenticated session
// unless the engine explicitly declared itself a pre-auth route.
if (empty($_SESSION['login_company_id']) && !defined('UNAUTHENTICATED_ROUTE')) {
http_response_code(401);
$expired = !empty($_SESSION['_idle_expired']);
exit(json_encode([
'success' => 0,
'message' => $expired ? 'Your session has expired. Please sign in again.' : 'Authentication required.',
'code' => $expired ? 'session_expired' : 'auth_required',
]));
}
// set up ANSWER
$answer = array("success"=>0, "message"=>"");
if (isset($_POST['json'])) {
// Old Method: Data is wrapped in a JSON string
$data = json_decode($_POST['json'], true);
if (!is_array($data)) {
// An undecodable payload used to carry on as an empty request.
http_response_code(400);
$answer["message"] = "The request could not be read. Please reload the page and try again.";
exit(json_encode($answer));
}
} else if (isset($_POST['otp'])) {
// New Method: Data is sent directly (FormData)
// We check for 'otp' because every request should have one
$data = $_POST;
} else {
// Truly no data received
http_response_code(400);
$answer["message"] = "Request denied: No valid JSON payload or Form Data detected.";
exit(json_encode($answer));
}
// incase logging in
if(!empty($_SESSION["login_company_id"])){
$company_id = (int)$_SESSION["login_company_id"];
$user_id = (int)$_SESSION["login_user_id"];
$user_role = $_SESSION['login_role'] ?? ($user_role ?? 'viewer');
$uuid = bin2hex(random_bytes(16));
// create json for table logging
$logging = array(
"user_id" => $user_id,
"data" => json_encode($data),
"dt" => date('Y-m-d H:i:s'),
"login" => date('Y-m-d H:i:s', $_SESSION["otpTime"])
);
}
?>