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,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();