Skip to content

Commit

Permalink
PUSH
Browse files Browse the repository at this point in the history
-> Time to test redis
  • Loading branch information
NaysKutzu committed Nov 28, 2024
1 parent 289f78d commit b79ff24
Show file tree
Hide file tree
Showing 20 changed files with 368 additions and 91 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"cSpell.words": [
"Predis",
"Swal",
"sweetalert"
]
Expand Down
5 changes: 4 additions & 1 deletion backend/app/Api/User/Auth/Login.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@
$password = $_POST['password'];

$login = User::login($login, $password);

$token = $_COOKIE['user_token'];
if ($login) {
if ($token == "") {
$appInstance->BadRequest('Something behind went wrong!', ['error_code' => 'LOGIC_ERROR']);
}
if (User::getInfo($_COOKIE['user_token'], UserColumns::VERIFIED, false) == 'false') {
if (Mail::isEnabled() == true) {
setcookie('user_token', '', time() - 123600, '/');
Expand Down
30 changes: 30 additions & 0 deletions backend/app/Api/User/Auth/Logout.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php


use MythicalClient\App;
use MythicalClient\Chat\User;
use MythicalClient\Mail\Mail;
use MythicalSystems\CloudFlare\Turnstile;
use MythicalClient\Config\ConfigInterface;
use MythicalSystems\CloudFlare\CloudFlare;
use MythicalClient\Chat\columns\UserColumns;

$router->get('/api/user/auth/logout', function (): void {
echo '<script>
localStorage.clear();
sessionStorage.clear();
</script>';
try {
setcookie('user_token', '', time() - 460800 * 460800 * 460800, '/');
if (session_status() === PHP_SESSION_ACTIVE) {
session_unset();
session_destroy();
}

header('location: /auth/login?href=api');
exit;
} catch (Exception $e) {
App::getInstance(true)->getLogger()->error('Failed to logout user' . $e->getMessage());
header('location: /auth/login?href=api');
}
});
79 changes: 42 additions & 37 deletions backend/app/Api/User/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,20 @@
*/

use MythicalClient\App;
use MythicalClient\Chat\Billing;
use MythicalClient\Chat\User;
use MythicalClient\Chat\Roles;
use MythicalClient\Chat\columns\UserColumns;
use MythicalClient\Chat\Session;

$router->post('/api/user/session', function (): void {
App::init();
$appInstance = App::getInstance(true);
$config = $appInstance->getConfig();

$appInstance->allowOnlyPOST();
$session = new Session($appInstance);

$router->post('/api/user/session/updatebilling', function (): void {

});

Expand All @@ -44,41 +53,37 @@
$config = $appInstance->getConfig();

$appInstance->allowOnlyGET();

if (isset($_COOKIE['user_token']) && $_COOKIE['user_token'] != '') {
$accountToken = $_COOKIE['user_token'];

if (User::exists(UserColumns::ACCOUNT_TOKEN, $accountToken)) {
try {
$appInstance->OK('Account token is valid', ['user_token' => $accountToken, 'user_info' => [
'username' => User::getInfo($accountToken, UserColumns::USERNAME, false),
'email' => User::getInfo($accountToken, UserColumns::EMAIL, false),
'verified' => User::getInfo($accountToken, UserColumns::VERIFIED, false),
'banned' => User::getInfo($accountToken, UserColumns::BANNED, false),
'2fa_blocked' => User::getInfo($accountToken, UserColumns::TWO_FA_BLOCKED, false),
'2fa_enabled' => User::getInfo($accountToken, UserColumns::TWO_FA_ENABLED, false),
'2fa_secret' => User::getInfo($accountToken, UserColumns::TWO_FA_KEY, false),
'first_name' => User::getInfo($accountToken, UserColumns::FIRST_NAME, true),
'last_name' => User::getInfo($accountToken, UserColumns::LAST_NAME, true),
'avatar' => User::getInfo($accountToken, UserColumns::AVATAR, false),
'uuid' => User::getInfo($accountToken, UserColumns::UUID, false),
'role_id' => User::getInfo($accountToken, UserColumns::ROLE_ID, false),
'first_ip' => User::getInfo($accountToken, UserColumns::FIRST_IP, false),
'last_ip' => User::getInfo($accountToken, UserColumns::LAST_IP, false),
'deleted' => User::getInfo($accountToken, UserColumns::DELETED, false),
'last_seen' => User::getInfo($accountToken, UserColumns::LAST_SEEN, false),
'first_seen' => User::getInfo($accountToken, UserColumns::FIRST_SEEN, false),
'background' => User::getInfo($accountToken, UserColumns::BACKGROUND, true),
'role_name' => Roles::getUserRoleName(User::getInfo($accountToken, UserColumns::UUID, false)),
'role_real_name' => Roles::getUserRoleName(User::getInfo($accountToken, UserColumns::UUID, false)),
]]);
} catch (Exception $e) {
$appInstance->BadRequest('Bad Request', ['error_code' => 'INVALID_ACCOUNT_TOKEN', 'error' => $e->getMessage()]);
}
} else {
$appInstance->BadRequest('Bad Request', ['error_code' => 'INVALID_ACCOUNT_TOKEN']);
}
} else {
$appInstance->BadRequest('Bad Request', ['error_code' => 'MISSING_ACCOUNT_TOKEN']);
$session = new Session($appInstance);
$accountToken = $session->SESSION_KEY;
try {
$billing = Billing::getBillingData(User::getInfo($accountToken, UserColumns::UUID, false));
$appInstance->OK('Account token is valid', [
'user_info' => [
'username' => User::getInfo($accountToken, UserColumns::USERNAME, false),
'email' => User::getInfo($accountToken, UserColumns::EMAIL, false),
'verified' => User::getInfo($accountToken, UserColumns::VERIFIED, false),
'banned' => User::getInfo($accountToken, UserColumns::BANNED, false),
'2fa_blocked' => User::getInfo($accountToken, UserColumns::TWO_FA_BLOCKED, false),
'2fa_enabled' => User::getInfo($accountToken, UserColumns::TWO_FA_ENABLED, false),
'2fa_secret' => User::getInfo($accountToken, UserColumns::TWO_FA_KEY, false),
'first_name' => User::getInfo($accountToken, UserColumns::FIRST_NAME, true),
'last_name' => User::getInfo($accountToken, UserColumns::LAST_NAME, true),
'avatar' => User::getInfo($accountToken, UserColumns::AVATAR, false),
'uuid' => User::getInfo($accountToken, UserColumns::UUID, false),
'role_id' => User::getInfo($accountToken, UserColumns::ROLE_ID, false),
'first_ip' => User::getInfo($accountToken, UserColumns::FIRST_IP, false),
'last_ip' => User::getInfo($accountToken, UserColumns::LAST_IP, false),
'deleted' => User::getInfo($accountToken, UserColumns::DELETED, false),
'last_seen' => User::getInfo($accountToken, UserColumns::LAST_SEEN, false),
'first_seen' => User::getInfo($accountToken, UserColumns::FIRST_SEEN, false),
'background' => User::getInfo($accountToken, UserColumns::BACKGROUND, true),
'role_name' => Roles::getUserRoleName(User::getInfo($accountToken, UserColumns::UUID, false)),
'role_real_name' => Roles::getUserRoleName(User::getInfo($accountToken, UserColumns::UUID, false)),
],
'billing' => $billing
]);
} catch (Exception $e) {
$appInstance->BadRequest('Bad Request', ['error_code' => 'INVALID_ACCOUNT_TOKEN', 'error' => $e->getMessage()]);
}

});
14 changes: 13 additions & 1 deletion backend/app/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,23 @@ public function __construct(bool $softBoot)
self::init();
self::InternalServerError($e->getMessage(), null);
}

/**
* Email correction
*/
if ($this->getConfig()->getSetting('app_url', null) == null) {
$this->getConfig()->setSetting('app_url', $_SERVER['HTTP_HOST']);
}

/**
* Redis
*/

$redis = new FastChat\Redis();
if ($redis->testConnection() == false) {
self::init();
self::InternalServerError('Failed to connect to Redis', null);
}

new PluginCompiler();

$router = new rt();
Expand Down
91 changes: 89 additions & 2 deletions backend/app/Chat/Billing.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,95 @@

namespace MythicalClient\Chat;

class Billing extends Database {
use MythicalClient\App;

class Billing extends Database
{
public const TABLE_NAME = "mythicalclient_billing";


public static function updateBilling(
string $uuid,
string|null $company_name,
string|null $vat_number,
string|null $address1,
string|null $address2,
string|null $city,
string|null $country,
string|null $state,
string|null $zip,
): void {
$conn = self::getPdoConnection();
if (self::doesHaveBilling($uuid)) {
$stmt = $conn->prepare("UPDATE " . self::TABLE_NAME . " SET company_name = :company_name, vat_number = :vat_number, address1 = :address1, address2 = :address2, city = :city, country = :country, state = :state, zip = :zip WHERE user = :uuid");
} else {
$stmt = $conn->prepare("INSERT INTO " . self::TABLE_NAME . " (user, company_name, vat_number, address1, address2, city, country, state, zip) VALUES (:uuid, :company_name, :vat_number, :address1, :address2, :city, :country, :state, :zip)");
}
$company_name = $company_name !== null ? App::getInstance(true)->encrypt($company_name) : null;
$vat_number = $vat_number !== null ? App::getInstance(true)->encrypt($vat_number) : null;
$address1 = $address1 !== null ? App::getInstance(true)->encrypt($address1) : null;
$address2 = $address2 !== null ? App::getInstance(true)->encrypt($address2) : null;
$city = $city !== null ? App::getInstance(true)->encrypt($city) : null;
$country = $country !== null ? App::getInstance(true)->encrypt($country) : null;
$state = $state !== null ? App::getInstance(true)->encrypt($state) : null;
$zip = $zip !== null ? App::getInstance(true)->encrypt($zip) : null;

$stmt->execute([
"uuid" => $uuid,
"company_name" => $company_name,
"vat_number" => $vat_number,
"address1" => $address1,
"address2" => $address2,
"city" => $city,
"country" => $country,
"state" => $state,
"zip" => $zip
]);
}

private static function doesHaveBilling(string $uuid): bool
{
$conn = self::getPdoConnection();
$stmt = $conn->prepare("SELECT * FROM " . self::TABLE_NAME . " WHERE user = :uuid");
$stmt->execute([
"uuid" => $uuid
]);
$result = $stmt->fetch();
return $result !== false;
}

public static function getBillingData(string $uuid): array
{
if (!self::doesHaveBilling($uuid)) {
return [
"company_name" => "N/A",
"vat_number" => "N/A",
"address1" => "N/A",
"address2" => "N/A",
"city" => "N/A",
"country" => "N/A",
"state" => "N/A",
"postcode" => "N/A"
];
}
$conn = self::getPdoConnection();
$stmt = $conn->prepare("SELECT * FROM ". self::TABLE_NAME . " WHERE user = :uuid");
$stmt->execute([
"uuid" => $uuid
]);
$result = $stmt->fetch();
if ($result !== false) {
return [
"company_name" => $result['company_name'] !== null ? App::getInstance(true)->decrypt($result['company_name']) : "N/A",
"vat_number" => $result['vat_number'] !== null ? App::getInstance(true)->decrypt($result['vat_number']) : "N/A",
"address1" => $result['address1'] !== null ? App::getInstance(true)->decrypt($result['address1']) : "N/A",
"address2" => $result['address2'] !== null ? App::getInstance(true)->decrypt($result['address2']) : "N/A",
"city" => $result['city'] !== null ? App::getInstance(true)->decrypt($result['city']) : "N/A",
"country" => $result['country'] !== null ? App::getInstance(true)->decrypt($result['country']) :"N/A",
"state" => $result['state'] !== null ? App::getInstance(true)->decrypt($result['state']) : "N/A",
"postcode" => $result['zip'] !== null ? App::getInstance(true)->decrypt($result['zip']) : "N/A"
];
} else {
return [];
}
}
}
11 changes: 8 additions & 3 deletions backend/app/Chat/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

namespace MythicalClient\Chat;

use Exception;
use MythicalClient\App;
use MythicalClient\Chat\columns\UserColumns;

Expand All @@ -46,6 +47,7 @@ public function __construct(App $app)
try {
$this->app = $app;
$this->SESSION_KEY = $_COOKIE['user_token'];
$this->updateLastSeen();
} catch (\Exception) {
$app->Unauthorized('Bad Request', ['error_code' => 'INVALID_ACCOUNT_TOKEN']);
}
Expand Down Expand Up @@ -81,8 +83,11 @@ public function setInfo(string|UserColumns $info, string $value, bool $encrypted

public function updateLastSeen(): void
{
$con = self::getPdoConnection();
$con->exec('UPDATE ' . User::TABLE_NAME . ' SET last_seen = NOW() WHERE user_token = ' . $this->SESSION_KEY);

try {
$con = self::getPdoConnection();
$con->exec('UPDATE ' . User::TABLE_NAME . ' SET last_seen = NOW() WHERE token = "' . $this->SESSION_KEY . '";');
} catch (Exception $e) {
$this->app->getLogger()->error('Failed to update last seen: ' . $e->getMessage());
}
}
}
16 changes: 9 additions & 7 deletions backend/app/Chat/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,12 @@ public static function register(string $username, string $password, string $emai
/**
* GRAvatar Logic.
*/
$gravatar = new Gravatar(['s' => 9001], true);
$avatar = $gravatar->avatar($email);
try {
$gravatar = new Gravatar(['s' => 9001], true);
$avatar = $gravatar->avatar($email);
} catch (\Exception) {
$avatar = 'https://www.gravatar.com/avatar';
}

/**
* Get the PDO connection.
Expand Down Expand Up @@ -201,9 +205,9 @@ public static function login(string $login, string $password): bool
$stmt->bindParam(':login', $login);
$stmt->execute();
$user = $stmt->fetch(\PDO::FETCH_ASSOC);

if ($user) {
if (App::getInstance(true)->decrypt($user['password']) == $password) {
self::logout();
setcookie('user_token', $user['token'], time() + 3600, '/');
if (Mail::isEnabled()) {
try {
Expand All @@ -213,15 +217,13 @@ public static function login(string $login, string $password): bool
}
}
setcookie('user_token', $user['token'], time() + 3600, '/');

return true;
}

return false;
}

return false;
} catch (\Exception $e) {
App::getInstance(true)->getLogger()->error('Failed to login user: ' . $e->getMessage());
return false;
}
}
Expand All @@ -231,7 +233,7 @@ public static function login(string $login, string $password): bool
*/
public static function logout(): void
{
setcookie('user_token', '', time() - 3600, '/');
setcookie('user_token', '', time() - 460800 * 460800 * 460800, '/');
}

/**
Expand Down
39 changes: 39 additions & 0 deletions backend/app/FastChat/Redis.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
namespace MythicalClient\FastChat;

use MythicalClient\App;
use Predis\Client;

class Redis
{
private $redis;
public function __construct()
{
$app = App::getInstance(true);
$app->loadEnv();
$host = $_ENV['REDIS_HOST'];
$pwd = $_ENV['REDIS_PASSWORD'];
$client = new Client([
'scheme' => 'tcp',
'host' => $host,
]);
$this->redis = $client;
}

public function getRedis(): Client
{
return $this->redis;
}

public function testConnection(): bool
{
try {
$redis = $this->getRedis();
$redis->connect();
return $redis->isConnected();
} catch (\Exception $e) {
App::getInstance(true)->getLogger()->error('Failed to connect to Redis: ' . $e->getMessage());
return false;
}
}
}
Loading

0 comments on commit b79ff24

Please sign in to comment.