XBackBone/app/Controllers/Controller.php
Pietro Marangon 3cb4ca790c Fix & improvements (#2)
* New .gitignore
Added violinist.io configuration
Start with CI
Started moving CSS/JS to NPM

* Fix & improvements
Security improves (SHA256 instead of MD5) and new PHP7 random function
Security fix admin check from database instead of session
Security fix user active for every page that require login
UX fix admin cannot demote himself
Added Gruntfile.js
Updated composer.json dependency
Addeded PHP >=7.1 to composer.json
Moved static file to src

* Results of .gitignore "static/"

* Fix migration for admin user_code

* Travis test for grunt (JS)

* Changed user_code generation method
Updated Travis test
2018-06-02 22:32:14 +02:00

73 lines
No EOL
2.2 KiB
PHP

<?php
namespace App\Controllers;
use App\Exceptions\AuthenticationException;
use App\Exceptions\UnauthorizedException;
use App\Web\Session;
use Flight;
use App\Database\DB;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
abstract class Controller
{
/**
* @throws AuthenticationException
*/
protected function checkLogin(): void
{
if (!Session::get('logged', false)) {
Session::set('redirectTo', (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
throw new AuthenticationException();
}
if (!DB::query('SELECT `id`, `active` FROM `users` WHERE `id` = ? LIMIT 1', [Session::get('user_id')])->fetch()->active) {
Session::alert('Your account is not active anymore.', 'danger');
Session::set('logged', false);
Session::set('redirectTo', (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
throw new AuthenticationException();
}
}
/**
* @throws AuthenticationException
* @throws UnauthorizedException
*/
protected function checkAdmin(): void
{
$this->checkLogin();
if (!DB::query('SELECT `id`, `is_admin` FROM `users` WHERE `id` = ? LIMIT 1', [Session::get('user_id')])->fetch()->is_admin) {
Session::alert('Your account is not admin anymore.', 'danger');
Session::set('admin', false);
Session::set('redirectTo', (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
throw new UnauthorizedException();
}
}
protected function humanFilesize($size, $precision = 2): string
{
for ($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) {
}
return round($size, $precision) . ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][$i];
}
protected function getStorage(): Filesystem
{
return new Filesystem(new Local(Flight::get('config')['storage_dir']));
}
protected function http2push(string $url, string $as = 'image'): void
{
if (Flight::request()->scheme === 'HTTP/2.0') {
$headers = isset(Flight::response()->headers()['Link']) ? Flight::response()->headers()['Link'] : [];
$headers[] = "<${url}>; rel=preload; as=${as}";
Flight::response()->header('Link', $headers);
}
}
}