User rights fixes; cleanup

This commit is contained in:
Pinga 2023-11-16 11:00:02 +02:00
parent f3f5530642
commit 3a9d39da38
8 changed files with 29 additions and 388 deletions

View file

@ -1,4 +1,6 @@
<?php namespace App\Lib;
<?php
namespace App\Lib;
use Monolog\ErrorHandler;
use Monolog\Handler\StreamHandler;
@ -25,7 +27,7 @@ class Logger extends \Monolog\Logger
parent::__construct($key);
if (empty($config)) {
$LOG_PATH = '/tmp/slim';
$LOG_PATH = '/var/log/namingo';
$config = [
'logFile' => "{$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']);
}
}

View file

@ -1,95 +0,0 @@
<?php
use Pinga\Db\PdoDatabase;
// Include the Delight-IM/db package
require_once __DIR__ . '/../vendor/autoload.php';
// Get the table name from the user input
$tableName = readline('Enter table name: ');
// Connect to the database using the PDO driver
$pdo = new PDO('mysql:host=localhost;dbname=my_database;charset=utf8mb4', 'my_username', 'my_password');
$db = \Pinga\Db\PdoDatabase::fromPdo($pdo);
// Get the column names and types for the specified table
$columnData = $db->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 = <<<PHP
<?php
namespace App\Models;
use Pinga\Db\PdoDatabase;
class $className
{
private PdoDatabase \$db;
public function __construct(PdoDatabase \$db)
{
\$this->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";

View file

@ -1,72 +0,0 @@
<?php
// Database type
$dbType = 'mysql';
// Database credentials
$host = 'localhost';
$username = 'your_mysql_username';
$password = 'your_mysql_password';
try {
// Connect to database
if ($dbType == 'mysql') {
$pdo = new PDO("mysql:host=$host", $username, $password);
} elseif ($dbType == 'postgresql') {
$pdo = new PDO("pgsql:host=$host", $username, $password);
} elseif ($dbType == 'sqlite') {
$pdo = new PDO("sqlite:host=$host");
}
// Set PDO attributes
$pdo->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();
}

View file

@ -1,203 +0,0 @@
<?php
use Imefisto\PsrSwoole\ServerRequest as PsrRequest;
use Imefisto\PsrSwoole\ResponseMerger;
use Nyholm\Psr7\Factory\Psr17Factory;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Chubbyphp\StaticFile\StaticFileMiddleware;
use Psr\Http\Message\StreamFactoryInterface;
use App\Lib\Logger;
use DI\Container;
use Slim\Csrf\Guard;
use Slim\Factory\AppFactory;
use Slim\Handlers\Strategies\RequestResponseArgs;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;
use Twig\TwigFunction;
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../bootstrap/helper.php';
try {
Dotenv\Dotenv::createImmutable(__DIR__. '/../')->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();

View file

@ -114,7 +114,7 @@ $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
WHERE ru.user_id = ?';
@ -122,12 +122,18 @@ $container->set('view', function ($container) use ($translations, $uiLang, $lang
if (isset($_SESSION['auth_user_id'])) {
$result = $db->select($query, [$_SESSION['auth_user_id']]);
// Default value for currency
// Default values
$_SESSION['_currency'] = 'USD';
$_SESSION['auth_registrar_id'] = null; // Default registrar_id
if ($result !== null && isset($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'];
}
}
}
$currency = isset($_SESSION['_currency']) ? $_SESSION['_currency'] : 'USD';

View file

@ -1,4 +1,4 @@
APP_NAME='StarterApp'
APP_NAME='CP'
APP_ENV=public
APP_URL=http://localhost

View file

View file

@ -134,7 +134,8 @@ $app->any('/api[/{params:.*}]', function (
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'];