[+] возможность авторизации через телеграм (админка)

This commit is contained in:
rsgrinko committed 2023-10-28 16:12:27 +03:00
1 parent 0146815e2d
commit 8cb0b860ea
5 files changed
+135 -10

No files matched your search

+5 -2
View File
@@ -42,7 +42,7 @@
<meta name="description" content=""> <meta name="description" content="">
<meta name="author" content=""> <meta name="author" content="">
<title>Delta - CPanel</title> <title>Delta - CPanel<?= isset($pageTitle) ? ' | ' . $pageTitle : '' ?></title>
<link href="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/css/style.default.css" rel="stylesheet"> <link href="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/css/style.default.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
@@ -59,11 +59,14 @@
width: 100%; width: 100%;
height: 70px; height: 70px;
} }
.telegramAuthButtonBox {
margin-top: 20px;
float: right;
}
</style> </style>
</head> </head>
<body> <body>
<header> <header>
<div class="headerwrapper"> <div class="headerwrapper">
<div class="header-left"> <div class="header-left">
+74 -7
View File
@@ -20,11 +20,53 @@
*/ */
use Core\Helpers\Captcha; use Core\Helpers\Captcha;
use Core\Models\User; use Core\Helpers\SystemFunctions;
use Core\SystemConfig;
use Core\Models\{User, UserMeta};
use Core\CoreException; use Core\CoreException;
require_once __DIR__ . '/inc/bootstrap.php'; require_once __DIR__ . '/inc/bootstrap.php';
// Определяем тип авторизации
$authType = isset($_REQUEST['authType']) && !empty($_REQUEST['authType']) ? $_REQUEST['authType'] : 'default';
/**
* array(7) {
["id"]=> string(7) "1831337"
["first_name"]=> string(18) "Александр"
["last_name"]=> string(16) "Менщиков"
["username"]=> string(5) "n0str"
["photo_url"]=> string(36) "https://t.me/i/userpic/100/n0str.jpg"
["auth_date"]=> string(10) "1518168109"
["hash"]=> string(64) "abba<..>1345"
}
*/
switch ($authType) {
case 'telegram':
$data = [
'id' => $_REQUEST['id'],
'first_name' => $_REQUEST['first_name'],
'last_name' => $_REQUEST['last_name'],
'username' => $_REQUEST['username'],
'photo_url' => $_REQUEST['photo_url'],
'auth_date' => $_REQUEST['auth_date'],
'hash' => $_REQUEST['hash'],
];
$isCorrectTelegramAuth = SystemFunctions::checkTelegramAuthorization($data);
if ($isCorrectTelegramAuth) {
$res = UserMeta::getListByParams(['name' => 'telegramId', 'value' => $data['id']]);
if (!empty($res)) {
$userId = array_shift($res)['user_id'];
User::authorize($userId);
header('Location: index.php');
die();
}
}
$auth = false;
$err_mess = true;
break;
case 'default':
$captchaCorrect = true; $captchaCorrect = true;
if (USE_CAPTCHA) { if (USE_CAPTCHA) {
$captchaCorrect = isset($_REQUEST['captchaCode']) && Captcha::isValidCaptcha($_REQUEST['captchaCode']); $captchaCorrect = isset($_REQUEST['captchaCode']) && Captcha::isValidCaptcha($_REQUEST['captchaCode']);
@@ -49,6 +91,11 @@
} else { } else {
$err_mess = false; $err_mess = false;
} }
break;
}
if ($auth === true) { if ($auth === true) {
global $USER; global $USER;
@@ -56,6 +103,7 @@
try { try {
User::logout(); User::logout();
User::authorize($_REQUEST['loginAs']); User::authorize($_REQUEST['loginAs']);
die();
} catch (CoreException $e) { } catch (CoreException $e) {
die('Авторизация не удалась'); die('Авторизация не удалась');
} }
@@ -70,23 +118,23 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content=""> <meta name="description" content="">
<meta name="author" content=""> <meta name="author" content="">
<title>Delta Framework - Авторизация</title> <title>Delta Framework - Авторизация</title>
<link href="//<?php echo $_SERVER['SERVER_NAME']; ?>/admin/styles/css/style.default.css" rel="stylesheet"> <link href="//<?php echo $_SERVER['SERVER_NAME']; ?>/admin/styles/css/style.default.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]> <!--[if lt IE 9]>
<script src="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/js/html5shiv.js"></script> <script src="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/js/html5shiv.js"></script>
<script src="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/js/respond.min.js"></script> <script src="//<?= $_SERVER['SERVER_NAME']; ?>/admin/styles/js/respond.min.js"></script>
<![endif]--> <![endif]-->
<style>
.telegramAuthButtonBox {
margin-top: 20px;
float: right;
}
</style>
</head> </head>
<body class="signin"> <body class="signin">
<section> <section>
<div class="panel panel-signin"> <div class="panel panel-signin">
<div class="panel-body"> <div class="panel-body">
<div class="logo text-center"> <div class="logo text-center">
@@ -105,6 +153,7 @@
<?php } ?> <?php } ?>
<form action="login.php" method="post"> <form action="login.php" method="post">
<input type="hidden" name="authType" value="default">
<div class="input-group mb15"> <div class="input-group mb15">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control" name="login" placeholder="Имя пользователя"> <input type="text" class="form-control" name="login" placeholder="Имя пользователя">
@@ -142,6 +191,24 @@
</div> </div>
</form> </form>
<h4 class="text-center mb5">Вход через сторонний сервис</h4>
<p class="text-center">Вы можете использовать для авторизации один из вариантов ниже</p>
<div class="telegramAuthButtonBox">
<script async src="https://telegram.org/js/telegram-widget.js?22" data-telegram-login="<?= SystemConfig::getValue('TELEGRAM_BOT_USERNAME') ?>" data-size="large" data-onauth="onTelegramAuth(user)" data-request-access="write"></script>
<script type="text/javascript">
function onTelegramAuth(user) {
document.location.href = 'login.php?authType=telegram&hash='+ user.hash
+ '&id=' + user.id
+ '&auth_date=' + user.auth_date
+ '&first_name=' + user.first_name
+ '&last_name=' + user.last_name
+ '&photo_url=' + user.photo_url
+ '&username=' + user.username
}
</script>
</div>
</div><!-- panel-body --> </div><!-- panel-body -->
<div class="panel-footer"> <div class="panel-footer">
<a href="register.php" class="btn btn-primary btn-block">Регистрация в системе</a> <a href="register.php" class="btn btn-primary btn-block">Регистрация в системе</a>
+8 -1
View File
@@ -124,6 +124,13 @@
define('PATH_TO_TEMPLATES', ROOT_PATH . '/templates'); define('PATH_TO_TEMPLATES', ROOT_PATH . '/templates');
} }
/**
* Имя телеграм бота
*/
if (!defined('TELEGRAM_BOT_USERNAME')) {
define('TELEGRAM_BOT_USERNAME', 'deltacore_bot');
}
/** /**
* Токен телеграм бота * Токен телеграм бота
*/ */
@@ -213,7 +220,7 @@
* Флаг использования Captcha * Флаг использования Captcha
*/ */
if (!defined('USE_CAPTCHA')) { if (!defined('USE_CAPTCHA')) {
define('USE_CAPTCHA', true); define('USE_CAPTCHA', false);
} }
/** /**
@@ -947,4 +947,37 @@
sendTelegram('<b>' . $title . '</b>' . PHP_EOL. $text); sendTelegram('<b>' . $title . '</b>' . PHP_EOL. $text);
} }
} }
/**
* Проверка авторизации через Telegram
*
* @param array $authData Данные для проверки
*
* @return bool Результат проверки
*/
public static function checkTelegramAuthorization(array $authData): bool
{
if (empty($authData['hash']) || empty($authData['auth_date'])) {
return false;
}
$checkHash = $authData['hash'];
unset($authData['hash']);
$dataCheckArr = [];
foreach ($authData as $key => $value) {
$dataCheckArr[] = $key . '=' . $value;
}
sort($dataCheckArr);
$dataCheckString = implode("\n", $dataCheckArr);
$secretKey = hash('sha256', SystemConfig::getValue('TELEGRAM_BOT_TOKEN'), true);
$hash = hash_hmac('sha256', $dataCheckString, $secretKey);
if (strcmp($hash, $checkHash) !== 0) {
//Data is NOT from Telegram
return false;
}
if ((time() - (int)$authData['auth_date']) > 86400) {
//Data is outdated
return false;
}
return true;
}
} }
+15
View File
@@ -2,6 +2,7 @@
namespace Core\Models; namespace Core\Models;
use Core\CoreException;
use Core\DataBases\DB; use Core\DataBases\DB;
use Core\Helpers\Cache; use Core\Helpers\Cache;
@@ -123,4 +124,18 @@
$DB = DB::getInstance(); $DB = DB::getInstance();
$DB->query('DELETE FROM ' . self::TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND id="' . $id . '"'); $DB->query('DELETE FROM ' . self::TABLE . ' WHERE user_id=' . $this->user->getId() . ' AND id="' . $id . '"');
} }
/**
* Получить список мета данных по фильтру
*
* @param array $params Параметры
*
* @return array|null
* @throws CoreException
*/
public static function getListByParams(array $params = []): ?array {
/** @var $DB DB */
$DB = DB::getInstance();
return $DB->getItems(self::TABLE, $params);
}
} }