From 3a9d39da38ef960c0bf296bb93dbc0524b6d0d13 Mon Sep 17 00:00:00 2001 From: Pinga <121483313+getpinga@users.noreply.github.com> Date: Thu, 16 Nov 2023 11:00:02 +0200 Subject: [PATCH] User rights fixes; cleanup --- cp/app/Lib/Logger.php | 12 ++- cp/bin/createModel.php | 95 ------------------- cp/bin/installDB.php | 72 --------------- cp/bin/swoole.php | 203 ----------------------------------------- cp/bootstrap/app.php | 18 ++-- cp/env-sample | 2 +- cp/logs/errors.log | 0 cp/routes/web.php | 15 +-- 8 files changed, 29 insertions(+), 388 deletions(-) delete mode 100644 cp/bin/createModel.php delete mode 100644 cp/bin/installDB.php delete mode 100644 cp/bin/swoole.php delete mode 100644 cp/logs/errors.log diff --git a/cp/app/Lib/Logger.php b/cp/app/Lib/Logger.php index 3d5d23f..d4b6e0a 100644 --- a/cp/app/Lib/Logger.php +++ b/cp/app/Lib/Logger.php @@ -1,4 +1,6 @@ - "{$LOG_PATH}/{$key}.log", 'logLevel' => \Monolog\Logger::DEBUG @@ -54,7 +56,7 @@ class Logger extends \Monolog\Logger public static function systemLogs($enable = true) { - $LOG_PATH = '/tmp/slim'; + $LOG_PATH = '/var/log/namingo'; $appEnv = envi('APP_ENV') ?? 'local'; if($enable) { @@ -63,7 +65,7 @@ class Logger extends \Monolog\Logger }else { // Error Log to file self::$loggers['error'] = new Logger('errors'); - self::$loggers['error']->pushHandler(new StreamHandler("{$LOG_PATH}/errors.log")); + self::$loggers['error']->pushHandler(new StreamHandler("{$LOG_PATH}/cp.log")); ErrorHandler::register(self::$loggers['error']); } } @@ -76,4 +78,4 @@ class Logger extends \Monolog\Logger $run->pushHandler(new PrettyPageHandler); $run->register(); } -} +} \ No newline at end of file diff --git a/cp/bin/createModel.php b/cp/bin/createModel.php deleted file mode 100644 index a822384..0000000 --- a/cp/bin/createModel.php +++ /dev/null @@ -1,95 +0,0 @@ -select('DESCRIBE ' . $tableName); - -// Create the class name based on the table name (e.g. "users" -> "User") -$className = ucwords($tableName, '_'); - -// Generate the necessary lists outside of the heredoc -$columnFieldsList = implode(', ', array_map(function ($column) { - return $column['Field']; -}, $columnData)); - -$columnValuesList = implode(', ', array_map(function ($column) { - return '$' . $column['Field']; -}, $columnData)); - -$quotedColumnValuesList = implode(', ', array_map(function ($column) { - return '$' . $column['Field'] . ' = $this->db->quote($' . $column['Field'] . ');'; -}, $columnData)); - -$setColumnsList = implode(', ', array_map(function ($column) { - return $column['Field'] . ' = $' . $column['Field']; -}, $columnData)); - -// Generate the PHP code for the CRUD model based on the column data -$modelCode = <<db = \$db; - } - - public function getAll{$className}() - { - return \$this->db->select('SELECT * FROM $tableName'); - } - - public function get{$className}ById(\$id) - { - return \$this->db->select('SELECT * FROM $tableName WHERE id = ?', [\$id])->fetch(); - } - - public function create{$className}($columnValuesList) - { - $quotedColumnValuesList - - \$this->db->insert('INSERT INTO $tableName ($columnFieldsList) VALUES ($columnValuesList)'); - - return \$this->db->lastInsertId(); - } - - public function update{$className}(\$id, $columnValuesList) - { - $quotedColumnValuesList - - \$this->db->update('UPDATE $tableName SET $setColumnsList WHERE id = ?', [\$id]); - - return true; - } - - public function delete{$className}(\$id) - { - \$this->db->delete('DELETE FROM $tableName WHERE id = ?', [\$id]); - return true; - } -} -PHP; - -// Save the generated PHP code to a file -file_put_contents(__DIR__ . "/../app/Models/$className.php", $modelCode); - -// Output a success message -echo "CRUD model for table '$tableName' generated successfully.\n"; \ No newline at end of file diff --git a/cp/bin/installDB.php b/cp/bin/installDB.php deleted file mode 100644 index c94b44b..0000000 --- a/cp/bin/installDB.php +++ /dev/null @@ -1,72 +0,0 @@ -setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - // New database details - $newDatabaseName = 'new_database_name'; - $newDatabaseUsername = 'new_database_username'; - $newDatabasePassword = 'new_database_password'; - - // Create new database - if ($dbType == 'mysql') { - $pdo->exec("CREATE DATABASE `$newDatabaseName`"); - } elseif ($dbType == 'postgresql') { - $pdo->exec("CREATE DATABASE $newDatabaseName"); - } elseif ($dbType == 'sqlite') { - $pdo->exec("CREATE DATABASE $newDatabaseName"); - } - echo "Created new database '$newDatabaseName'\n"; - - // Create new user with access to the new database - if ($dbType == 'mysql') { - $pdo->exec("CREATE USER '$newDatabaseUsername'@'localhost' IDENTIFIED BY '$newDatabasePassword'"); - $pdo->exec("GRANT ALL PRIVILEGES ON `$newDatabaseName`.* TO '$newDatabaseUsername'@'localhost'"); - } elseif ($dbType == 'postgresql') { - $pdo->exec("CREATE USER $newDatabaseUsername WITH PASSWORD '$newDatabasePassword'"); - $pdo->exec("GRANT ALL PRIVILEGES ON DATABASE $newDatabaseName TO $newDatabaseUsername"); - } elseif ($dbType == 'sqlite') { - // SQLite doesn't have users and privileges, so skip this step - } - echo "Created new user '$newDatabaseUsername'\n"; - echo "Granted all privileges to user '$newDatabaseUsername' on database '$newDatabaseName'\n"; - - // Connect to the new database as the new user - if ($dbType == 'mysql') { - $pdo = new PDO("mysql:host=$host;dbname=$newDatabaseName", $newDatabaseUsername, $newDatabasePassword); - } elseif ($dbType == 'postgresql') { - $pdo = new PDO("pgsql:host=$host;dbname=$newDatabaseName", $newDatabaseUsername, $newDatabasePassword); - } elseif ($dbType == 'sqlite') { - $pdo = new PDO("sqlite:$newDatabaseName"); - } - $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - // Path to SQL file to import - $sqlFile = '/path/to/sql/file.sql'; - - // Import SQL file - $sql = file_get_contents($sqlFile); - $pdo->exec($sql); - echo "Imported SQL file '$sqlFile' into database '$newDatabaseName'\n"; - -} catch (PDOException $e) { - echo $e->getMessage(); -} diff --git a/cp/bin/swoole.php b/cp/bin/swoole.php deleted file mode 100644 index 94f7721..0000000 --- a/cp/bin/swoole.php +++ /dev/null @@ -1,203 +0,0 @@ -load(); -} catch (\Dotenv\Exception\InvalidPathException $e) { - // -} -//Enable error display in details when APP_ENV=local -if(envi('APP_ENV')=='local') { - Logger::systemLogs(true); -}else{ - Logger::systemLogs(false); -} - -$container = new Container(); -// Set container to create App with on AppFactory -AppFactory::setContainer($container); - -/** - * Create your slim app - */ -$app = AppFactory::create(); - -$responseFactory = $app->getResponseFactory(); - -$routeCollector = $app->getRouteCollector(); -$routeCollector->setDefaultInvocationStrategy(new RequestResponseArgs()); -$routeParser = $app->getRouteCollector()->getRouteParser(); - -require_once __DIR__ . '/../bootstrap/database.php'; - -$container->set('router', function () use ($routeParser) { - return $routeParser; -}); - -$container->set('db', function () use ($db) { - return $db; -}); - -$container->set('pdo', function () use ($pdo) { - return $pdo; -}); - -$container->set('auth', function() { - return new \App\Auth\Auth; -}); - -$container->set('flash', function() { - return new \Slim\Flash\Messages; -}); - -$container->set('view', function ($container) { - $view = Twig::create(__DIR__ . '/../resources/views', [ - 'cache' => false, - ]); - $view->getEnvironment()->addGlobal('auth', [ - 'isLogin' => $container->get('auth')->isLogin(), - 'user' => $container->get('auth')->user(), - ]); - $view->getEnvironment()->addGlobal('flash', $container->get('flash')); - $view->getEnvironment()->addGlobal('screen_mode', $_SESSION['_screen_mode']); - - //route - $route = new TwigFunction('route', function ($name) { - return route($name); - }); - $view->getEnvironment()->addFunction($route); - - // Define the route_is function - $routeIs = new \Twig\TwigFunction('route_is', function ($routeName) { - return strpos($_SERVER['REQUEST_URI'], $routeName) !== false; - }); - $view->getEnvironment()->addFunction($routeIs); - - //assets - $assets = new TwigFunction('assets', function ($location) { - return assets($location); - }); - $view->getEnvironment()->addFunction($assets); - - //Pagination - $pagination = new TwigFunction("links", function ($object) { - - }); - $view->getEnvironment()->addFunction($pagination); - - return $view; -}); -$app->add(TwigMiddleware::createFromContainer($app)); - -$container->set('validator', function ($container) { - return new App\Lib\Validator; -}); - -$container->set('csrf', function($container) use ($responseFactory) { - return new Guard($responseFactory); -}); - -$app->add(new \App\Middleware\ValidationErrorsMiddleware($container)); -$app->add(new \App\Middleware\OldInputMiddleware($container)); -$app->add(new \App\Middleware\CsrfViewMiddleware($container)); - - - -$app->add('csrf'); -$app->setBasePath(routePath()); - -$uriFactory = new Psr17Factory; -$streamFactory = new Psr17Factory; -//$responseFactory = new Psr17Factory; -$uploadedFileFactory = new Psr17Factory; -$responseMerger = new ResponseMerger; - -$app->add(new StaticFileMiddleware( - $responseFactory, - $streamFactory, - __DIR__ . '/../public' -)); - -require __DIR__ . '/../routes/web.php'; - - -$http = new Swoole\Http\Server("0.0.0.0", 3000); -$http->set([ - 'worker_num' => swoole_cpu_num() * 2, - 'enable_coroutine' => true, - 'log_file' => '/tmp/sw' -]); - - - -$http->on( - 'request', - function ( - Request $swooleRequest, - Response $swooleResponse - ) use ( - $uriFactory, - $streamFactory, - $uploadedFileFactory, - $responseFactory, - $responseMerger, - $app - ) { - /** - * create psr request from swoole request - */ - $psrRequest = new PsrRequest( - $swooleRequest, - $uriFactory, - $streamFactory, - $uploadedFileFactory - ); - - // Check if the request path matches a static file path - if (preg_match('#^/assets/.*#', $psrRequest->getUri()->getPath())) { - // If the request path matches a static file path, pass the request off to the StaticFile middleware - $psrResponse = $app->handle($psrRequest, new Response()); - } else { - // If the request path does not match a static file path, process the request with Slim - $psrResponse = $app->handle($psrRequest); - } - - /** - * merge your psr response with swoole response - */ - $response = $responseMerger->toSwoole( - $psrResponse, - $swooleResponse - ); - - if ($response->isWritable()) { - $response->end(); - } else { - // throw a generic exception - throw new RuntimeException('HTTP response is not available'); - } - } -); - -$http->start(); diff --git a/cp/bootstrap/app.php b/cp/bootstrap/app.php index 4d0d1dc..e0fd135 100644 --- a/cp/bootstrap/app.php +++ b/cp/bootstrap/app.php @@ -114,19 +114,25 @@ $container->set('view', function ($container) use ($translations, $uiLang, $lang } $db = $container->get('db'); - $query = 'SELECT r.currency + $query = 'SELECT r.currency, ru.registrar_id FROM registrar_users ru - JOIN registrar r ON ru.registrar_id = r.id + JOIN registrar r ON ru.registrar_id = r.id WHERE ru.user_id = ?'; if (isset($_SESSION['auth_user_id'])) { $result = $db->select($query, [$_SESSION['auth_user_id']]); - // Default value for currency - $_SESSION['_currency'] = 'USD'; + // Default values + $_SESSION['_currency'] = 'USD'; + $_SESSION['auth_registrar_id'] = null; // Default registrar_id - if ($result !== null && isset($result[0]['currency'])) { - $_SESSION['_currency'] = $result[0]['currency']; + if ($result !== null && count($result) > 0) { + if (isset($result[0]['currency'])) { + $_SESSION['_currency'] = $result[0]['currency']; + } + if (isset($result[0]['registrar_id'])) { + $_SESSION['auth_registrar_id'] = $result[0]['registrar_id']; + } } } diff --git a/cp/env-sample b/cp/env-sample index 0acb3cc..ecd7c51 100644 --- a/cp/env-sample +++ b/cp/env-sample @@ -1,4 +1,4 @@ -APP_NAME='StarterApp' +APP_NAME='CP' APP_ENV=public APP_URL=http://localhost diff --git a/cp/logs/errors.log b/cp/logs/errors.log deleted file mode 100644 index e69de29..0000000 diff --git a/cp/routes/web.php b/cp/routes/web.php index 3af57f2..2dc6713 100644 --- a/cp/routes/web.php +++ b/cp/routes/web.php @@ -130,11 +130,12 @@ $app->any('/api[/{params:.*}]', function ( 'dbAuth.passwordColumn' => 'password', 'dbAuth.returnedColumns' => 'email,roles_mask', 'dbAuth.registerUser' => false, - 'multiTenancy.handler' => function ($operation, $tableName) { + 'multiTenancy.handler' => function ($operation, $tableName) { if (isset($_SESSION['auth_roles']) && $_SESSION['auth_roles'] === 0) { return []; } - $userId = $_SESSION['auth_user_id']; + $registrarId = $_SESSION['auth_registrar_id']; + $columnMap = [ 'contact' => 'clid', 'domain' => 'clid', @@ -143,11 +144,13 @@ $app->any('/api[/{params:.*}]', function ( 'registrar' => 'id', 'payment_history' => 'registrar_id', 'statement' => 'registrar_id', - 'support_tickets' => 'user_id', + 'support_tickets' => 'user_id', // Note: this still uses user_id ]; if (array_key_exists($tableName, $columnMap)) { - return [$columnMap[$tableName] => $userId]; + // Use registrarId for tables where 'registrar_id' is the filter + // For 'support_tickets', continue to use userId + return [$columnMap[$tableName] => ($tableName === 'support_tickets' ? $_SESSION['auth_user_id'] : $registrarId)]; } return ['1' => '0']; @@ -188,13 +191,13 @@ $app->any('/log-api[/{params:.*}]', function ( if (isset($_SESSION['auth_roles']) && $_SESSION['auth_roles'] === 0) { return []; } - $userId = $_SESSION['auth_user_id']; + $registrarId = $_SESSION['auth_registrar_id']; $columnMap = [ 'transaction_identifier' => 'registrar_id', ]; if (array_key_exists($tableName, $columnMap)) { - return [$columnMap[$tableName] => $userId]; + return [$columnMap[$tableName] => $registrarId]; } return ['1' => '0'];