Browse Source

chore: code clean up for new oauth system

M1Screw 2 years ago
parent
commit
711c5d8a21

+ 0 - 3
app/routes.php

@@ -137,14 +137,11 @@ return static function (Slim\App $app): void {
     // Auth
     $app->group('/auth', static function (RouteCollectorProxy $group): void {
         $group->get('/login', App\Controllers\AuthController::class . ':login');
-        $group->post('/qrcode_check', App\Controllers\AuthController::class . ':qrcodeCheck');
         $group->post('/login', App\Controllers\AuthController::class . ':loginHandle');
-        $group->post('/qrcode_login', App\Controllers\AuthController::class . ':qrcodeLoginHandle');
         $group->get('/register', App\Controllers\AuthController::class . ':register');
         $group->post('/register', App\Controllers\AuthController::class . ':registerHandle');
         $group->post('/send', App\Controllers\AuthController::class . ':sendVerify');
         $group->get('/logout', App\Controllers\AuthController::class . ':logout');
-        $group->get('/telegram_oauth', App\Controllers\AuthController::class . ':telegramOauth');
     })->add(new Guest());
 
     // Password

+ 0 - 4
config/.config.example.php

@@ -117,10 +117,6 @@ $_ENV['telegram_chatid']                    = -111;         //Telegram bot,群
 $_ENV['telegram_bot']                       = '_bot';       //Telegram 机器人账号
 $_ENV['telegram_request_token']             = '';           //Telegram 机器人请求Key,随意设置,由大小写英文和数字组成,更新这个参数之后请 php xcat Tool setTelegram
 
-//社交登录设置
-#Telegram
-$_ENV['enable_telegram_login']              = false;   //开启这个设置前请先配置 Telegram bot 否则不会生效
-
 #工单系统设置
 $_ENV['enable_ticket']        = true;        //是否开启工单系统
 $_ENV['mail_ticket']          = true;        //是否开启工单邮件提醒

+ 1 - 1
resources/views/tabler/admin/setting/reg.tpl

@@ -101,7 +101,7 @@
                                     </div>
                                 </div>
                                 <div class="form-group mb-3 row">
-                                    <label class="form-label col-3 col-form-label">新用户默认使用新商店系统</label>
+                                    <label class="form-label col-3 col-form-label">默认使用新商店系统</label>
                                     <div class="col">
                                         <select id="enable_reg_new_shop" class="col form-select" value="{$settings['enable_reg_new_shop']}">
                                             <option value="0" {if $settings['enable_reg_new_shop'] == false}selected{/if}>关闭</option>

+ 0 - 88
resources/views/tabler/auth/telegram.tpl

@@ -1,88 +0,0 @@
-<script src="//cdn.jsdelivr.net/npm/[email protected]/qrcode.min.js"></script>
-<script>
-    var telegram_qrcode = 'mod://login/{$login_token}';
-    var qrcode = new QRCode(document.getElementById("telegram-qr"));
-    qrcode.clear();
-    qrcode.makeCode(telegram_qrcode);
-</script>
-<script>
-    var flag = false;
-    $(document).ready(function () {
-        $("#calltgauth").click(
-                function () {
-                    if(flag == false){
-                        f();
-                        flag = true;
-                    }else{
-                        return 0;
-                    }
-                }
-        );
-    function f() {
-            $.ajax({
-                type: "POST",
-                url: "qrcode_check",
-                dataType: "json",
-                data: {
-                    token: "{$login_token}",
-                    number: "{$login_number}"
-                },
-                success: (data) => {
-                    if (data.ret > 0) {
-                        clearTimeout(tid);
-                        $.ajax({
-                            type: "POST",
-                            url: "/auth/qrcode_login",
-                            dataType: "json",
-                            data: {
-                                token: "{$login_token}",
-                                number: "{$login_number}"
-                            },
-                            success: (data) => {
-                                if (data.ret) {
-                                    $("#result").modal();
-                                    $$.getElementById('msg').innerHTML = '登录成功!';
-                                    window.setTimeout("location.href=/user/", {$config['jump_delay']});
-                                }
-                            },
-                            error: (jqXHR) => {
-                                $("#result").modal();
-                                $$.getElementById('msg').innerHTML = `发生错误:${
-                                        jqXHR.status
-                                        }`;
-                            }
-                        });
-                    } else {
-                        if (data.ret === -1) {
-                            $('#telegram-qr').replaceWith('此二维码已经过期,请刷新页面后重试。');
-                            $('#code_number').replaceWith('<code id="code_number">此数字已经过期,请刷新页面后重试。</code>');
-                        }
-                    }
-                },
-                error: (jqXHR) => {
-                    if (jqXHR.status !== 200 && jqXHR.status !== 0) {
-                        $("#result").modal();
-                        $$.getElementById('msg').innerHTML = `发生错误:${
-                                jqXHR.status
-                                }`;
-                    }
-                }
-            });
-            tid = setTimeout(f, 2500); //循环调用触发setTimeout
-        }
-    })
-</script>
-<script>
-    $(document).ready(function () {
-        var el = document.createElement('script');
-        document.getElementById('telegram-login-box').append(el);
-        el.onload = function () {
-            $('#telegram-alert').remove()
-        }
-        el.src = 'https://telegram.org/js/telegram-widget.js?4';
-        el.setAttribute('data-size', 'large')
-        el.setAttribute('data-telegram-login', '{$telegram_bot}')
-        el.setAttribute('data-auth-url', '{$base_url}/auth/telegram_oauth')
-        el.setAttribute('data-request-access', 'write')
-    });
-</script>

+ 0 - 50
resources/views/tabler/auth/telegram_modal.tpl

@@ -1,50 +0,0 @@
-<div class="card auth-tg cust-model">
-    <div class="card-main">
-        <nav class="tab-nav margin-top-no margin-bottom-no">
-            <ul class="nav nav-justified">
-                <li class="active">
-                    <a class="waves-attach" data-toggle="tab" href="#number_login">一键/验证码登录</a>
-                </li>
-                <li>
-                    <a class="waves-attach" data-toggle="tab" href="#qrcode_login">二维码登录</a>
-                </li>
-            </ul>
-        </nav>
-        <div class="tab-pane fade active in" id="number_login">
-            <div class="card-header">
-                <div class="card-inner">
-                    <h1 class="card-heading" style=" text-align:center;font-weight:bold;">Telegram 登录</h1>
-                </div>
-            </div>
-            <div class="card-inner">
-                <div class="text-center">
-                    <p>一键登陆</p>
-                </div>
-                <p id="telegram-alert">正在载入 Telegram,如果长时间未显示请刷新页面或检查代理</p>
-                <div class="text-center" id="telegram-login-box"></div>
-                <p>或者添加机器人账号 <a href="https://t.me/{$telegram_bot}">@{$telegram_bot}</a>,发送下面的数字给它。
-                </p>
-                <div class="text-center">
-                    <h2><code id="code_number">{$login_number}</code></h2>
-                </div>
-            </div>
-        </div>
-        <div class="tab-pane fade" id="qrcode_login">
-            <div class="card-header">
-                <div class="card-inner">
-                    <h1 class="card-heading" style=" text-align:center;font-weight:bold;">Telegram扫码登录</h1>
-                </div>
-            </div>
-            <div class="card-inner">
-                <p>添加机器人账号 <a href="https://t.me/{$telegram_bot}">@{$telegram_bot}</a>,拍下下面这张二维码发给它。
-                </p>
-                <div class="form-group form-group-label">
-                    <div class="text-center qr-center">
-                        <div id="telegram-qr"></div>
-                    </div>
-                </div>
-
-            </div>
-        </div>
-    </div>
-</div>

+ 0 - 70
scripts/block-whoops-env.sh

@@ -1,70 +0,0 @@
-#!/bin/bash
-
-check()
-{
-    dir=$(pwd)
-
-    if [[ ! -e "${dir}/vendor/filp/whoops/src/Whoops/Handler/PrettyPageHandler.php" ]];then
-        echo -e "\033[31m Please execute [composer install] first. \033[0m"
-        exit
-    fi
-
-    file="${dir}/vendor/filp/whoops/src/Whoops/Handler/PrettyPageHandler.php"
-}
-
-getline()
-{
-    del_line=$(cat -n ${file} | grep "PHP_AUTH_PW" | awk '{print $1}')
-    sed -i "${del_line}d" $file
-
-    line=$(cat -n ${file} | grep "blacklist php provided auth based values" | awk '{print $1}')
-    line=$(expr ${line} + 2)
-}
-
-backup()
-{
-    cp -f ${file} ${dir}/vendor/filp/whoops/src/Whoops/Handler/PrettyPageHandler.php.bak
-}
-
-run()
-{
-    list='key baseUrl db_host db_database db_username db_password muKey telegram_token telegram_request_token cloudflare_email cloudflare_key cloudflare_name sentry_dsn github_access_token pwdMethod salt'
-    for key in $list
-    do
-        sed -i "${line}i \ \ \ \ \ \ \ \ \$this->blacklist('_ENV', '${key}');" ${file}
-    done
-
-    masked_line=$(cat -n ${file} | grep "str_repeat" | awk '{print $1}')
-    masked_line=$(expr ${masked_line} + 2)
-
-    sed -i "${masked_line}i \ \ \ \ \ \ \ \ \ \ \ \ \}" ${file}
-    sed -i "${masked_line}i \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \$values[\$key] = '*';" ${file}
-    sed -i "${masked_line}i \ \ \ \ \ \ \ \ \ \ \ \ \if (is_array(\$superGlobal[\$key])) {" ${file}
-}
-
-tip()
-{
-    echo -e "\033[31m Important environment configuration has been blocked, but please note that even so, it is still very dangerous to open debug mode in the production environment, please close it in time. \033[0m"
-}
-
-recover()
-{
-    check
-    cp -f ${dir}/vendor/filp/whoops/src/Whoops/Handler/PrettyPageHandler.php.bak ${file}
-    echo -e "\033[32m Whoops has been restored to the original file. \033[0m"
-}
-
-main()
-{
-    check
-    getline
-    backup
-    run
-    tip
-}
-
-if [[ $1 != "recover" ]];then
-    main
-else
-    recover
-fi

+ 0 - 130
src/Controllers/AuthController.php

@@ -40,21 +40,8 @@ final class AuthController extends BaseController
             $captcha = Captcha::generate();
         }
 
-        if ($_ENV['enable_telegram_login'] === true) {
-            $login_text = TelegramSessionManager::addLoginSession();
-            $login = explode('|', $login_text);
-            $login_token = $login[0];
-            $login_number = $login[1];
-        } else {
-            $login_token = '';
-            $login_number = '';
-        }
-
         return $response->write($this->view()
-            ->assign('login_token', $login_token)
-            ->assign('login_number', $login_number)
             ->assign('base_url', $_ENV['baseUrl'])
-            ->assign('telegram_bot', $_ENV['telegram_bot'])
             ->assign('captcha', $captcha)
             ->fetch('auth/login.tpl'));
     }
@@ -122,27 +109,6 @@ final class AuthController extends BaseController
         ]);
     }
 
-    /**
-     * @param array     $args
-     */
-    public function qrcodeLoginHandle(ServerRequest $request, Response $response, array $args)
-    {
-        $token = $request->getParam('token');
-        $number = $request->getParam('number');
-
-        $ret = TelegramSessionManager::step2VerifyLoginSession($token, $number);
-        if ($ret === 0) {
-            return ResponseHelper::error($response, '此令牌无法被使用。');
-        }
-
-        $user = User::find($ret);
-
-        Auth::login($user->id, 3600 * 24);
-        // 记录登录成功
-        $user->collectLoginIP($_SERVER['REMOTE_ADDR']);
-        return ResponseHelper::successfully($response, '登录成功');
-    }
-
     /**
      * @param array     $args
      */
@@ -161,22 +127,9 @@ final class AuthController extends BaseController
             $code = $antiXss->xss_clean($ary['code']);
         }
 
-        if ($_ENV['enable_telegram_login'] === true) {
-            $login_text = TelegramSessionManager::addLoginSession();
-            $login = explode('|', $login_text);
-            $login_token = $login[0];
-            $login_number = $login[1];
-        } else {
-            $login_token = '';
-            $login_number = '';
-        }
-
         return $response->write($this->view()
             ->assign('code', $code)
             ->assign('base_url', $_ENV['baseUrl'])
-            ->assign('login_token', $login_token)
-            ->assign('login_number', $login_number)
-            ->assign('telegram_bot', $_ENV['telegram_bot'])
             ->assign('enable_email_verify', Setting::obtain('reg_email_verify'))
             ->assign('captcha', $captcha)
             ->fetch('auth/register.tpl'));
@@ -456,87 +409,4 @@ final class AuthController extends BaseController
         return $response->withStatus(302)
             ->withHeader('Location', '/auth/login');
     }
-
-    /**
-     * @param array     $args
-     */
-    public function qrcodeCheck(ServerRequest $request, Response $response, array $args)
-    {
-        $token = $request->getParam('token');
-        $number = $request->getParam('number');
-        $user = Auth::getUser();
-
-        if ($user->isLogin) {
-            return ResponseHelper::error($response, '用户已登陆');
-        }
-
-        if ($_ENV['enable_telegram_login'] === true) {
-            $ret = TelegramSessionManager::checkLoginSession($token, $number);
-            return $response->withJson([
-                'ret' => $ret,
-            ]);
-        }
-
-        return ResponseHelper::error($response, '不允许 QRCode 登陆');
-    }
-
-    /**
-     * @param array     $args
-     */
-    public function telegramOauth(ServerRequest $request, Response $response, array $args)
-    {
-        if ($_ENV['enable_telegram_login'] === true) {
-            $auth_data = $request->getQueryParams();
-            if ($this->telegramOauthCheck($auth_data) === true) { // Looks good, proceed.
-                $telegram_id = $auth_data['id'];
-                $user = User::query()->where('telegram_id', $telegram_id)->firstOrFail(); // Welcome Back :)
-                if ($user === null) {
-                    return $response->write($this->view()
-                        ->assign('title', '您需要先进行邮箱注册后绑定Telegram才能使用授权登录')
-                        ->assign('message', '很抱歉带来的不便,请重新试试')
-                        ->assign('redirect', '/auth/login')
-                        ->fetch('telegram_error.tpl'));
-                }
-                Auth::login($user->id, 3600);
-                $user->collectLoginIP($_SERVER['REMOTE_ADDR']);
-
-                return $response->write($this->view()
-                    ->assign('title', '登录成功')
-                    ->assign('message', '正在前往仪表盘')
-                    ->assign('redirect', '/user')
-                    ->fetch('telegram_success.tpl'));
-            }
-            return $response->write($this->view()
-                ->assign('title', '登陆超时或非法构造信息')
-                ->assign('message', '很抱歉带来的不便,请重新试试')
-                ->assign('redirect', '/auth/login')
-                ->fetch('telegram_error.tpl'));
-        }
-        return $response->withRedirect('/404');
-    }
-
-    /**
-     * @param array     $args
-     */
-    private function telegramOauthCheck($auth_data)
-    {
-        $check_hash = $auth_data['hash'];
-        $bot_token = $_ENV['telegram_token'];
-        unset($auth_data['hash']);
-        $data_check_arr = [];
-        foreach ($auth_data as $key => $value) {
-            $data_check_arr[] = $key . '=' . $value;
-        }
-        sort($data_check_arr);
-        $data_check_string = implode("\n", $data_check_arr);
-        $secret_key = \hash('sha256', $bot_token, true);
-        $hash = hash_hmac('sha256', $data_check_string, $secret_key);
-        if (strcmp($hash, $check_hash) !== 0) {
-            return false; // Bad Data :(
-        }
-        if (\time() - $auth_data['auth_date'] > 300) { // Expire @ 5mins
-            return false;
-        }
-        return true; // Good to Go
-    }
 }

+ 22 - 40
src/Utils/Telegram/Message.php

@@ -57,51 +57,33 @@ final class Message
             $MessageData = trim($this->Message->getText());
             if ($this->ChatID > 0) {
                 // 私聊
-                if ($this->User !== null) {
-                    if (is_numeric($MessageData) && strlen((string) $MessageData) === 6) {
-                        $uid = TelegramSessionManager::verifyLoginNumber($MessageData, $this->User->id);
-                        if ($uid !== 0) {
-                            $text = '登录验证成功,邮箱:' . $this->User->email;
+                if (strlen($MessageData) === 16) {
+                    $Uid = TelegramSessionManager::verifyBindSession($MessageData);
+                    if ($Uid === 0) {
+                        $text = '绑定失败了呢,经检查发现:【' . $MessageData . '】的有效期为 10 分钟,您可以在我们网站上的 **资料编辑** 页面刷新后重试.';
+                    } else {
+                        $BinsUser = TelegramTools::getUser($Uid, 'id');
+                        $BinsUser->telegram_id = $this->triggerUser['id'];
+                        $BinsUser->im_type = 4;
+                        $BinsUser->im_value = $this->triggerUser['username'];
+                        $BinsUser->save();
+                        if ($BinsUser->is_admin >= 1) {
+                            $text = '尊敬的**管理员**您好,恭喜绑定成功。' . PHP_EOL . '当前绑定邮箱为:' . $BinsUser->email;
                         } else {
-                            $text = '登录验证失败,数字无效';
-                        }
-                        $bot->sendMessage(
-                            [
-                                'chat_id' => $this->ChatID,
-                                'text' => $text,
-                                'parse_mode' => 'Markdown',
-                            ]
-                        );
-                    }
-                } else {
-                    if (strlen($MessageData) === 16) {
-                        $Uid = TelegramSessionManager::verifyBindSession($MessageData);
-                        if ($Uid === 0) {
-                            $text = '绑定失败了呢,经检查发现:【' . $MessageData . '】的有效期为 10 分钟,您可以在我们网站上的 **资料编辑** 页面刷新后重试.';
-                        } else {
-                            $BinsUser = TelegramTools::getUser($Uid, 'id');
-                            $BinsUser->telegram_id = $this->triggerUser['id'];
-                            $BinsUser->im_type = 4;
-                            $BinsUser->im_value = $this->triggerUser['username'];
-                            $BinsUser->save();
-                            if ($BinsUser->is_admin >= 1) {
-                                $text = '尊敬的**管理员**您好,恭喜绑定成功。' . PHP_EOL . '当前绑定邮箱为:' . $BinsUser->email;
+                            if ($BinsUser->class >= 1) {
+                                $text = '尊敬的 **VIP ' . $BinsUser->class . '** 用户您好.' . PHP_EOL . '恭喜您绑定成功,当前绑定邮箱为:' . $BinsUser->email;
                             } else {
-                                if ($BinsUser->class >= 1) {
-                                    $text = '尊敬的 **VIP ' . $BinsUser->class . '** 用户您好.' . PHP_EOL . '恭喜您绑定成功,当前绑定邮箱为:' . $BinsUser->email;
-                                } else {
-                                    $text = '绑定成功了,您的邮箱为:' . $BinsUser->email;
-                                }
+                                $text = '绑定成功了,您的邮箱为:' . $BinsUser->email;
                             }
                         }
-                        $this->bot->sendMessage(
-                            [
-                                'chat_id' => $this->ChatID,
-                                'text' => $text,
-                                'parse_mode' => 'Markdown',
-                            ]
-                        );
                     }
+                    $this->bot->sendMessage(
+                        [
+                            'chat_id' => $this->ChatID,
+                            'text' => $text,
+                            'parse_mode' => 'Markdown',
+                        ]
+                    );
                 }
             }
             return;

+ 0 - 72
src/Utils/TelegramSessionManager.php

@@ -22,21 +22,6 @@ final class TelegramSessionManager
         return "couldn't alloc token";
     }
 
-    public static function generateLoginRandomLink()
-    {
-        $i = 0;
-        for ($i = 0; $i < 10; $i++) {
-            $token = Tools::genRandomChar(16);
-            $number = random_int(100000, 999999);
-            $Elink = TelegramSession::where('session_content', 'LIKE', $token . '|%')->orWhere('session_content', 'LIKE', '%|' . $number)->first();
-            if ($Elink === null) {
-                return $token . '|' . $number;
-            }
-        }
-
-        return "couldn't alloc token";
-    }
-
     public static function addBindSession($user)
     {
         $Elink = TelegramSession::where('type', '=', 0)->where('user_id', '=', $user->id)->first();
@@ -67,61 +52,4 @@ final class TelegramSessionManager
         }
         return 0;
     }
-
-    public static function addLoginSession()
-    {
-        $NLink = new TelegramSession();
-        $NLink->type = 1;
-        $NLink->user_id = 0;
-        $NLink->datetime = \time();
-        $NLink->session_content = self::generateLoginRandomLink();
-        $NLink->save();
-
-        return $NLink->session_content;
-    }
-
-    public static function verifyLoginSession($token, $uid)
-    {
-        $Elink = TelegramSession::where('type', '=', 1)->where('user_id', 0)->where('session_content', 'LIKE', $token . '|%')->where('datetime', '>', \time() - 90)->orderBy('datetime', 'desc')->first();
-        if ($Elink !== null) {
-            $Elink->user_id = $uid;
-            $Elink->save();
-            return $uid;
-        }
-        return 0;
-    }
-
-    public static function verifyLoginNumber($token, $uid)
-    {
-        $Elink = TelegramSession::where('type', '=', 1)->where('user_id', 0)->where('session_content', 'LIKE', '%|' . $token)->where('datetime', '>', \time() - 90)->orderBy('datetime', 'desc')->first();
-        if ($Elink !== null) {
-            $Elink->user_id = $uid;
-            $Elink->save();
-            return $uid;
-        }
-        return 0;
-    }
-
-    public static function step2VerifyLoginSession($token, $number)
-    {
-        $Elink = TelegramSession::where('type', '=', 1)->where('session_content', $token . '|' . $number)->where('datetime', '>', \time() - 90)->orderBy('datetime', 'desc')->first();
-        if ($Elink !== null) {
-            $uid = $Elink->user_id;
-            $Elink->delete();
-            return $uid;
-        }
-        return 0;
-    }
-
-    public static function checkLoginSession($token, $number)
-    {
-        $Elink = TelegramSession::where('type', '=', 1)->where('session_content', $token . '|' . $number)->orderBy('datetime', 'desc')->first();
-        if ($Elink !== null) {
-            if ($Elink->datetime < \time() - 90) {
-                return -1;
-            }
-            return $Elink->user_id;
-        }
-        return 0;
-    }
 }