Skip to content

Commit

Permalink
Use Laravel as new session handler
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelfolaron committed Jun 5, 2024
1 parent 095b3fc commit ce3af40
Show file tree
Hide file tree
Showing 219 changed files with 2,062 additions and 1,726 deletions.
1 change: 1 addition & 0 deletions .idea/leantime-oss.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions .idea/php.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions .idea/phpspec.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 6 additions & 3 deletions app/Core/ApiSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,16 @@ public static function oAuth2Grants(
} else {
$middleware_params[] = new ClientCredentials($client, $creds);
}

if ($usesRefresh) {
$middleware_params[] = new RefreshToken($client, $creds);
}

} else {
$middleware_params[] = $customGrantType;
}

if ($usesRefresh) {
$middleware_params[] = new RefreshToken($client, $creds);
}


$stack = HandlerStack::create();
$oauth = new OAuth2Middleware(...$middleware_params);
Expand Down
5 changes: 4 additions & 1 deletion app/Core/AppSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,14 @@ public function loadSettings(Environment $config = null): void
ini_set('display_errors', 0);
}

/*
if (session_status() !== PHP_SESSION_ACTIVE) {
if (filter_var($config->useRedis, FILTER_VALIDATE_BOOL) && (!defined("LEAN_CLI") || !LEAN_CLI)) {
ini_set('session.save_handler', 'redis');
ini_set('session.save_path', $config->redisUrl);
}
ini_set('session.use_cookies', 1);
//ini_set('session.use_cookies', 1);
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.use_trans_sid', 0);
Expand All @@ -55,6 +56,8 @@ public function loadSettings(Environment $config = null): void
ini_set('session.cache_limiter', '');
}*/

ini_set("log_errors", 1);

if ($config->logPath != '' && $config->logPath != 'null') {
Expand Down
75 changes: 64 additions & 11 deletions app/Core/Bootloader.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Container\Container as IlluminateContainerContract;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Contracts\Http\Kernel as HttpKernelContract;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Facades\Log;
use Leantime\Domain\Auth\Services\Auth as AuthService;
Expand Down Expand Up @@ -136,18 +139,15 @@ public function boot(): void

Events::discover_listeners();

self::dispatch_event('config_initialized');

$app->instance(Session::class, $app->make(Session::class));

self::dispatch_event('session_initialized');

$app = self::dispatch_filter("initialized", $app, ['bootloader' => $this]);

$config = $app->make(Environment::class);

$this->setErrorHandler($config->debug ?? 0);

self::dispatch_event('config_initialized');


$request = $app->make(IncomingRequest::class);

if (! defined('BASE_URL')) {
Expand Down Expand Up @@ -212,18 +212,66 @@ private function registerCoreBindings(): void
$this->app->singleton(ModulemanagerService::class, ModulemanagerService::class);
$this->app->singleton(\Illuminate\Filesystem\Filesystem::class, fn () => new \Illuminate\Filesystem\Filesystem());

$this->app->singleton(\Illuminate\Encryption\Encrypter::class, function ($app) {

$configKey = app()->make(Environment::class)->sessionPassword;

if (strlen($configKey) > 32) {
$configKey = substr($configKey, 0, 32);
}

if (strlen($configKey) < 32) {
$configKey = str_pad($configKey, 32, "x", STR_PAD_BOTH);
}

$app['config']['app_key'] = $configKey;

$encrypter = new \Illuminate\Encryption\Encrypter($app['config']['app_key'], "AES-256-CBC");
return $encrypter;
});

$this->app->singleton(\Illuminate\Session\SessionManager::class, function ($app) {

$app['config']['session'] = array(
'driver' => "file",
'lifetime' => app()->make(Environment::class)->sessionExpiration,
'expire_on_close' => false,
'encrypt' => true,
'files' => APP_ROOT . '/cache/sessions',
'store' => null,
'lottery' => [2, 100],
'cookie' => "ltid",
'path' => '/',
'domain' => is_array(parse_url(BASE_URL)) ? parse_url(BASE_URL)['host'] : null,
'secure' => true,
'http_only' => true,
'same_site' => "Strict",
);

$sessionManager = new \Illuminate\Session\SessionManager($app);
$sessionManager->setDefaultDriver("file");

return $sessionManager;
});

$this->app->singleton('session.store', fn($app) => $app['session']->driver());



/**
* @todo the following should eventually automatically turn caches into redis if available,
* then memcached if available,
* then fileStore
**/
$this->app->singleton(\Illuminate\Cache\CacheManager::class, function ($app) {

//installation cache is per server
$app['config']['cache.stores.installation'] = [
'driver' => 'file',
'path' => APP_ROOT . '/cache/installation',
];

//Instance is per company id
$instanceStore = fn () =>
$app['config']['cache.stores.instance'] = [
'driver' => 'file',
Expand All @@ -237,21 +285,22 @@ private function registerCoreBindings(): void

$instanceStore();
} else {
//Initialize instance cache store only after install was successfull
Events::add_event_listener(
'leantime.core.middleware.installed.handle.after_install',
function () use ($instanceStore) {
if (! $_SESSION['isInstalled']) {
if (! session("isInstalled")) {
return;
}

$instanceStore();
}
);

}

$cacheManager = new \Illuminate\Cache\CacheManager($app);

//Setting the default does not mean that is exists already.
//Installation store is always available
//Instance store is only available post after_install event
$cacheManager->setDefaultDriver('instance');

return $cacheManager;
Expand All @@ -271,8 +320,13 @@ private function registerCoreAliases(): void
$this->app->alias(\Illuminate\Filesystem\Filesystem::class, 'files');
$this->app->alias(ConsoleKernel::class, ConsoleKernelContract::class);
$this->app->alias(HttpKernel::class, HttpKernelContract::class);

$this->app->alias(\Illuminate\Cache\CacheManager::class, 'cache');
$this->app->alias(\Illuminate\Cache\CacheManager::class, \Illuminate\Contracts\Cache\Factory::class);

$this->app->alias(\Illuminate\Session\SessionManager::class, 'session');

$this->app->alias(\Illuminate\Encryption\Encrypter::class, "encrypter");
}

private function clearCache(): void
Expand Down Expand Up @@ -336,7 +390,6 @@ private function setErrorHandler(int $debug): void
}

Debug::enable();

}

/**
Expand Down
10 changes: 5 additions & 5 deletions app/Core/ConsoleKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,16 +124,16 @@ protected function commands()

$customCommands = $customPluginCommands = null;

$_SESSION['commands']['core'] ??= collect(glob(APP_ROOT . '/app/Command/*.php') ?? [])
session(["commands.core" => collect(glob(APP_ROOT . '/app/Command/*.php') ?? [])
->filter(function ($command) use (&$customCommands) {
return ! Arr::has(
$customCommands ??= collect(glob(APP_ROOT . '/custom/Command/*.php') ?? []),
str_replace(APP_ROOT . '/app', APP_ROOT . '/custom', $command)
);
})
->concat($customCommands ?? []);
->concat($customCommands ?? [])]);

$_SESSION['commands']['plugins'] ??= collect(glob(APP_ROOT . '/app/Plugins/*/Command/*.php') ?? [])
session(["commands.plugins" => collect(glob(APP_ROOT . '/app/Plugins/*/Command/*.php') ?? [])
->filter(function ($command) use (&$customPluginCommands) {
return ! in_array(
str_replace(APP_ROOT . '/app', APP_ROOT . '/custom', $command),
Expand All @@ -145,9 +145,9 @@ protected function commands()
->filter(fn ($command) => in_array(
Str::of($command)->after('Plugins/')->before('/Command')->toString(),
array_map(fn ($plugin) => $plugin->foldername, $this->getApplication()->make(PluginsService::class)->getAllPlugins(enabledOnly: true)),
));
))]);

$commands = collect(Arr::flatten($_SESSION['commands']))
$commands = collect(Arr::flatten(session("commands")))
->map(fn ($path) => $this->getApplication()->getNamespace() . Str::of($path)->remove([APP_ROOT . '/app/', APP_ROOT . '/custom/'])->replace(['/', '.php'], ['\\', ''])->toString());

/**
Expand Down
2 changes: 1 addition & 1 deletion app/Core/DefaultConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ class DefaultConfig
/**
* @var string Salting sessions. Replace with a strong password
*/
public string $sessionpassword = '3evBlq9zdUEuzKvVJHWWx3QzsQhturBApxwcws2m';
public string $sessionPassword = '3evBlq9zdUEuzKvVJHWWx3QzsQhturBApxwcws2m';

/**
* @var int How many seconds after inactivity should we logout? 28800seconds = 8hours
Expand Down
33 changes: 17 additions & 16 deletions app/Core/Environment.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Leantime\Config\Config;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\Yaml\Yaml;

/**
Expand Down Expand Up @@ -41,6 +42,11 @@ class Environment implements ArrayAccess, ConfigContract
*/
public array $config = [];

/**
* @var bool $configCached
*/
public bool $configCached = false;

/**
* @var array list of legacy mappings
* @todo remove this after deprecating configuration.php
Expand All @@ -49,7 +55,6 @@ class Environment implements ArrayAccess, ConfigContract
'printLogoUrl' => 'LEAN_PRINT_LOGO_URL',
'primarycolor' => 'LEAN_PRIMARY_COLOR',
'secondarycolor' => 'LEAN_SECONDARY_COLOR',
'sessionpassword' => 'LEAN_SESSION_PASSWORD',
'email' => 'LEAN_EMAIL_RETURN',
'useSMTP' => 'LEAN_EMAIL_USE_SMTP',
'smtpHosts' => 'LEAN_EMAIL_SMTP_HOSTS',
Expand Down Expand Up @@ -82,13 +87,6 @@ class Environment implements ArrayAccess, ConfigContract
*/
public function __construct(DefaultConfig $defaultConfiguration)
{
if (
isset($_SESSION)
&& (! empty($_SESSION['mainconfig']) && ! $_SESSION['mainconfig']['debug'])
) {
$this->config = $_SESSION['mainconfig'];
return $this;
}

/* PHP */
$this->phpConfig = null;
Expand Down Expand Up @@ -125,11 +123,14 @@ public function __construct(DefaultConfig $defaultConfiguration)
);
}

//Cache is not available until after install.
Events::add_event_listener(
'leantime.core.bootloader.boot.session_initialized',
'leantime.core.middleware.installed.handle.after_install',
function () {
$_SESSION['mainconfig'] = $this->config;
}
Cache::set("mainconfig", $this->config);
$this->configCached = true;
},
20
);
}

Expand Down Expand Up @@ -242,7 +243,7 @@ private function tryGetFromYaml(string $envVar, mixed $currentValue): mixed
*/
public function has($key): bool
{
return Arr::has($_SESSION['mainconfig'] ?? [], $key) || Arr::has($this->config, $key);
return Arr::has([], $key) || Arr::has($this->config, $key);
}

/**
Expand All @@ -258,7 +259,7 @@ public function get($key, $default = null): mixed
return $this->getMany($key);
}

return Arr::get($_SESSION['mainconfig'] ?? [], $key, Arr::get(
return Arr::get([], $key, Arr::get(
$this->config,
$key,
$default
Expand Down Expand Up @@ -300,10 +301,10 @@ public function set($key, $value = null): void
foreach ($keys as $key => $value) {
Arr::set($this->config, $key, $value);

# this basically checks to see if the session is initialized
if (isset($_SESSION['mainconfig'])) {
Arr::set($_SESSION['mainconfig'], $key, $value);
if($this->configCached === true && Cache::has("mainconfig")){
Cache::set("mainconfig.".$key, $value);
}

}
}

Expand Down
2 changes: 1 addition & 1 deletion app/Core/Events.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ public static function discover_listeners(): void
}

Events::add_event_listener('leantime.core.middleware.installed.handle.after_install', function () {
if (! $_SESSION['isInstalled']) {
if (! session("isInstalled")) {
return;
}

Expand Down
2 changes: 2 additions & 0 deletions app/Core/HttpKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Contracts\Http\Kernel as HttpKernelContract;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Session\Middleware\StartSession;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
Expand Down Expand Up @@ -145,6 +146,7 @@ public function getApplication(): \Leantime\Core\Application
public function getMiddleware(): array
{
return self::dispatch_filter('http_middleware', [
Middleware\StartSession::class,
Middleware\TrustProxies::class,
Middleware\InitialHeaders::class,
Middleware\Installed::class,
Expand Down
Loading

0 comments on commit ce3af40

Please sign in to comment.