Skip to content

Commit

Permalink
0.2.26
Browse files Browse the repository at this point in the history
Добавлена авторизация через Cookie. Не уверен по безопасности, но вроде норм. Исправлена ошибка с opcache. Добавлен пункт, который позволяет убрать кеширование браузером стилей и скриптов. Добавлен полный шрифт montserrat. Исправлена ссылка в .htaccess на шрифты и прочее
  • Loading branch information
FlamesONE committed Mar 20, 2022
1 parent 7efe747 commit e577747
Show file tree
Hide file tree
Showing 13 changed files with 178 additions and 240 deletions.
2 changes: 1 addition & 1 deletion .htaccess
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ RewriteEngine On
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_URI} !\.
RewriteRule ^(.*) %{REQUEST_URI}/ [L,R=301]
RewriteRule !.(gif|jpg|png|ico|css|js|svg|js_controller.php)$ index.php
RewriteRule !.(gif|jpg|png|ico|css|js|svg|js_controller.php|woff2|mp3|mp4|webm|ttf)$ index.php
149 changes: 135 additions & 14 deletions app/ext/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ class Auth {
*/
public $Db;

/**
* Длина токена
* @var int
*/
protected $token_length = 16;

/**
* Время жизни куки
* @var int
*/
protected $cookie_days = 30;

/**
* Организация работы вэб-приложения с авторизацией.
*
Expand All @@ -85,6 +97,8 @@ function __construct( $General, $Db ) {
// Импорт класса отвечающего за работу с базой данных.
$this->Db = $Db;

!isset( $_SESSION["steamid"] ) && $this->authByCookie();

// Работа с авторизованным пользователем.
if( isset( $_SESSION['steamid'] ) ):
// Проверка сессии.
Expand All @@ -100,37 +114,142 @@ function __construct( $General, $Db ) {
// Работа со Steam авторизацией.
if(isset( $_GET["auth"] ))
{
if($this->General->arr_general['steam_auth'] == 1 && $_GET["auth"] == 'login') require 'app/includes/auth/steam.php';
if($this->General->arr_general['steam_auth'] == 1 && $_GET["auth"] == 'login')
require 'app/includes/auth/steam.php';
}

// Работа с No-Steam авторизацией
isset( $_POST['log_in'] ) && ! empty( $_POST['_login'] ) && ! empty( $_POST['_pass'] ) && $this->General->arr_general['steam_only_authorization'] === 0 && $this->authorization_no_steam();

// Выход пользователя из аккаунта.
isset( $_GET["auth"] ) && $_GET["auth"] == 'logout' && require 'app/includes/auth/steam.php';
}

/**
* Если не существует столбца, он его создает
*/
protected function checkTokenCol()
{
if( !$this->Db->mysql_table_search( "Core", 0, 0, "lr_web_cookie_tokens" ) )
$this->Db->query("Core", 0, 0, "CREATE TABLE IF NOT EXISTS `lr_web_cookie_tokens` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`steam` varchar(255) NOT NULL DEFAULT '0',
`cookie_expire` varchar(255) NOT NULL DEFAULT '0',
`cookie_token` varchar(255) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
}

/**
* Просто возвращает true/false, включены ли токены
*/
protected function cookieEnabled() : bool
{
return (bool) $this->General->arr_general['auth_cock'];
}

/**
* Получить пользователя по текущему токену
*/
public function getUserToken( string $token )
{
if( $this->cookieEnabled() )
return $this->Db->query("Core", 0, 0, "SELECT * FROM `lr_web_cookie_tokens` WHERE `cookie_token` = :token", [
"token" => $token
]);

return [];
}

/**
* Авторизация пользователя по кукам
*/
public function authByCookie()
{
$this->clearOldTokens();

if( isset( $_COOKIE["cookie_token"] ) )
{
if( !empty( $user = $this->getUserToken( htmlentities($_COOKIE["cookie_token"]) ) ) )
{
if( $user["cookie_expire"] > time() )
{
$steam32 = con_steam64to32( $user["steam"] );

$_SESSION = [
"steamid" => $user["steam"],
"steamid64" => $user["steam"],
"steamid32" => $steam32,
"steamid32_short" => substr( $steam32, 8 ),
"USER_AGENT" => $_SERVER['HTTP_USER_AGENT'],
"REMOTE_ADDR" => $this->General->get_client_ip_cdn()
];

( $General->arr_general['auth_cock'] == 1 && !empty($_SESSION) && empty($_COOKIE['session']) ) && $this->check_cookie();
header('Location: ' . $this->General->arr_general['site'] );
}
}
}
}

( $General->arr_general['auth_cock'] == 1 && empty($_SESSION) && !empty($_COOKIE['session']) ) && $this->auth_cookie();
/**
* Почистить старые токены
*/
public function clearOldTokens()
{
$this->checkTokenCol();

if( $General->arr_general['auth_cock'] == 0 && !empty( $_COOKIE['session'] ) )
unset($_COOKIE['session']);
$this->Db->query("Core", 0, 0, "DELETE FROM `lr_web_cookie_tokens` WHERE `cookie_expire` < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL ".$this->cookie_days." DAY))");
}

// Запись в куки данных о сессии
private function check_cookie()
/**
* функция, которая генерирует токен для авторизации по куки
*/
public function generateToken()
{
if( $this->cookieEnabled() )
{
$this->checkTokenCol();
$token = bin2hex(random_bytes( $this->token_length ));
$this->setUserToken($token, $_SESSION["steamid64"]);

setcookie("cookie_token", $token, strtotime("+".$this->cookie_days." days"), "/", ".".$_SERVER['HTTP_HOST']);
}
}

/**
* Записать данные токена в пользователя
*/
protected function setUserToken( string $token, int $steamid64 )
{
foreach ($_SESSION as $key => $val)
if( $this->cookieEnabled() )
{
setcookie("session[".$key."]", $val, strtotime('+1 day'));
if( !empty( $this->Db->query("Core", 0, 0, "SELECT * FROM `lr_web_cookie_tokens` WHERE `steam` = :steam", ["steam" => $steamid64]) ) )
{
$this->Db->query("Core", 0, 0, "UPDATE `lr_web_cookie_tokens` SET `cookie_token` = :token, `cookie_expire` = :expire WHERE `steam` = :steam", [
"steam" => $steamid64,
"token" => $token,
"expire"=> strtotime("+".$this->cookie_days." days")
]);
}
else
{
$this->Db->query("Core", 0, 0, "INSERT INTO `lr_web_cookie_tokens`(`steam`, `cookie_token`, `cookie_expire`) VALUES (:steam, :token, :expire)", [
"steam" => $steamid64,
"token" => $token,
"expire"=> strtotime("+".$this->cookie_days." days")
]);
}
}
}

// Авторизация пользователя с помощью куки
private function auth_cookie()
/**
* Удалить определенный токен при разлогине
*/
public function delToken( string $steam )
{
$_SESSION = $_COOKIE['session'];
header("Location: ".$this->General->arr_general['site']);
$this->Db->query("Core", 0, 0, "DELETE FROM `lr_web_cookie_tokens` WHERE `steam` = :steam", [
"steam" => (int) $steam
]);
}

/**
Expand Down Expand Up @@ -159,7 +278,9 @@ public function get_count_admins() {
* @since 0.2.120
*/
public function check_session_admin() {
$result = $this->Db->query( 'Core', 0, 0,"SELECT `steamid`, `group`, `flags`, `access` FROM `lvl_web_admins` WHERE `steamid`={$_SESSION['steamid']} LIMIT 1" );
$result = $this->Db->query( 'Core', 0, 0,"SELECT `steamid`, `group`, `flags`, `access` FROM `lvl_web_admins` WHERE `steamid`= :steamid LIMIT 1", [
"steamid" => $_SESSION["steamid64"]
]);
if( ! empty( $result ) ):
$_SESSION['user_admin'] = 1;
$_SESSION['user_group'] = $result['group'];
Expand Down
18 changes: 14 additions & 4 deletions app/includes/auth/steam.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,11 @@
*
* @license GNU General Public License Version 3
*/
$red = $_SESSION['page_redirect'] ?? '';
$red = $_SESSION['rpage'] ?? '';
if ( ! empty( $_GET["auth"] ) && $_GET["auth"] == 'login' ) {
require 'app/ext/LightOpenID.php';
try
{
// empty( $_SERVER['HTTPS'] ) ? 'http:' : "https:" - Bad idea.
$openid = new LightOpenID( "http:" . $this->General->arr_general['site'] );
if ( ! $openid->mode )
{
Expand Down Expand Up @@ -68,6 +67,8 @@
}
}

$this->generateToken();

header('Location: ' . $this->General->arr_general['site']);
}
}
Expand All @@ -78,10 +79,19 @@
header('Location: ' . $this->General->arr_general['site']);
}
};
if ( ! empty( $_GET["auth"] ) && $_GET["auth"] == 'logout' ) {
if ( ! empty( $_GET["auth"] ) && $_GET["auth"] == 'logout' )
{
// Чистим токен из базы
$this->cookieEnabled() && $this->delToken( $_SESSION["steamid64"] );

// Удаляем сессию
session_unset();
session_destroy();
setcookie('session', null, 1);

// Чистим токен у пользователя
setcookie('cookie_token', null, 1, "/", ".".$_SERVER['HTTP_HOST']);

// Редирект
header('Location: ' . $this->General->arr_general['site']);
if ( ! headers_sent() ) {?>
<script type="text/javascript">window.location.href="<?php echo $this->General->arr_general['site'] ?>";</script>
Expand Down
3 changes: 3 additions & 0 deletions app/modules/module_page_adminpanel/forward/data.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
// Создаём экземпляр класса для работы с админкой
$Admin = new Admin ( $General, $Modules, $Auth, $Db, $Translate );

# Убираем кеширование
isset( $_POST ) && opcache_reset();

# Настройки модулей

// Нажатие на кнопку - Очистить кэш модулей.
Expand Down
4 changes: 4 additions & 0 deletions app/modules/module_page_adminpanel/includes/general.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@
<div class="input-form">
<div class="text_on_line"><?php echo $Translate->get_translate_module_phrase( 'module_page_adminpanel','_Security')?></div>
</div>
<div class="input-form">
<input onclick="set_options_data(this.id,'')" class="border-checkbox" type="checkbox" name="css_off_cache" id="css_off_cache" <?php $General->arr_general['css_off_cache'] === 1 && print 'checked'?>>
<label class="border-checkbox-label" for="css_off_cache"><?php echo $Translate->get_translate_module_phrase( 'module_page_adminpanel','_Css_off_cache')?></label>
</div>
<div class="input-form">
<input onclick="set_options_data(this.id,'')" class="border-checkbox" type="checkbox" name="session_check" id="session_check" <?php $General->arr_general['session_check'] === 1 && print 'checked'?>>
<label class="border-checkbox-label" for="session_check"><?php echo $Translate->get_translate_module_phrase( 'module_page_adminpanel','_Session_check')?></label>
Expand Down
4 changes: 4 additions & 0 deletions app/modules/module_page_adminpanel/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -877,5 +877,9 @@
"_Template":{
"EN": "Choose Template",
"RU": "Выберете шаблон"
},
"_Css_off_cache": {
"EN": "Disable CSS/JS Browser Cache",
"RU": "Отключение браузерного кеша CSS/JS"
}
}
4 changes: 4 additions & 0 deletions app/page/custom/install/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
// Ограничиваем время выполнения скрипта.
set_time_limit(3);

// Убрать кеширование, чтобы кучу раз не тыкать
opcache_reset();

(!empty($_GET['code']) && !empty($_GET['description'])) && exit(require PAGE_CUSTOM . '/error/index.php');

// Проверка на PDO
Expand Down Expand Up @@ -75,6 +78,7 @@ class_exists('PDO') || get_iframe('001','Need support to work PDO');
$options['graphics.blocks_blur'] = 0;
$options['background_image'] = 'null';
$options['auth_cock'] = 0;
$options['css_off_cache'] = 0;
$options['session_check'] = 0;
$options['avatars_cache_time'] = 259200;
file_put_contents(SESSIONS . '/options.php', '<?php return ' . var_export_min( $options ) . ";\n");
Expand Down
8 changes: 4 additions & 4 deletions app/page/general/footer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,19 @@
<script>let domain = '<?php echo $General->arr_general['site'] ?>';</script>
<?php if( empty( $General->arr_general['enable_js_cache'] ) ) :
for ( $js = 0, $js_s = sizeof( $Modules->js_library ); $js < $js_s; $js++ ):?>
<script src="<?php echo $General->arr_general['site'] . $Modules->js_library[ $js ]?>"></script>
<script src="<?php echo $General->arr_general['site'] . $Modules->js_library[ $js ]?><?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>"></script>
<?php endfor;
if( ! empty( $Modules->arr_module_init['page'][ $Modules->route ]['js'] ) ):
for ( $js = 0, $js_s = sizeof( $Modules->arr_module_init['page'][ $Modules->route ]['js'] ); $js < $js_s; $js++ ):?>
<script src="<?php echo $General->arr_general['site'] . 'app/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['js'][ $js ]['name'] . '/assets/js/' . $Modules->arr_module_init['page'][ $Modules->route ]['js'][ $js ]['type'] . '.js'?>"></script>
<script src="<?php echo $General->arr_general['site'] . 'app/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['js'][ $js ]['name'] . '/assets/js/' . $Modules->arr_module_init['page'][ $Modules->route ]['js'][ $js ]['type'] . '.js'?><?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>"></script>
<?php if(isset($Modules->template_modules)):
if(isset($Modules->template_modules[ $Modules->arr_module_init['page'][ $Modules->route ]['js'][ $css ]['name'] ][ 'js' ])) { ?>
<script src="<?php echo $General->arr_general['site'] . 'app/templates/' . $General->arr_general['theme'] . '/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['js'][ $css ]['name'] . '/dop.js'; ?>"></script>
<script src="<?php echo $General->arr_general['site'] . 'app/templates/' . $General->arr_general['theme'] . '/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['js'][ $css ]['name'] . '/dop.js'; ?><?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>"></script>
<?php }
endif;endfor;
endif;
else:?>
<script src="<?php echo ! file_exists( ASSETS_JS . '/generation/app_generated.min.ver.' . $Modules->actual_library['actual_js_ver'] . '.js' ) ? $General->arr_general['site'] . 'storage/assets/js/app' : $General->arr_general['site'] . 'storage/assets/js/generation/app_generated.min.ver.' . $Modules->actual_library['actual_js_ver']?>.js"></script>
<script src="<?php echo ! file_exists( ASSETS_JS . '/generation/app_generated.min.ver.' . $Modules->actual_library['actual_js_ver'] . '.js' ) ? $General->arr_general['site'] . 'storage/assets/js/app' : $General->arr_general['site'] . 'storage/assets/js/generation/app_generated.min.ver.' . $Modules->actual_library['actual_js_ver']?>.js<?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>"></script>
<?php endif;

if(!empty($General->notes)):
Expand Down
8 changes: 4 additions & 4 deletions app/page/general/head.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,20 @@
<meta name="twitter:image" content="<?php echo $Modules->get_page_image()?>">
<?php if( empty( $General->arr_general['enable_css_cache'] ) ) : ?>
<?php for ( $style = 0, $style_s = sizeof( $Modules->css_library ); $style < $style_s; $style++ ):?>
<link rel="stylesheet" type="text/css" href="<?php echo $General->arr_general['site'] . $Modules->css_library[ $style ]?>">
<link rel="stylesheet" type="text/css" href="<?php echo $General->arr_general['site'] . $Modules->css_library[ $style ]?><?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>">
<?php endfor;
if( ! empty( $Modules->arr_module_init['page'][ $Modules->route ]['css'] ) ):
for ( $css = 0, $css_s = sizeof( $Modules->arr_module_init['page'][ $Modules->route ]['css'] ); $css < $css_s; $css++ ):?>
<link rel="stylesheet" type="text/css" href="<?php echo $General->arr_general['site'] . 'app/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['css'][ $css ]['name'] . '/assets/css/' . $Modules->arr_module_init['page'][ $Modules->route ]['css'][ $css ]['type'] . '.css'?>">
<link rel="stylesheet" type="text/css" href="<?php echo $General->arr_general['site'] . 'app/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['css'][ $css ]['name'] . '/assets/css/' . $Modules->arr_module_init['page'][ $Modules->route ]['css'][ $css ]['type'] . '.css'?><?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>">
<?php if(isset($Modules->template_modules)):
if(isset($Modules->template_modules[ $Modules->arr_module_init['page'][ $Modules->route ]['css'][ $css ]['name'] ][ 'css' ])) { ?>
<link rel="stylesheet" href="<?php echo $General->arr_general['site'] . 'app/templates/' . $General->arr_general['theme'] . '/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['css'][ $css ]['name'] . '/dop.css'; ?>">
<link rel="stylesheet" href="<?php echo $General->arr_general['site'] . 'app/templates/' . $General->arr_general['theme'] . '/modules/' . $Modules->arr_module_init['page'][ $Modules->route ]['css'][ $css ]['name'] . '/dop.css'; ?><?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>">
<?php }
endif;
endfor;
endif;
else: ?>
<link rel="stylesheet" type="text/css" href="<?php echo ! file_exists( ASSETS_CSS . '/generation/style_generated.min.ver.' . $Modules->actual_library['actual_css_ver'] . '.css' ) ? $General->arr_general['site'] . 'app/templates/'.$General->arr_general['theme'].'css/style' : $General->arr_general['site'] . 'storage/assets/css/generation/style_generated.min.ver.' . $Modules->actual_library['actual_css_ver']?>.css">
<link rel="stylesheet" type="text/css" href="<?php echo ! file_exists( ASSETS_CSS . '/generation/style_generated.min.ver.' . $Modules->actual_library['actual_css_ver'] . '.css' ) ? $General->arr_general['site'] . 'app/templates/'.$General->arr_general['theme'].'css/style' : $General->arr_general['site'] . 'storage/assets/css/generation/style_generated.min.ver.' . $Modules->actual_library['actual_css_ver']?>.css<?php $General->arr_general['css_off_cache'] == 1 && print "?".time() ?>">
<?php endif; ?>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/material-design-iconic-font/2.2.0/css/material-design-iconic-font.min.css">
<style>
Expand Down
Loading

0 comments on commit e577747

Please sign in to comment.