helpers.php000064400000007407150247310640006731 0ustar00getInputHandler()->value($index, $defaultValue, ...$methods); } return request()->getInputHandler(); } /** * @param string $url * @param int|null $code */ function redirect(string $url, ?int $code = null): void { if ($code !== null) { response()->httpCode($code); } response()->redirect($url); } /** * Get current csrf-token * @return string|null */ function csrf_token(): ?string { $baseVerifier = Router::router()->getCsrfVerifier(); if ($baseVerifier !== null) { return $baseVerifier->getTokenProvider()->getToken(); } return null; } //Custom Helpers /** * Flatten the array * @return array|null */ function array_flatten(array $array) { $return = array(); array_walk_recursive($array, function ($a) use (&$return) { $return[] = $a; }); return $return; } /** * Get data from .env * @return string */ function env($key, $value = null) { if ($value) { $_ENV[$key] = $value; } return $_ENV[$key]; } /** * Given a valid file location (it must be an path starting with "/"), i.e. "/css/style.css", * it returns a string containing the file's mtime as query string, i.e. "/css/style.css?v=0123456789". * Otherwise, it returns the file location. * * @param $file the file to be loaded. */ // function auto_version($file) // { // // if it is not a valid path (example: a CDN url) // if (strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; // // retrieving the file modification time // // https://www.php.net/manual/en/function.filemtime.php // $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); // return sprintf("%s?v=%d", $file, $mtime); // } function asset_version($file) { // if it is not a valid path (example: a CDN url) if (strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; return sprintf("%s?v=%s", $file, env('ASSETS_VERSION')); } function escape($string) { return htmlspecialchars($string, ENT_QUOTES, 'UTF-8'); // return htmlspecialchars($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); // return htmlentities($string, ENT_QUOTES | ENT_HTML5, 'UTF-8'); } function config($config) { return (object) include('../config/' . $config . '.php'); } Utilities/Token.php000064400000000257150247310640010316 0ustar00getUser(array(Session::get('uid'))); foreach ($response as $key => $value) { $this->{$key} = $value; } } } public static function check() { if (!empty(Session::get('uid'))) { return true; } return false; } public static function user() { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } } Utilities/Hash.php000064400000000425150247310640010116 0ustar00Utilities/Uuid.php000064400000001126150247310640010140 0ustar00selectBaseQuery($sql); // return $result; } public static function short() { return rUuid::uuid4(); // $sql = "SELECT UUID_SHORT()"; // $db_handle = new \App\Core\Database; // $result = $db_handle->selectBaseQuery($sql); // return $result; } } Utilities/Utility.php000064400000010455150247310640010702 0ustar00 $value) { if (is_array($value)) { $array[$key] = self::nullEmptyArray($value); } if (empty($value) && !strlen($value)) { $array[$key] = NULL; } } return $array; } public static function emptyNullArray($array) { foreach ($array as $key => $value) { if (is_array($value)) { $array[$key] = self::emptyNullArray($value); } if ($value === null) { $array[$key] = ""; } } return $array; } public static function toUpperCase($data) { if (is_array($data)) { foreach ($data as $key => $value) { if (is_array($value)) { $data[$key] = self::toUpperCase($value); } else { $data[$key] = strtoupper($data[$key]); } } return $data; } else { return strtoupper($data); } } public static function includeFiles($directory) { if (is_dir($directory)) { $scan = scandir($directory); unset($scan[0], $scan[1]); //unset . and .. foreach ($scan as $file) { if (is_dir($directory . "/" . $file)) { self::includeFiles($directory . "/" . $file); } else { if (strpos($file, '.php') !== false) { include_once($directory . "/" . $file); } } } } } public static function numberFormat($number) { return number_format($number, 2, '.', ','); } public static function clientIP() { return isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']); } public static function clientUserAgent() { if (empty($_SERVER['HTTP_USER_AGENT'])) { return null; } return $_SERVER['HTTP_USER_AGENT']; } public static function curl($array_data) { if (empty($array_data['uri'])) { return "No uri"; } $ch = \curl_init(); curl_setopt($ch, CURLOPT_URL, $array_data['uri']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, empty($array_data['parameters']) ? null : $array_data['parameters']); if (!empty($array_data['header']) > 0) { curl_setopt($ch, CURLOPT_HTTPHEADER, $array_data['header']); } return curl_exec($ch); } public static function escapeString($string) { $strArr = array("data" => $string); $jsonArr = json_encode($strArr); return json_decode($jsonArr['data'], true); } public static function cleanString($data) { if (is_array($data)) { foreach ($data as $key => $value) { if (is_array($value)) { $data[$key] = self::cleanString($value); } else { $data[$key] = self::removeNonAscii(self::removeExtraSpace(trim($data[$key]))); } } return $data; } else { return self::removeNonAscii(self::removeExtraSpace(trim($data))); } } public static function removeNonAscii($string) { return preg_replace('/[^\r\n[:print:]]/', '', $string); // return preg_replace('/[\x00-\x1F\x7F\xA0]/u', '', $string); bedt // return preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $string); } public static function removeExtraSpace($data) { // return preg_replace('/\s+/', ' ', $data); return preg_replace('/\h+/', ' ', $data); // return preg_replace('/\x20+/', ' ', $data); } } Utilities/Session.php000064400000002114150247310640010653 0ustar00 $value) { $_SESSION[$row] = $value; } return; } /** * Get session * * @param $name * @return mixed */ public static function get($name) { if (isset($_SESSION[$name])) { return $_SESSION[$name]; } } /** * Check session * * @param $name * @return bool */ public static function exists($name) { return isset($_SESSION[$name]); } /** * Delete session * * @param $name */ public static function delete($name) { unset($_SESSION[$name]); } public static function destroy() { if (session_status() == PHP_SESSION_ACTIVE) { session_destroy(); } } } ?>Utilities/Cookie.php000064400000004263150247310640010450 0ustar00 */ class Cookie { /** * Delete: * @access public * @param string $key * @return void */ public static function delete($key) { if (self::exists($key)) { setcookie($key, '', time() - 1, '/'); } } /** * Exists: * @access public * @param string $key * @return boolean */ public static function exists($key): bool { return isset($_COOKIE[$key]); } /** * Get: Returns the value of a specific key of the COOKIE super-global * @access public * @param string $key * @return string */ public static function get($key): string { if (self::exists($key)) { return $_COOKIE[$key]; } else { return ''; } } /** * Put: * @access public * @param string $key * @param string $value * @param integer $expiry * @return boolean */ public static function put($name, $value, $expire, $path, $samesite = "", $secure = false, $httponly = false): bool { // return setcookie($key, $value, time() + $data, '/'); // if (PHP_VERSION_ID < 70300) { // return setcookie($name, $value, time() + $expire, $path, $domain, $secure, $httponly); // } // return setcookie($name, $value, [ // 'expires' => $expire, // 'path' => $path, // 'domain' => $domain, // 'samesite' => $samesite, // 'secure' => $secure, // 'httponly' => $httponly, // ]); // return setcookie('cookie_name', 'cookie_value', time() + 60 * 60 * 24 * 30, '/; SameSite=strict'); $arr_cookie_options = array( 'expires' => time() + $expire, 'path' => $path, // 'domain' => 'ecom.test', // leading dot for compatibility or use subdomain 'secure' => $secure, // or false 'httponly' => $httponly, // or false 'samesite' => $samesite // None || Lax || Strict ); return setcookie($name, $value, $arr_cookie_options); } } Handlers/CustomExceptionHandler.php000064400000002165150247310640013452 0ustar00getUrl()->contains('/api')) { response()->json([ 'error' => $error->getMessage(), 'code' => $error->getCode(), ]); } /* The router will throw the NotFoundHttpException on 404 */ if($error instanceof NotFoundHttpException) { /* * Render your own custom 404-view, rewrite the request to another route, * or simply return the $request object to ignore the error and continue on rendering the route. * * The code below will make the router render our page.notfound route. */ $request->setRewriteCallback('DefaultController@notFound'); return; } throw $error; } }Core/Model.php000064400000000251150247310640007205 0ustar00db_handle = new \App\Core\Database; // } } ?>Core/View.php000064400000000600150247310640007055 0ustar00query("SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));"); // ini_set('memory_limit', '-1'); } public static function connect() { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } public static function connectDB() { $conn = \mysqli_connect(self::$host, self::$user, self::$password, self::$database); return $conn; } public static function runBaseQuery($query) { $result = self::$conn->query($query); if (self::$conn->error) { return self::$conn->error; } $resultset = []; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset[] = $row; } } return $resultset; } public static function runQuery($query, $param_type, $param_value_array) { $sql = self::$conn->prepare($query); if (self::$conn->error) { return self::$conn->error; } self::bindQueryParams($sql, $param_type, $param_value_array); $sql->execute(); $result = $sql->get_result(); $resultset = []; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset[] = $row; } } return $resultset; } public static function bindQueryParams($sql, $param_type, $param_value_array) { $param_value_reference[] = &$param_type; for ($i = 0; $i < count($param_value_array); $i++) { $param_value_reference[] = &$param_value_array[$i]; } call_user_func_array(array( $sql, 'bind_param' ), $param_value_reference); } public static function insert($query, $param_type, $param_value_array) { $sql = self::$conn->prepare($query); if (self::$conn->error) { return self::$conn->error; } self::bindQueryParams($sql, $param_type, $param_value_array); $sql->execute(); if ($sql->errno) { return $sql->error; } $insertId = $sql->insert_id; return $insertId; } public static function update($query, $param_type, $param_value_array) { $sql = self::$conn->prepare($query); if (self::$conn->error) { return self::$conn->error; } self::bindQueryParams($sql, $param_type, $param_value_array); $sql->execute(); if ($sql->errno) { return $sql->error; } return $sql->affected_rows; } public static function select($query, $param_type, $param_value_array) { $sql = self::$conn->prepare($query); if (self::$conn->error) { return self::$conn->error; } self::bindQueryParams($sql, $param_type, $param_value_array); $sql->execute(); $result = $sql->get_result(); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset[] = $row; foreach ($resultset as $resultsetRow) { foreach ($resultsetRow as $resultsetRowRow) { return $resultsetRowRow; } } } } else { return ''; } } public static function selectBaseQuery($query) { $result = self::$conn->query($query); if (self::$conn->error) { return self::$conn->error; } if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $resultset[] = $row; foreach ($resultset as $resultsetRow) { foreach ($resultsetRow as $resultsetRowRow) { return $resultsetRowRow; } } } } else { return ''; } } public static function insertBaseQuery($query) { $sql = self::$conn->prepare($query); if (self::$conn->error) { return self::$conn->error; } $sql->execute(); if ($sql->errno) { return $sql->error; } $insertId = $sql->insert_id; return $insertId; } public static function updateBaseQuery($query) { $sql = self::$conn->prepare($query); if (self::$conn->error) { return self::$conn->error; } $sql->execute(); if ($sql->errno) { return $sql->error; } return $sql->affected_rows; } // $mysqli->real_escape_string($city)); public static function escape($string) { return self::$conn->real_escape_string($string); // $sql = self::$conn->real_escape_string("asd"); // if (self::$conn->error) { // return self::$conn->error; // } // $sql->real_escape_string("asd"); // if ($sql->errno) { // return $sql->error; // } // return $sql->affected_rows; } } Core/Mail.php000064400000011562150247310640007036 0ustar00json(array("status" => 0, "message" => "No recipient/s.")); } if (empty($array_data['subject'])) { response()->json(array("status" => 0, "message" => "Subject is required.")); } if (empty($array_data['message'])) { response()->json(array("status" => 0, "message" => "Message is required.")); } //clean from if (isset($array_data['from'])) { if (!isset($array_data['from']['email'])) { $array_data['from'] = []; } else { if (!isset($array_data['from']['name'])) { $array_data['from']['name'] = ""; } } } else { $array_data['from'] = []; } //clean reply to if (isset($array_data['reply_to'])) { if (!isset($array_data['reply_to']['email'])) { $array_data['reply_to'] = []; } else { if (!isset($array_data['reply_to']['name'])) { $array_data['reply_to']['name'] = ""; } } } else { $array_data['reply_to'] = []; } //clean recipient/s foreach ($array_data['recipient'] as $key => $value) { if (!isset($value['email'])) { unset($array_data['recipient'][$key]); $array_data['recipient'] = array_values($array_data['recipient']); } } //clean recipient/s name foreach ($array_data['recipient'] as $key => $value) { if (!isset($value['name'])) { $array_data['recipient'][$key]['name'] = ""; } } // // print_r(json_encode($array_data)); // print_r($array_data); // exit; //Create an instance; passing `true` enables exceptions $mail = new PHPMailer(true); try { //Server settings $mail->SMTPDebug = SMTP::DEBUG_OFF; //Enable verbose debug output DEBUG_OFF $mail->isSMTP(); //Send using SMTP $mail->Host = env('MAIL_HOST'); //Set the SMTP server to send through $mail->SMTPAuth = true; //Enable SMTP authentication $mail->Username = env('MAIL_USERNAME'); //SMTP username $mail->Password = env('MAIL_PASSWORD'); //SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption $mail->Port = env('MAIL_PORT');; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` //Recipients if (!empty($array_data['from'])) { $mail->setFrom($array_data['from']['email'], $array_data['from']['name']); } foreach ($array_data['recipient'] as $recipient) { $mail->addAddress($recipient['email'], $recipient['name']); //Add a recipient // $mail->addAddress('ellen@example.com'); //Name is optional } if (!empty($array_data['reply_to'])) { $mail->addReplyTo($array_data['reply_to']['email'], $array_data['reply_to']['name']); } if (!empty($array_data['cc'])) { foreach ($array_data['cc'] as $cc) { $mail->addCC($cc); } } if (!empty($array_data['bcc'])) { foreach ($array_data['bcc'] as $bcc) { $mail->addBCC($bcc); } } //Attachments // $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments // $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name //Content $mail->isHTML(true); //Set email format to HTML $mail->Subject = $array_data['subject']; $mail->Body = $array_data['message']; $mail->AltBody = $array_data['message']; $mail->send(); response()->json(array("status" => 1, "message" => "Message has been sent")); } catch (Exception $e) { response()->json(array("status" => 0, "message" => "Message could not be sent. Mailer Error: {$mail->ErrorInfo}")); } } } Core/Controller.php000064400000000061150247310640010267 0ustar00meow3; $id = null; if (empty(Auth::user()->id)) { $id = session_id(); } else { $id = Auth::user()->id; } echo $id; } } Controllers/QRController.php000064400000003652150247310640012161 0ustar00json(array("status" => 0, "message" => "data parameter is required.")); } $label = input('label') ? input('label') : ''; $image = input('logo') ? config('qr')->logo : config('qr')->no_logo; $result = Builder::create() ->writer(new PngWriter()) ->writerOptions([]) ->data(input('data')) ->encoding(new Encoding('UTF-8')) ->errorCorrectionLevel(new ErrorCorrectionLevelHigh()) ->size(300) ->margin(10) ->roundBlockSizeMode(new RoundBlockSizeModeMargin()) ->logoPath($image) ->labelText($label) ->labelFont(new NotoSans(20)) ->labelAlignment(new LabelAlignmentCenter()) ->build(); // Directly output the QR code header('Content-Type: ' . $result->getMimeType()); if (!empty(input('filename'))) { header("Content-Disposition: inline;filename=" . input('filename') . ".png"); } echo $result->getString(); // Save it to a file // $result->saveToFile(__DIR__ . '/qrcode.png'); // Generate a data URI to include image data inline (i.e. inside an tag) $dataUri = $result->getDataUri(); } } Controllers/PlaceController.php000064400000013443150247310640012662 0ustar00 new ExtJsonDecoder(true)]); // $countries_new = Items::fromFile('../resources/json/place/countries+states+cities.json', ['decoder' => new ExtJsonDecoder(true)]); // foreach ($countries_new as $row) { // $nationality = ""; // $flag = ""; // foreach ($countries_old as $row1) { // if ($row['iso2'] == $row1['iso2']) { // $nationality = $row1['nationality']; // $flag = $row1['flag']; // } // } // $row['flag'] = $flag; // $row['nationality'] = $nationality; // $generated_json = array_merge($generated_json, array($row)); // } // $myfile = fopen("newfile.json", "w") or die("Unable to open file!"); // fwrite($myfile, json_encode($generated_json)); // fclose($myfile); // response()->json($generated_json); // $countries = Items::fromFile('../resources/json/place/countries+states+cities.json', ['pointer' => '/-/states']); // foreach ($countries as $name => $data) { // print_r($data); // } // exit; $countries = Items::fromFile('../resources/json/place/countries+states+cities.json', ['decoder' => new ExtJsonDecoder(true)]); if (!empty(input('country')) && !empty(input('state')) && !empty(input('city'))) { // $countries = Items::fromFile('../resources/json/place/countries+states+cities.json', ['decoder' => new ExtJsonDecoder(true)]); $result = array(); foreach ($countries as $name => $data) { $country_key = null; if (is_numeric(input('country'))) { $country_key = 'id'; } else { $country_key = 'iso2'; } if ($data[$country_key] == input('country')) { foreach ($data['states'] as $stateK => $stateV) { $state_key = null; if (is_numeric(input('state'))) { $state_key = 'id'; } else { $state_key = 'state_code'; } if ($stateV[$state_key] == input('state')) { // response()->json($stateV['cities']); $result = $stateV['cities']; break; } } } } if (count($result)) { $result['status'] = 1; response()->json($result); } else { response()->json(array("status" => 0, "message" => "Country or state not found.")); } } else if (!empty(input('country')) && !empty(input('state'))) { // $countries = Items::fromFile('../resources/json/place/countries+states+cities.json', ['decoder' => new ExtJsonDecoder(true)]); $result = array(); foreach ($countries as $name => $data) { $country_key = null; if (is_numeric(input('country'))) { $country_key = 'id'; } else { $country_key = 'iso2'; } if ($data[$country_key] == input('country')) { foreach ($data['states'] as $stateK => $stateV) { unset($data['states'][$stateK]['cities']); } $result = $data['states']; break; // response()->json($data['states']); } } if (count($result)) { $result['status'] = 1; response()->json($result); } else { response()->json(array("status" => 0, "message" => "Country not found.")); } } else if (!empty(input('country'))) { // $countries = Items::fromFile('../resources/json/place/countries+states+cities.json', ['decoder' => new ExtJsonDecoder(true)]); $result = array(); foreach ($countries as $name => $data) { $country_key = null; if (is_numeric(input('country'))) { $country_key = 'id'; } else { $country_key = 'iso2'; } if ($data[$country_key] == input('country')) { // $data = array_diff_key($data, array_flip(["states"])); unset($data['states']); $result = $data; break; } } if (count($result)) { $result['status'] = 1; response()->json($result); } else { response()->json(array("status" => 0, "message" => "Country not found.")); } } else { // $countries = Items::fromFile('../resources/json/place/countries+states+cities.json', ['decoder' => new ExtJsonDecoder(true)]); $country_arr = array(); foreach ($countries as $key => $value) { unset($value['states']); $country_arr = array_merge($country_arr, array($value)); } response()->json($country_arr); } } } Controllers/BarCodeController.php000064400000001661150247310640013134 0ustar00json(array("status" => 0, "message" => "data parameter is required.")); } $color = [0, 0, 0]; $generator = new \Picqer\Barcode\BarcodeGeneratorPNG(); // file_put_contents('barcode.jpg', $generator->getBarcode(input('data'), $generator::TYPE_CODE_128, 3, 50, $color)); header('Content-Type: image/png'); if (!empty(input('filename'))) { header("Content-Disposition: inline;filename=" . input('filename') . ".png"); } echo $generator->getBarcode(input('data'), $generator::TYPE_CODE_128, 3, 50, $color); // echo ''; } } Controllers/ApiController.php000064400000003172150247310640012345 0ustar00json([ 'authenticated' => request()->authenticated ]); } /** * @return string|null */ public function index(): ?string { return response()->json([ 'method' => 'index' ]); } /** * @return string|null */ public function store(): ?string { return response()->json([ 'method' => 'store' ]); } /** * @return string|null */ public function create(): ?string { return response()->json([ 'method' => 'create' ]); } /** * View * @param mixed $id * @return string|null */ public function edit($id): ?string { return response()->json([ 'method' => sprintf('edit: %s', $id), ]); } /** * @param mixed $id * @return string|null */ public function update($id): ?string { return response()->json([ 'method' => sprintf('update: %s', $id), ]); } /** * @param mixed $id * @return string|null */ public function destroy($id): ?string { return response()->json([ 'method' => sprintf('destroy: %s', $id), ]); } } Controllers/AuthController.php000064400000005447150247310640012544 0ustar00redirect('/'); response()->redirect(url('login')); } public static function login() { } public static function loginIndex() { // $http_referer = escape(input('ref')); View::render('login', get_defined_vars()); } public function loginData() { $email = input('email'); $username = input('username'); $password = input('password'); $remember = input('remember'); $user = new \App\Models\User; $user_data = $user->getUserByEmail(array($email)); $response['status'] = 0; if (!$user_data) { $response['message'] = "User is not registered."; response()->json($response); } if (!Hash::verify($password, $user_data['password'])) { $response['message'] = "Incorrect password."; response()->json($response); } if (!$user_data['status']) { $response['message'] = "Account is disabled."; response()->json($response); } if (!$user_data['active']) { $response['message'] = "Account is not yet verified."; response()->json($response); } if (!$user_data['is_admin']) { $response['message'] = "You do not have admin privileges."; response()->json($response); } //save user session Session::set(['uid' => $user_data['id'], 'agent' => $_SERVER['HTTP_USER_AGENT']]); //save remember cookie $token = Token::generate(); $user->createLoginToken(array($user_data['id'], $token)); if ($remember) { // Cookie::put("uid", $token, (86400 * 30), '/', 'None', env('APP_URL'), false, false); // Cookie::put("uid", $token, (86400 * 30), '/'); Cookie::put("uid", $token, (86400 * 30), '/', 'Strict', false, true); } $user->createLastLoginDate(array($user_data['id'])); $response['id'] = $user_data['id']; $response['ref'] = empty(Cookie::get('ref')) ? url('main') : Cookie::get('ref'); $response['status'] = 1; $response['message'] = "Login successful."; Cookie::delete('ref'); response()->json($response); } } Middlewares/NotAuth.php000064400000000541150247310640011101 0ustar00redirect(url('main')); } } } Middlewares/Admin.php000064400000001146150247310640010551 0ustar00redirect(url('login')); } if (!Auth::user()->is_admin) { response()->redirect(url('user_access')); } } } Middlewares/Token.php000064400000003426150247310640010604 0ustar00id)) { $id = session_id(); } else { $id = Auth::user()->id; } $secretKey = hash_hmac('sha256', $id, env('APP_KEY')); $tokenId = base64_encode(random_bytes(16)); $issuedAt = new \DateTimeImmutable(); $expire = $issuedAt->modify('+30 minutes')->getTimestamp(); // Add 60 seconds $serverName = env('APP_URL'); // Create the token as an array $data = [ 'iat' => $issuedAt->getTimestamp(), // Issued at: time when the token was generated 'jti' => $tokenId, // Json Token Id: an unique identifier for the token 'iss' => $serverName, // Issuer 'nbf' => $issuedAt->getTimestamp(), // Not before 'exp' => $expire, // Expire 'data' => [ // Data related to the signer user 'id' => $id, // User name ] ]; // Encode the array to a JWT string. $jwt = JWT::encode( $data, //Data to be encoded in the JWT $secretKey, // The signing key 'HS512' // Algorithm used to sign the token, see https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40#section-3 ); Cookie::put("Authorization", $jwt, (86400 * 30), '/', 'Strict', false, true); // response()->json(['key' => $jwt]); // echo $jwt; } } Middlewares/Auth.php000064400000002173150247310640010423 0ustar00redirect(url('login')); } //login using cookie if (empty(Session::get('uid')) && !empty(Cookie::get('uid'))) { $user_id = $user->getUserIdBySessionToken(array(Cookie::get('uid'))); $user_data = $user->getUser(array($user_id)); if (empty($user_data)) { response()->redirect(url('logout')); } Session::set(['uid' => $user_data['id'], 'agent' => $_SERVER['HTTP_USER_AGENT']]); } //check user status if (empty($user->getUserStatus(array(Session::get('uid'))))) { response()->redirect(url('logout')); } } } Middlewares/CsrfVerifier.php000064400000000357150247310640012115 0ustar00json(array('status' => 0, "message" => "Parameter (key) is required.")); } $api = new \App\Models\Api(); $api_data = $api->getApi(array(input('key'))); if (empty($api_data)) { response()->json(array('status' => 0, "message" => "Invalid key.")); } $api_access_uri_data = $api->getApiAccessUri(array($api_data['id'], url(null, null, array()))); if (empty($api_access_uri_data)) { response()->json(array('status' => 0, "message" => "Key has no access to this API.")); } $api_log_arr = array( $api_access_uri_data['id'], \App\Utilities\Utility::clientIP(), \App\Utilities\Utility::clientUserAgent(), null, ); $api->createApiLog($api_log_arr); } } Middlewares/TokenVerifier.php000064400000003532150247310640012276 0ustar00authenticated = true; // if (!preg_match('/Bearer\s(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $matches)) { // header('HTTP/1.0 400 Bad Request'); // exit; // } $id = null; if (empty(Auth::user()->id)) { $id = session_id(); } else { $id = Auth::user()->id; } // $jwt = $matches[1]; // Using httponly cookies $jwt = Cookie::get('Authorization'); //$jwt = ""; //debug // echo $jwt; // exit; if (!$jwt) { // No token was able to be extracted from the authorization header header('HTTP/1.0 400 Bad Request'); exit; } $secretKey = hash_hmac('sha256', $id, env('APP_KEY')); //env('APP_KEY'); // $token = JWT::decode((string)$jwt, $secretKey, ['HS512']); try { JWT::$leeway += 60; $token = JWT::decode($jwt, new Key($secretKey, 'HS512')); $now = new \DateTimeImmutable(); $serverName = env('APP_URL'); if ( $token->iss !== $serverName || $token->nbf > $now->getTimestamp() || $token->exp < $now->getTimestamp() || $token->data->id !== $id ) { header('HTTP/1.1 401 Unauthorized'); exit; } } catch (\Exception $e) { header('HTTP/1.1 401 Unauthorized'); exit; } } } Middlewares/ApiVerification1.php000064400000000355150247310640012657 0ustar00authenticated = true; } } Models/User.php000064400000004524150247310640007425 0ustar00runQuery($query, $paramType, $array_data); return count($response) > 0 ? $response[0] : $response; } public function getUserByEmail($array_data) { $query = "SELECT * FROM `users` WHERE 1 AND `email` = ?"; $paramType = "s"; $response = Database::connect()->runQuery($query, $paramType, $array_data); return count($response) > 0 ? $response[0] : $response; } public function getUserByUsername($array_data) { $query = "SELECT * FROM `users` WHERE 1 AND `username` = ?"; $paramType = "s"; $response = Database::connect()->runQuery($query, $paramType, $array_data); return count($response) > 0 ? $response[0] : $response; } public function getUserStatus($array_data) { $query = "SELECT * FROM `users` WHERE 1 AND `id` = ? AND status = 1 AND active = 1"; $paramType = "i"; $response = Database::connect()->runQuery($query, $paramType, $array_data); return count($response) > 0 ? $response[0] : $response; } public function createLoginToken($array_data) { $query = "INSERT INTO `users_login_session_token`(`user_id`, `token`, `updated_at`,`status`) VALUES (?,?,NOW(),1) ON DUPLICATE KEY UPDATE token = VALUES (token), updated_at = VALUES(updated_at), status = VALUES(status) "; $paramType = "is"; $insertId = Database::connect()->insert($query, $paramType, $array_data); return $insertId; } public function createLastLoginDate($array_data) { $query = "UPDATE users SET last_login = NOW() WHERE id = ?"; $paramType = "i"; Database::connect()->update($query, $paramType, $array_data); } public function getUserIdBySessionToken($array_data) { $query = "SELECT user_id FROM users_login_session_token WHERE token = ? AND status = 1"; $paramType = "s"; return Database::connect()->select($query, $paramType, $array_data); } } Models/Api.php000064400000002036150247310640007214 0ustar00runQuery($query, $paramType, $array_data); return count($response) > 0 ? $response[0] : $response; } public function getApiAccessUri($array_data) { $query = "SELECT * FROM api_key_access_uris WHERE 1 AND status = 1 AND api_key_id = ? AND uri = ?"; $paramType = "is"; $response = Database::connect()->runQuery($query, $paramType, $array_data); return count($response) > 0 ? $response[0] : $response; } public function createApiLog($array_data) { $query = "INSERT INTO `api_logs` VALUES (null,?,?,?,?,NOW())"; $paramType = "isss"; $response = Database::connect()->insert($query, $paramType, $array_data); return $response; } } Router.php000064400000002246150247310640006543 0ustar00 \App\Handlers\CustomExceptionHandler::class], function () { // API // Router::group(['prefix' => '/api', 'middleware' => \App\Middlewares\ApiVerification::class], function () { // Router::resource('/demo', 'ApiController'); // }); // Load our custom routes $gfg_folderpath = "../routes/"; \App\Utilities\Utility::includeFiles($gfg_folderpath); }); // Do initial stuff parent::start(); } }