浏览代码

feat: tg & discord oauth services

M1Screw 2 年之前
父节点
当前提交
382e34bc4e

+ 7 - 6
app/routes.php

@@ -17,8 +17,11 @@ return static function (Slim\App $app): void {
     $app->get('/404', App\Controllers\HomeController::class . ':notFound');
     $app->get('/405', App\Controllers\HomeController::class . ':methodNotAllowed');
     $app->get('/500', App\Controllers\HomeController::class . ':internalServerError');
-    // Telegram
-    $app->post('/telegram_callback', App\Controllers\HomeController::class . ':telegram');
+    // Bot Callback
+    $app->post('/callback/{type}', App\Controllers\CallbackController::class . ':index');
+    // OAuth
+    $app->post('/oauth/{type}', App\Controllers\OAuthController::class . ':index');
+    $app->get('/oauth/{type}', App\Controllers\OAuthController::class . ':index');
     // User Center
     $app->group('/user', static function (RouteCollectorProxy $group): void {
         $group->get('', App\Controllers\UserController::class . ':index');
@@ -49,15 +52,15 @@ return static function (Slim\App $app): void {
         $group->get('/edit', App\Controllers\User\InfoController::class . ':index');
         $group->post('/email', App\Controllers\User\InfoController::class . ':updateEmail');
         $group->post('/username', App\Controllers\User\InfoController::class . ':updateUsername');
+        $group->post('/unbind_im', App\Controllers\User\InfoController::class . ':unbindIM');
         $group->post('/password', App\Controllers\User\InfoController::class . ':updatePassword');
-        $group->post('/contact_update', App\Controllers\User\InfoController::class . ':updateContact');
         $group->post('/theme', App\Controllers\User\InfoController::class . ':updateTheme');
         $group->post('/daily_mail', App\Controllers\User\InfoController::class . ':updateDailyMail');
         $group->post('/passwd_reset', App\Controllers\User\InfoController::class . ':resetPasswd');
         $group->post('/apitoken_reset', App\Controllers\User\InfoController::class . ':resetApiToken');
         $group->post('/method', App\Controllers\User\InfoController::class . ':updateMethod');
         $group->post('/url_reset', App\Controllers\User\InfoController::class . ':resetURL');
-        $group->put('/invite', App\Controllers\User\InfoController::class . ':resetInviteURL');
+        $group->post('/invite_reset', App\Controllers\User\InfoController::class . ':resetInviteURL');
         $group->post('/kill', App\Controllers\User\InfoController::class . ':sendToGulag');
         // 发送验证邮件
         $group->post('/send', App\Controllers\AuthController::class . ':sendVerify');
@@ -67,8 +70,6 @@ return static function (Slim\App $app): void {
         $group->post('/ga_check', App\Controllers\User\MFAController::class . ':checkGa');
         $group->post('/ga_set', App\Controllers\User\MFAController::class . ':setGa');
         $group->post('/ga_reset', App\Controllers\User\MFAController::class . ':resetGa');
-        // Telegram
-        $group->post('/telegram_reset', App\Controllers\UserController::class . ':resetTelegram');
         // 深色模式切换
         $group->post('/switch_theme_mode', App\Controllers\UserController::class . ':switchThemeMode');
         // 记录

+ 12 - 12
composer.lock

@@ -123,16 +123,16 @@
         },
         {
             "name": "aws/aws-sdk-php",
-            "version": "3.277.11",
+            "version": "3.278.0",
             "source": {
                 "type": "git",
                 "url": "https://github.com/aws/aws-sdk-php.git",
-                "reference": "c34f137abd571a9a19e290ce0b6fc6fc80f559b6"
+                "reference": "494c3bcd0e1f99aed7ef8b90e3a413d82f6c7e4d"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/c34f137abd571a9a19e290ce0b6fc6fc80f559b6",
-                "reference": "c34f137abd571a9a19e290ce0b6fc6fc80f559b6",
+                "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/494c3bcd0e1f99aed7ef8b90e3a413d82f6c7e4d",
+                "reference": "494c3bcd0e1f99aed7ef8b90e3a413d82f6c7e4d",
                 "shasum": ""
             },
             "require": {
@@ -212,9 +212,9 @@
             "support": {
                 "forum": "https://forums.aws.amazon.com/forum.jspa?forumID=80",
                 "issues": "https://github.com/aws/aws-sdk-php/issues",
-                "source": "https://github.com/aws/aws-sdk-php/tree/3.277.11"
+                "source": "https://github.com/aws/aws-sdk-php/tree/3.278.0"
             },
-            "time": "2023-08-08T18:06:20+00:00"
+            "time": "2023-08-10T18:15:03+00:00"
         },
         {
             "name": "bacon/bacon-qr-code",
@@ -4760,16 +4760,16 @@
         },
         {
             "name": "stripe/stripe-php",
-            "version": "v10.20.0",
+            "version": "v10.21.0",
             "source": {
                 "type": "git",
                 "url": "https://github.com/stripe/stripe-php.git",
-                "reference": "6be8827ee0d6466bf48e2b6997a8feac596405f9"
+                "reference": "b4ab319731958077227fad1874a3671458c5d593"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/stripe/stripe-php/zipball/6be8827ee0d6466bf48e2b6997a8feac596405f9",
-                "reference": "6be8827ee0d6466bf48e2b6997a8feac596405f9",
+                "url": "https://api.github.com/repos/stripe/stripe-php/zipball/b4ab319731958077227fad1874a3671458c5d593",
+                "reference": "b4ab319731958077227fad1874a3671458c5d593",
                 "shasum": ""
             },
             "require": {
@@ -4815,9 +4815,9 @@
             ],
             "support": {
                 "issues": "https://github.com/stripe/stripe-php/issues",
-                "source": "https://github.com/stripe/stripe-php/tree/v10.20.0"
+                "source": "https://github.com/stripe/stripe-php/tree/v10.21.0"
             },
-            "time": "2023-08-03T20:01:03+00:00"
+            "time": "2023-08-11T00:23:24+00:00"
         },
         {
             "name": "symfony/deprecation-contracts",

+ 30 - 0
config/settings.json

@@ -959,6 +959,36 @@
         "default": "",
         "mark": "Discord Bot Token"
     },
+    {
+        "id": null,
+        "item": "discord_client_id",
+        "value": "0",
+        "class": "discord",
+        "is_public": 0,
+        "type": "int",
+        "default": "0",
+        "mark": "Discord Client ID"
+    },
+    {
+        "id": null,
+        "item": "discord_client_secret",
+        "value": "",
+        "class": "discord",
+        "is_public": 0,
+        "type": "string",
+        "default": "",
+        "mark": "Discord Client Secret"
+    },
+    {
+        "id": null,
+        "item": "discord_guild_id",
+        "value": "0",
+        "class": "discord",
+        "is_public": 0,
+        "type": "int",
+        "default": "0",
+        "mark": "Discord Guild ID"
+    },
     {
         "id": null,
         "item": "slack_token",

+ 1 - 1
db/migrations/2023020100-init.php

@@ -285,7 +285,7 @@ return new class() implements MigrationInterface {
                 `node_speedlimit` double NOT NULL DEFAULT 0 COMMENT '用户限速',
                 `node_iplimit` smallint(6) unsigned NOT NULL DEFAULT 0 COMMENT '同时可连接IP数',
                 `is_admin` tinyint(1) unsigned NOT NULL DEFAULT 0 COMMENT '是否管理员',
-                `im_type` smallint(6) unsigned NOT NULL DEFAULT 1 COMMENT '联系方式类型',
+                `im_type` smallint(6) unsigned NOT NULL DEFAULT 0 COMMENT '联系方式类型',
                 `im_value` varchar(255) NOT NULL DEFAULT '' COMMENT '联系方式',
                 `daily_mail_enable` tinyint(1) NOT NULL DEFAULT 0 COMMENT '每日报告开关',
                 `class` smallint(5) unsigned NOT NULL DEFAULT 0 COMMENT '等级',

+ 28 - 0
db/migrations/2023080900-update_user_im_type.php

@@ -0,0 +1,28 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Interfaces\MigrationInterface;
+use App\Services\DB;
+
+return new class() implements MigrationInterface {
+    public function up(): int
+    {
+        DB::getPdo()->exec("
+            ALTER TABLE user MODIFY COLUMN `im_type` smallint(6) unsigned NOT NULL DEFAULT 0 COMMENT '联系方式类型';
+            UPDATE user SET `im_value` = `telegram_id` WHERE `im_type` = 4;
+            UPDATE user SET `im_value` = '' WHERE `im_value` = '0';
+        ");
+
+        return 2023080900;
+    }
+
+    public function down(): int
+    {
+        DB::getPdo()->exec("
+            ALTER TABLE user MODIFY COLUMN `im_type` smallint(6) unsigned NOT NULL DEFAULT 1 COMMENT '联系方式类型';
+        ");
+
+        return 2023072000;
+    }
+};

+ 19 - 1
resources/views/tabler/admin/setting/im.tpl

@@ -305,6 +305,24 @@
                                         <input id="discord_bot_token" type="text" class="form-control" value="{$settings['discord_bot_token']}">
                                     </div>
                                 </div>
+                                <div class="form-group mb-3 row">
+                                    <label class="form-label col-3 col-form-label">Client ID</label>
+                                    <div class="col">
+                                        <input id="discord_client_id" type="text" class="form-control" value="{$settings['discord_client_id']}">
+                                    </div>
+                                </div>
+                                <div class="form-group mb-3 row">
+                                    <label class="form-label col-3 col-form-label">Client Secret</label>
+                                    <div class="col">
+                                        <input id="discord_client_secret" type="text" class="form-control" value="{$settings['discord_client_secret']}">
+                                    </div>
+                                </div>
+                                <div class="form-group mb-3 row">
+                                    <label class="form-label col-3 col-form-label">Guild ID</label>
+                                    <div class="col">
+                                        <input id="discord_guild_id" type="text" class="form-control" value="{$settings['discord_guild_id']}">
+                                    </div>
+                                </div>
                                 <div class="form-group mb-3 row">
                                     <label class="form-label col-3 col-form-label">Discord 用户 ID</label>
                                     <input type="text" class="form-control" id="discord_user_id" value="">
@@ -426,4 +444,4 @@
     });
 </script>
 
-{include file='admin/footer.tpl'}
+{include file='admin/footer.tpl'}

+ 138 - 114
resources/views/tabler/user/edit.tpl

@@ -81,7 +81,7 @@
                                                             class="btn btn-primary ms-auto">修改</button>
                                                         {else}
                                                         <button id="modify-email" class="btn btn-primary ms-auto"
-                                                            disabled>不允许修改</button>
+                                                            disabled>不允许修改</button>
                                                         {/if}
                                                     </div>
                                                 </div>
@@ -90,25 +90,16 @@
                                         <div class="col-sm-12 col-md-6">
                                             <div class="card">
                                                 <div class="card-body">
-                                                    <h3 class="card-title">IM 账号</h3>
-                                                    <div class="mb-3">
-                                                        <select id="imtype" class="form-select">
-                                                            <option value="1" {if $user->im_type === 1}selected{/if}>
-                                                                Slack</option>
-                                                            <option value="2" {if $user->im_type === 2}selected{/if}>
-                                                                Discord</option>
-                                                            <option value="4" {if $user->im_type === 4}selected{/if}>
-                                                                Telegram</option>
-                                                        </select>
-                                                    </div>
+                                                    <h3 class="card-title">用戶名</h3>
+                                                    <p>当前用戶名:<code>{$user->user_name}</code></p>
                                                     <div class="mb-3">
-                                                        <input id="imvalue" type="text" class="form-control" 
-                                                            disabled="" value="{$user->im_value}" placeholder="社交账户">
+                                                        <input id="new-nickname" type="text" class="form-control"
+                                                               placeholder="新用戶名" autocomplete="off">
                                                     </div>
                                                 </div>
                                                 <div class="card-footer">
                                                     <div class="d-flex">
-                                                        <a id="modify-im" class="btn btn-primary ms-auto">修改</a>
+                                                        <a id="modify-username" class="btn btn-primary ms-auto">修改</a>
                                                     </div>
                                                 </div>
                                             </div>
@@ -116,76 +107,55 @@
                                         <div class="col-sm-12 col-md-6">
                                             <div class="card">
                                                 <div class="card-body">
-                                                    <h3 class="card-title">用戶名</h3>
-                                                    <p>当前用戶名:<code>{$user->user_name}</code></p>
+                                                    <h3 class="card-title">IM 账号绑定</h3>
                                                     <div class="mb-3">
-                                                        <input id="new-nickname" type="text" class="form-control"
-                                                        placeholder="新用戶名" autocomplete="off">
+                                                        <select id="imtype" class="form-select"
+                                                                {if $user->im_type !== 0 && $user->im_value !== ''}disabled=""{/if}>
+                                                            <option value="0" {if $user->im_type === 0}selected{/if}>
+                                                                未绑定</option>
+                                                            <option value="1" {if $user->im_type === 1}selected{/if}>
+                                                                Slack</option>
+                                                            <option value="2" {if $user->im_type === 2}selected{/if}>
+                                                                Discord</option>
+                                                            <option value="4" {if $user->im_type === 4}selected{/if}>
+                                                                Telegram</option>
+                                                        </select>
+                                                    </div>
+                                                    <div class="mb-3">
+                                                        <input id="imvalue" type="text" class="form-control"
+                                                            disabled="" value="{$user->im_value}">
                                                     </div>
                                                 </div>
                                                 <div class="card-footer">
-                                                    <div class="d-flex">
-                                                        <a id="modify-username" class="btn btn-primary ms-auto">修改</a>
-                                                    </div>
+                                                    <div class="d-flex btn-list justify-content-end" id="oauth-provider"></div>
                                                 </div>
                                             </div>
                                         </div>
-                                        {if $public_setting['enable_telegram']}
                                         <div class="col-sm-12 col-md-6">
-                                            {if $user->telegram_id !== 0}
                                             <div class="card">
                                                 <div class="card-body">
-                                                    <h3 class="card-title">解绑 Telegram</h3>
-                                                    <p>当前绑定的 Telegram 账户:
-                                                        {if $user->im_value === "用戶名未设置"}
-                                                        <code>{$user->telegram_id}</code>
-                                                        {else}
-                                                        <a href="https://t.me/{$user->im_value}">@{$user->im_value}</a>
-                                                        {/if}
+                                                    <h3 class="card-title">解绑 IM 账户</h3>
+                                                    {if $user->im_type === 0}
+                                                    <p>你的账户当前没有绑定任何 IM 服务</p>
+                                                    {else}
+                                                    <p>
+                                                        当前绑定的 IM 服务:{$user->imType()}
+                                                        <br>
+                                                        账户 ID:<code>{$user->im_value}</code>
                                                     </p>
+                                                    {/if}
                                                 </div>
+                                                {if $user->im_type !== 0}
                                                 <div class="card-footer">
                                                     <div class="d-flex">
-                                                       <button id="unbind-telegram-btn" 
-                                                            class="btn btn-red ms-auto">
+                                                        <button id="unbind-im" class="btn btn-red ms-auto">
                                                             解绑
-                                                       </button>
-                                                    </div>
-                                                </div>
-                                            </div>
-                                            {else}
-                                            <div class="card">
-                                                <div class="card-body">
-                                                    <h3 class="card-title">绑定 Telegram</h3>
-                                                    <div class="row">
-                                                        <div class="col-6 col-sm-2 col-md-2 col-xl mb-3">
-                                                            手机电脑平板等如已安装 Telegram 可点击
-                                                        </div>
-                                                        <div class="col-6 col-sm-2 col-md-2 col-sm mb-3">
-                                                            <a href="https://t.me/{$public_setting['telegram_bot']}?start={$bind_token}"
-                                                                class="btn btn-primary w-100">
-                                                                一键绑定
-                                                            </a>
-                                                        </div>
-                                                    </div>
-                                                    <div class="row">
-                                                        <div class="col-6 col-sm-2 col-md-2 col-xl mb-3">
-                                                            向机器人 <a
-                                                                href="https://t.me/{$public_setting['telegram_bot']}">@{$public_setting['telegram_bot']}</a>
-                                                            发送验证码绑定
-                                                        </div>
-                                                        <div class="col-6 col-sm-2 col-md-2 col-sm mb-3">
-                                                            <button data-clipboard-text="{$bind_token}"
-                                                                class="copy btn btn-primary w-100">
-                                                                复制验证码
-                                                            </button>
-                                                        </div>
+                                                        </button>
                                                     </div>
                                                 </div>
+                                                {/if}
                                             </div>
-                                            {/if}
                                         </div>
-                                        {/if}
                                     </div>
                                 </div>
                                 <div class="tab-pane" id="login_security" role="tabpanel">
@@ -196,19 +166,18 @@
                                                     <h3 class="card-title">多因素认证</h3>
                                                     <div class="col-md-12">
                                                         <div class="col-sm-6 col-md-6">
-                                                            <p>
-                                                                <i class="ti ti-brand-apple"></i>
-                                                                <a target="view_window"
-                                                                    href="https://apps.apple.com/us/app/google-authenticator/id388497605">iOS 客户端
-                                                                </a>
-                                                                &nbsp;&nbsp;&nbsp;
-                                                                <i class="ti ti-brand-android"></i>
-                                                                <a target="view_window"
-                                                                    href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2">Android 客户端
-                                                                </a>
-                                                            </p>
+                                                            <i class="ti ti-brand-apple"></i>
+                                                            <a target="view_window"
+                                                                href="https://apps.apple.com/us/app/google-authenticator/id388497605">iOS 客户端
+                                                            </a>
+                                                            &nbsp;&nbsp;&nbsp;
+                                                            <i class="ti ti-brand-android"></i>
+                                                            <a target="view_window"
+                                                                href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2">Android 客户端
+                                                            </a>
                                                         </div>
                                                     </div>
+                                                    <br>
                                                     <div class="row">
                                                         <div class="col-md-3">
                                                             <p id="qrcode"></p>
@@ -288,8 +257,8 @@
                                                         <select id="user-method" class="form-select">
                                                             {foreach $methods as $method}
                                                             <option value="{$method}"
-                                                                {if $user->method === $method}selected{/if}
-                                                            >{$method}
+                                                                {if $user->method === $method}selected{/if}>
+                                                                {$method}
                                                             </option>
                                                             {/foreach}
                                                         </select>
@@ -305,13 +274,14 @@
                                         <div class="col-sm-12 col-md-6">
                                             <div class="card">
                                                 <div class="card-body">
-                                                    <h3 class="card-title">更换订阅地址</h3>
-                                                    <p>更换订阅地址后,旧的订阅地址将无法获取配置,但节点配置仍能使用。如果希望旧的节点配置不能使用,请配合修改连接密码操作</p>
+                                                    <h3 class="card-title">重置订阅地址</h3>
+                                                    <p>重置订阅地址后,旧的订阅地址将无法获取配置,但节点配置仍能使用。
+                                                        如果希望作废旧节点配置请配合重置连接密码操作</p>
                                                 </div>
                                                 <div class="card-footer">
                                                     <div class="d-flex">
                                                         <a id="reset-sub-url"
-                                                            class="btn btn-primary ms-auto bg-red">更换</a>
+                                                            class="btn btn-primary ms-auto bg-red">重置</a>
                                                     </div>
                                                 </div>
                                             </div>
@@ -326,8 +296,7 @@
                                                 </div>
                                                 <div class="card-footer">
                                                     <div class="d-flex">
-                                                        <a id="reset-passwd"
-                                                            class="btn btn-primary ms-auto bg-red">重置</a>
+                                                        <a id="reset-passwd" class="btn btn-primary ms-auto bg-red">重置</a>
                                                     </div>
                                                 </div>
                                             </div>
@@ -381,7 +350,7 @@
                                                         <a id="modify-user-theme" class="btn btn-primary ms-auto">修改</a>
                                                     </div>
                                                 </div>
-                                            </div>   
+                                            </div>
                                         </div>
                                         {if $config['enable_kill']}
                                         <div class="col-sm-12 col-md-6">
@@ -393,7 +362,7 @@
                                                 </div>
                                                 <div class="card-body">
                                                     <h3 class="card-title">删除账户数据</h3>
-                                                </div>    
+                                                </div>
                                                 <div class="card-footer">
                                                     <a href="#" class="btn btn-red" data-bs-toggle="modal"
                                                         data-bs-target="#destroy-account">
@@ -401,7 +370,7 @@
                                                         确认删除
                                                     </a>
                                                 </div>
-                                            </div>  
+                                            </div>
                                         </div>
                                         {/if}
                                     </div>
@@ -698,15 +667,11 @@
             })
         });
 
-        $("#modify-im").click(function() {
+        $("#unbind-im").click(function() {
             $.ajax({
                 type: "POST",
-                url: "/user/contact_update",
+                url: "/user/unbind_im",
                 dataType: "json",
-                data: {
-                    imtype: $('#imtype').val(),
-                    imvalue: $('#imvalue').val()
-                },
                 success: function(data) {
                     if (data.ret === 1) {
                         $('#success-message').text(data.msg);
@@ -776,26 +741,6 @@
             })
         });
 
-        $("#unbind-telegram-btn").click(function() {
-          $.ajax({
-            type: "POST",
-            url: "/user/telegram_reset",
-            dataType: "json",
-            success: function(data) {
-              if (data.ret === 1) {
-                $('#success-message').text(data.msg);
-                $('#success-dialog').modal('show');
-                setTimeout(function() {
-                  location.reload();
-                }, 1000);
-              } else {
-                $('#fail-message').text(data.msg);
-                $('#fail-dialog').modal('show');
-              }
-            }
-          })
-        });
-
         {if $config['enable_kill']}
         $("#confirm-destroy").click(function() {
             $.ajax({
@@ -817,6 +762,85 @@
             })
         });
         {/if}
+
+        {if $user->im_type === 0 && $user->im_value === ''}
+        $("#imtype").on('change', function() {
+            if ($(this).val() === '0') {
+                $('#oauth-provider').empty();
+            } else if ($(this).val() === '1') {
+                $('#oauth-provider').empty();
+                $('#oauth-provider').append(
+                    '<a id=\"bind-slack\" class=\"btn btn-azure ms-auto\">绑定 Slack<\/a>'
+                );
+            } else if ($(this).val() === '2') {
+                $('#oauth-provider').empty();
+                $('#oauth-provider').append(
+                    '<a id=\"bind-discord\" class=\"btn btn-indigo ms-auto\">绑定 Discord<\/a>'
+                );
+            } else if ($(this).val() === '4'){
+                $('#oauth-provider').empty();
+                $('#oauth-provider').append(
+                    '<script async src=\"https://telegram.org/js/telegram-widget.js?22\"' +
+                    ' data-telegram-login=\"' + "{$public_setting['telegram_bot']}" +
+                    '\" data-size=\"large" data-onauth=\"onTelegramAuth(user)\"' +
+                    ' data-request-access=\"write\"><\/script>'
+                );
+            }
+        });
+
+        $('#oauth-provider').on('click', '#bind-slack', function() {
+            $.ajax({
+                type: "POST",
+                url: "/oauth/slack",
+                dataType: "json",
+                success: function(data) {
+                    if (data.ret === 1) {
+                        $('#success-message').text(data.msg);
+                        $('#success-dialog').modal('show');
+                    } else {
+                        $('#fail-message').text(data.msg);
+                        $('#fail-dialog').modal('show');
+                    }
+                }
+            })
+        });
+
+        $('#oauth-provider').on('click', '#bind-discord', function() {
+            $.ajax({
+                type: "POST",
+                url: "/oauth/discord",
+                dataType: "json",
+                success: function(data) {
+                    if (data.ret === 1) {
+                        window.setTimeout(location.href=data.redir, 0);
+                    } else {
+                        $('#fail-message').text(data.msg);
+                        $('#fail-dialog').modal('show');
+                    }
+                }
+            })
+        });
+
+        function onTelegramAuth(user) {
+            $.ajax({
+                type: "POST",
+                url: "/oauth/telegram",
+                dataType: "json",
+                data: {
+                    user: JSON.stringify(user),
+                },
+                success: function(data) {
+                    if (data.ret === 1) {
+                        $('#success-message').text(data.msg);
+                        $('#success-dialog').modal('show');
+                    } else {
+                        $('#error-message').text(data.msg);
+                        $('#fail-dialog').modal('show');
+                    }
+                }
+            })
+        }
+        {/if}
     </script>
-    
+
 {include file='user/footer.tpl'}

+ 4 - 4
resources/views/tabler/user/invite.tpl

@@ -1,7 +1,7 @@
 {include file='user/header.tpl'}
 
 <div class="page-wrapper">
-    <div class="container-xl">       
+    <div class="container-xl">
         <div class="page-header d-print-none text-white">
             <div class="row align-items-center">
                 <div class="col">
@@ -93,8 +93,8 @@
 
         $("#reset-url").click(function() {
             $.ajax({
-                type: "PUT",
-                url: "/user/invite",
+                type: "POST",
+                url: "/user/invite_reset",
                 dataType: "json",
                 success: function(data) {
                     if (data.ret === 1) {
@@ -109,4 +109,4 @@
         });
     </script>
 
-{include file='user/footer.tpl'}
+{include file='user/footer.tpl'}

+ 2 - 2
src/Command/Tool.php

@@ -72,7 +72,7 @@ EOL;
      */
     public function setTelegram(): void
     {
-        $WebhookUrl = $_ENV['baseUrl'] . '/telegram_callback?token=' . Setting::obtain('telegram_request_token');
+        $WebhookUrl = $_ENV['baseUrl'] . '/callback/telegram?token=' . Setting::obtain('telegram_request_token');
         $telegram = new Api(Setting::obtain('telegram_token'));
         $telegram->removeWebhook();
 
@@ -333,7 +333,7 @@ EOL;
             $user->expire_in = date('Y-m-d H:i:s');
             $user->reg_date = date('Y-m-d H:i:s');
             $user->money = 0;
-            $user->im_type = 1;
+            $user->im_type = 0;
             $user->im_value = '';
             $user->class = 0;
             $user->node_iplimit = 0;

+ 3 - 0
src/Controllers/Admin/Setting/ImController.php

@@ -49,6 +49,9 @@ final class ImController extends BaseController
         'help_any_command',
         'user_not_bind_reply',
         'discord_bot_token',
+        'discord_client_id',
+        'discord_client_secret',
+        'discord_guild_id',
         'slack_token',
     ];
 

+ 1 - 1
src/Controllers/Admin/UserController.php

@@ -135,7 +135,7 @@ final class UserController extends BaseController
             $password = Tools::genRandomChar(16);
         }
 
-        AuthController::registerHelper($response, 'user', $email, $password, '', 1, '', 0, $balance, 1);
+        AuthController::registerHelper($response, 'user', $email, $password, '', 0, '', $balance, 1);
         $user = User::where('email', $email)->first();
 
         if ($ref_by !== '') {

+ 2 - 5
src/Controllers/AuthController.php

@@ -220,7 +220,6 @@ final class AuthController extends BaseController
      * @param $code
      * @param $imtype
      * @param $imvalue
-     * @param $telegram_id
      * @param $money
      * @param $is_admin_reg
      *
@@ -236,7 +235,6 @@ final class AuthController extends BaseController
         $code,
         $imtype,
         $imvalue,
-        $telegram_id,
         $money,
         $is_admin_reg
     ): ResponseInterface {
@@ -260,7 +258,6 @@ final class AuthController extends BaseController
         $user->forbidden_port = Setting::obtain('reg_forbidden_port');
         $user->im_type = $imtype;
         $user->im_value = $imvalue;
-        $user->telegram_id = $telegram_id;
 
         $user->transfer_enable = Tools::toGB($configs['sign_up_for_free_traffic']);
         $user->invite_num = $configs['sign_up_for_invitation_codes'];
@@ -363,7 +360,7 @@ final class AuthController extends BaseController
             }
         }
 
-        $imtype = 1;
+        $imtype = 0;
         $imvalue = '';
 
         // check email format
@@ -397,7 +394,7 @@ final class AuthController extends BaseController
             $redis->del('email_verify:' . $email_verify_code);
         }
 
-        return $this->registerHelper($response, $name, $email, $passwd, $code, $imtype, $imvalue, 0, 0, 0);
+        return $this->registerHelper($response, $name, $email, $passwd, $code, $imtype, $imvalue, 0, 0);
     }
 
     public function logout(ServerRequest $request, Response $response, $next): Response

+ 54 - 0
src/Controllers/CallbackController.php

@@ -0,0 +1,54 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Controllers;
+
+use App\Models\Setting;
+use App\Utils\Telegram\Process;
+use MaxMind\Db\Reader\InvalidDatabaseException;
+use Psr\Http\Message\ResponseInterface;
+use RedisException;
+use Slim\Http\Response;
+use Slim\Http\ServerRequest;
+use SmartyException;
+use Telegram\Bot\Exceptions\TelegramSDKException;
+
+/**
+ *  CallbackController
+ */
+final class CallbackController extends BaseController
+{
+    /**
+     * @throws RedisException
+     * @throws InvalidDatabaseException
+     * @throws SmartyException
+     * @throws TelegramSDKException
+     */
+    public function index(ServerRequest $request, Response $response, array $args): ResponseInterface
+    {
+        return match ($args['type']) {
+            'telegram' => $this->telegram($request, $response, $args),
+            default => $response->withStatus(404)->write($this->view()->fetch('404.tpl')),
+        };
+    }
+
+    /**
+     * @throws TelegramSDKException
+     * @throws RedisException
+     * @throws InvalidDatabaseException
+     */
+    public function telegram(ServerRequest $request, Response $response, array $args): ResponseInterface
+    {
+        $token = $request->getQueryParam('token');
+
+        if (Setting::obtain('enable_telegram') && $token === Setting::obtain('telegram_request_token')) {
+            Process::index($request);
+            $result = '1';
+        } else {
+            $result = '0';
+        }
+
+        return $response->write($result);
+    }
+}

+ 8 - 31
src/Controllers/HomeController.php

@@ -4,16 +4,11 @@ declare(strict_types=1);
 
 namespace App\Controllers;
 
-use App\Models\Setting;
 use App\Services\Auth;
-use App\Utils\Telegram\Process;
-use Exception;
-use MaxMind\Db\Reader\InvalidDatabaseException;
 use Psr\Http\Message\ResponseInterface;
-use RedisException;
 use Slim\Http\Response;
 use Slim\Http\ServerRequest;
-use Telegram\Bot\Exceptions\TelegramSDKException;
+use SmartyException;
 
 /**
  *  HomeController
@@ -21,7 +16,7 @@ use Telegram\Bot\Exceptions\TelegramSDKException;
 final class HomeController extends BaseController
 {
     /**
-     * @throws Exception
+     * @throws SmartyException
      */
     public function index(ServerRequest $request, Response $response, array $args): ResponseInterface
     {
@@ -29,7 +24,7 @@ final class HomeController extends BaseController
     }
 
     /**
-     * @throws Exception
+     * @throws SmartyException
      */
     public function tos(ServerRequest $request, Response $response, array $args): ResponseInterface
     {
@@ -37,11 +32,12 @@ final class HomeController extends BaseController
     }
 
     /**
-     * @throws Exception
+     * @throws SmartyException
      */
     public function staff(ServerRequest $request, Response $response, array $args): ResponseInterface
     {
         $user = Auth::getUser();
+
         if (! $user->isLogin) {
             return $response->withStatus(404)->write($this->view()->fetch('404.tpl'));
         }
@@ -50,7 +46,7 @@ final class HomeController extends BaseController
     }
 
     /**
-     * @throws Exception
+     * @throws SmartyException
      */
     public function notFound(ServerRequest $request, Response $response, array $args): ResponseInterface
     {
@@ -58,7 +54,7 @@ final class HomeController extends BaseController
     }
 
     /**
-     * @throws Exception
+     * @throws SmartyException
      */
     public function methodNotAllowed(ServerRequest $request, Response $response, array $args): ResponseInterface
     {
@@ -66,29 +62,10 @@ final class HomeController extends BaseController
     }
 
     /**
-     * @throws Exception
+     * @throws SmartyException
      */
     public function internalServerError(ServerRequest $request, Response $response, array $args): ResponseInterface
     {
         return $response->write($this->view()->fetch('500.tpl'));
     }
-
-    /**
-     * @throws TelegramSDKException
-     * @throws RedisException
-     * @throws InvalidDatabaseException
-     */
-    public function telegram(ServerRequest $request, Response $response, array $args): ResponseInterface
-    {
-        $token = $request->getQueryParam('token');
-
-        if (Setting::obtain('enable_telegram') && $token === Setting::obtain('telegram_request_token')) {
-            Process::index($request);
-            $result = '1';
-        } else {
-            $result = '0';
-        }
-
-        return $response->write($result);
-    }
 }

+ 186 - 0
src/Controllers/OAuthController.php

@@ -0,0 +1,186 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Controllers;
+
+use App\Models\Setting;
+use App\Models\User;
+use App\Services\Cache;
+use App\Utils\ResponseHelper;
+use App\Utils\Tools;
+use GuzzleHttp\Client;
+use GuzzleHttp\Exception\GuzzleException;
+use Psr\Http\Message\ResponseInterface;
+use RedisException;
+use Slim\Http\Response;
+use Slim\Http\ServerRequest;
+use SmartyException;
+use voku\helper\AntiXSS;
+use function hash;
+use function hash_hmac;
+use function implode;
+use function json_decode;
+use function strcmp;
+use function time;
+
+/**
+ *  OAuthController
+ */
+final class OAuthController extends BaseController
+{
+    /**
+     * @throws SmartyException
+     * @throws GuzzleException
+     * @throws RedisException
+     */
+    public function index(ServerRequest $request, Response $response, array $args): ResponseInterface
+    {
+        return match ($args['type']) {
+            'slack' => $this->slack($request, $response, $args),
+            'discord' => $this->discord($request, $response, $args),
+            'telegram' => $this->telegram($request, $response, $args),
+            default => $response->withStatus(404)->write($this->view()->fetch('404.tpl')),
+        };
+    }
+
+    public function slack(ServerRequest $request, Response $response, array $args): ResponseInterface
+    {
+        return ResponseHelper::error($response, '暂不支持');
+    }
+
+    /**
+     * @throws GuzzleException
+     * @throws RedisException
+     */
+    public function discord(ServerRequest $request, Response $response, array $args): ResponseInterface
+    {
+        $user = $this->user;
+        $redis = Cache::initRedis();
+
+        if ($request->getParam('code') === null) {
+            $state = Tools::genRandomChar(16);
+            $redis->setex('discord_state:' . $user->id, 300, $state);
+            $client_id = Setting::obtain('discord_client_id');
+            $redirect_uri = $_ENV['baseUrl'] . '/oauth/discord';
+
+            return $response->withJson([
+                'ret' => 1,
+                'redir' => 'https://discord.com/api/oauth2/authorize?client_id=' . $client_id .
+                    '&redirect_uri=' . $redirect_uri .
+                    '&response_type=code&scope=guilds.join identify&state=' . $state,
+            ]);
+        }
+
+        $code = $request->getParam('code');
+        $state = $request->getParam('state');
+
+        if ($state !== $redis->get('discord_state:' . $user->id)) {
+            return ResponseHelper::error($response, '参数错误');
+        }
+
+        $client = new Client();
+        $discord_api_url = 'https://discord.com/api/oauth2/token';
+
+        $code_headers = [
+            'Content-Type' => 'application/x-www-form-urlencoded',
+        ];
+
+        $code_body = [
+            'client_id' => Setting::obtain('discord_client_id'),
+            'client_secret' => Setting::obtain('discord_client_secret'),
+            'grant_type' => 'authorization_code',
+            'code' => $code,
+            'redirect_uri' => $_ENV['baseUrl'] . '/oauth/discord',
+        ];
+
+        $code_response = $client->post($discord_api_url, [
+            'headers' => $code_headers,
+            'form_params' => $code_body,
+        ]);
+
+        if ($code_response->getStatusCode() !== 200) {
+            return ResponseHelper::error($response, 'OAuth 请求失败');
+        }
+
+        $access_token = json_decode($code_response->getBody()->getContents())->access_token;
+        $discord_user_url = 'https://discord.com/api/users/@me';
+
+        $user_headers = [
+            'Content-Type' => 'application/x-www-form-urlencoded',
+            'Authorization' => 'Bearer ' . $access_token,
+        ];
+
+        $user_response = $client->get($discord_user_url, [
+            'headers' => $user_headers,
+        ]);
+
+        if ($user_response->getStatusCode() !== 200) {
+            return ResponseHelper::error($response, 'OAuth 请求失败');
+        }
+
+        $user->im_type = 2;
+        $user->im_value = json_decode($user_response->getBody()->getContents())->id;
+        $user->save();
+
+        if (Setting::obtain('discord_guild_id') !== 0) {
+            $discord_guild_url = 'https://discord.com/api/guilds/' . Setting::obtain('discord_guild_id') .
+                '/members/' . $user->im_value;
+
+            $guild_headers = [
+                'Content-Type' => 'application/json',
+                'Authorization' => 'Bot ' . Setting::obtain('discord_bot_token'),
+            ];
+
+            $guild_body = [
+                'access_token' => $access_token,
+            ];
+
+            $client->put($discord_guild_url, [
+                'headers' => $guild_headers,
+                'json' => $guild_body,
+            ]);
+        }
+
+        return $response->withRedirect($_ENV['baseUrl'] . '/user/edit');
+    }
+
+    public function telegram(ServerRequest $request, Response $response, array $args): ResponseInterface
+    {
+        $user_auth = json_decode($request->getParam('user'), true);
+
+        $check_hash = $user_auth['hash'];
+        unset($user_auth['hash']);
+        $data_check_arr = [];
+
+        foreach ($user_auth as $key => $value) {
+            $data_check_arr[] = $key . '=' . $value;
+        }
+
+        sort($data_check_arr);
+        $data_check_string = implode("\n", $data_check_arr);
+        $secret_key = hash('sha256', Setting::obtain('telegram_token'), true);
+        $hash = hash_hmac('sha256', $data_check_string, $secret_key);
+
+        if (strcmp($hash, $check_hash) !== 0 || (time() - $user_auth['auth_date']) > 86400) {
+            return ResponseHelper::error($response, '绑定失败');
+        }
+
+        $antiXss = new AntiXSS();
+
+        $telegram_id = $antiXss->xss_clean($user_auth['id']);
+        $user = $this->user;
+
+        if (User::where('im_type', 4)->where('im_value', $telegram_id)->first() !== null ||
+            ($user->im_type === 4 && $user->im_value === $telegram_id)) {
+            return ResponseHelper::error($response, 'Telegram 账户已绑定');
+        }
+
+        $user->im_type = 4;
+        $user->im_value = $telegram_id;
+
+        $user->save();
+
+        return ResponseHelper::success($response, '绑定成功');
+    }
+}

+ 11 - 32
src/Controllers/User/InfoController.php

@@ -13,7 +13,6 @@ use App\Services\Config;
 use App\Services\MFA;
 use App\Utils\Hash;
 use App\Utils\ResponseHelper;
-use App\Utils\Telegram\TelegramTools;
 use App\Utils\Tools;
 use Exception;
 use Psr\Http\Message\ResponseInterface;
@@ -38,14 +37,12 @@ final class InfoController extends BaseController
     public function index(ServerRequest $request, Response $response, array $args): Response|ResponseInterface
     {
         $themes = Tools::getDir(BASE_PATH . '/resources/views');
-        $bind_token = $this->user->telegram_id === 0 ? TelegramTools::addBindSession($this->user) : '';
         $methods = Config::getSupportParam('method');
         $gaurl = MFA::getGaUrl($this->user);
 
         return $response->write($this->view()
             ->assign('user', $this->user)
             ->assign('themes', $themes)
-            ->assign('bind_token', $bind_token)
             ->assign('methods', $methods)
             ->assign('gaurl', $gaurl)
             ->registerClass('Config', Config::class)
@@ -124,6 +121,17 @@ final class InfoController extends BaseController
         return ResponseHelper::success($response, '修改成功');
     }
 
+    public function unbindIM(ServerRequest $request, Response $response, array $args): ResponseInterface
+    {
+        $user = $this->user;
+
+        if (! $user->unbindIM()) {
+            return ResponseHelper::error($response, '解绑失败');
+        }
+
+        return ResponseHelper::success($response, '解绑成功');
+    }
+
     public function updatePassword(ServerRequest $request, Response $response, array $args): ResponseInterface
     {
         $oldpwd = $request->getParam('oldpwd');
@@ -158,35 +166,6 @@ final class InfoController extends BaseController
         return ResponseHelper::success($response, '修改成功');
     }
 
-    public function updateContact(ServerRequest $request, Response $response, array $args): Response|ResponseInterface
-    {
-        $antiXss = new AntiXSS();
-        $type = $antiXss->xss_clean($request->getParam('imtype'));
-        $value = $antiXss->xss_clean($request->getParam('imvalue'));
-        $user = $this->user;
-
-        if ($user->telegram_id !== null || $user->is_shadow_banned) {
-            return ResponseHelper::error($response, '修改失败');
-        }
-
-        if ($value === '' || $type === '') {
-            return ResponseHelper::error($response, '联络方式不能为空');
-        }
-
-        if (User::where('im_value', $value)->where('im_type', $type)->first() !== null) {
-            return ResponseHelper::error($response, '此联络方式已经被注册');
-        }
-
-        $user->im_type = $type;
-        $user->im_value = $value;
-
-        if (! $user->save()) {
-            return ResponseHelper::error($response, '修改失败');
-        }
-
-        return ResponseHelper::success($response, '修改成功');
-    }
-
     public function updateTheme(ServerRequest $request, Response $response, array $args): Response|ResponseInterface
     {
         $antiXss = new AntiXSS();

+ 0 - 8
src/Controllers/UserController.php

@@ -187,14 +187,6 @@ final class UserController extends BaseController
             ->fetch('user/banned.tpl'));
     }
 
-    public function resetTelegram(ServerRequest $request, Response $response, array $args): ResponseInterface
-    {
-        $user = $this->user;
-        $user->telegramReset();
-
-        return ResponseHelper::success($response, '重置成功');
-    }
-
     public function switchThemeMode(ServerRequest $request, Response $response, array $args): Response|ResponseInterface
     {
         $user = $this->user;

+ 6 - 39
src/Models/User.php

@@ -8,7 +8,6 @@ use App\Services\DB;
 use App\Services\IM\Telegram;
 use App\Services\Mail;
 use App\Utils\Hash;
-use App\Utils\Telegram\TelegramTools;
 use App\Utils\Tools;
 use Exception;
 use Psr\Http\Client\ClientExceptionInterface;
@@ -335,43 +334,11 @@ final class User extends Model
         return $return;
     }
 
-    /**
-     * 解绑 Telegram
-     */
-    public function telegramReset(): array
+    public function unbindIM(): bool
     {
-        $return = [
-            'ok' => true,
-            'msg' => '解绑成功.',
-        ];
-        $telegram_id = $this->telegram_id;
-        $this->telegram_id = 0;
-
-        if ($this->save()) {
-            if (Setting::obtain('enable_telegram')
-                &&
-                Setting::obtain('telegram_group_bound_user')
-                &&
-                Setting::obtain('telegram_unbind_kick_member')
-                &&
-                ! $this->is_admin
-            ) {
-                TelegramTools::SendPost(
-                    'kickChatMember',
-                    [
-                        'chat_id' => Setting::obtain('telegram_chatid'),
-                        'user_id' => $telegram_id,
-                    ]
-                );
-            }
-        } else {
-            $return = [
-                'ok' => false,
-                'msg' => '解绑失败.',
-            ];
-        }
-
-        return $return;
+        $this->im_type = 0;
+        $this->im_value = '';
+        return $this->save();
     }
 
     /**
@@ -426,9 +393,9 @@ final class User extends Model
     public function sendTelegram(string $text): bool
     {
         try {
-            if ($this->telegram_id > 0) {
+            if ($this->im_type === 4 && $this->im_value !== '') {
                 (new Telegram())->send(
-                    $this->telegram_id,
+                    (int) $this->im_value,
                     $text,
                 );
                 return true;

+ 1 - 1
src/Utils/Telegram/Callback.php

@@ -172,7 +172,7 @@ final class Callback
             [
                 [
                     'text' => $checkin,
-                    'callback_data' => 'user.checkin.' . $user->telegram_id,
+                    'callback_data' => 'user.checkin.' . $user->im_value,
                 ],
             ],
         ];

+ 1 - 1
src/Utils/Telegram/Commands/MyCommand.php

@@ -61,7 +61,7 @@ final class MyCommand extends Command
             'username' => $Message->getFrom()->getUsername(),
         ];
 
-        $User = User::where('telegram_id', $SendUser['id'])->first();
+        $User = User::where('im_type', 4)->where('im_value', $SendUser['id'])->first();
         if ($User === null) {
             // 回送信息
             $response = $this->replyWithMessage(

+ 0 - 51
src/Utils/Telegram/Commands/StartCommand.php

@@ -5,12 +5,9 @@ declare(strict_types=1);
 namespace App\Utils\Telegram\Commands;
 
 use App\Models\Setting;
-use App\Models\User;
-use App\Utils\Telegram\TelegramTools;
 use RedisException;
 use Telegram\Bot\Actions;
 use Telegram\Bot\Commands\Command;
-use function strlen;
 
 /**
  * Class StratCommand.
@@ -39,11 +36,8 @@ final class StartCommand extends Command
         $ChatID = $Message->getChat()->getId();
 
         if ($ChatID > 0) {
-            // 私人会话
-
             // 发送 '输入中' 会话状态
             $this->replyWithChatAction(['action' => Actions::TYPING]);
-
             // 触发用户
             $SendUser = [
                 'id' => $Message->getFrom()->getId(),
@@ -53,13 +47,6 @@ final class StartCommand extends Command
             // 消息内容
             $MessageText = explode(' ', trim($Message->getText()));
             $MessageKey = array_splice($MessageText, -1)[0];
-            if ($MessageKey !== ''
-                && TelegramTools::getUser($SendUser['id']) === null
-                && strlen($MessageKey) === 16
-            ) {
-                // 新用户绑定
-                $this->bindingAccount($SendUser, $MessageKey);
-            }
             // 回送信息
             $this->replyWithMessage(
                 [
@@ -82,42 +69,4 @@ final class StartCommand extends Command
             }
         }
     }
-
-    /**
-     * @throws RedisException
-     */
-    public function bindingAccount($SendUser, $MessageText): void
-    {
-        $Uid = TelegramTools::verifyBindSession($MessageText);
-        if ($Uid === 0) {
-            $text = '绑定失败了呢,经检查发现:【' . $MessageText . '】的有效期为 10 分钟,你可以在我们网站上的 **资料编辑** 页面刷新后重试.';
-        } else {
-            $BinsUser = User::where('id', $Uid)->first();
-            $BinsUser->telegram_id = $SendUser['id'];
-            $BinsUser->im_type = 4;
-            if ($SendUser['username'] === null) {
-                $BinsUser->im_value = '用戶名未设置';
-            } else {
-                $BinsUser->im_value = $SendUser['username'];
-            }
-            $BinsUser->save();
-            if ($BinsUser->is_admin === 1) {
-                $text = '尊敬的 **管理员** 你好,恭喜绑定成功。' . PHP_EOL . '当前绑定邮箱为: ' . $BinsUser->email;
-            } else {
-                if ($BinsUser->class >= 1) {
-                    $text = '尊敬的 **VIP ' . $BinsUser->class . '** 用户你好.' .
-                        PHP_EOL . '恭喜你绑定成功,当前绑定邮箱为: ' . $BinsUser->email;
-                } else {
-                    $text = '绑定成功了,你的邮箱为:' . $BinsUser->email;
-                }
-            }
-        }
-        // 回送信息
-        $this->replyWithMessage(
-            [
-                'text' => $text,
-                'parse_mode' => 'Markdown',
-            ]
-        );
-    }
 }

+ 1 - 1
src/Utils/Telegram/Commands/UnbindCommand.php

@@ -61,7 +61,7 @@ final class UnbindCommand extends Command
             $text = '';
 
             if ($MessageKey === $User->email) {
-                $temp = $User->telegramReset();
+                $temp = $User->unbindIM();
                 $text = $temp['msg'];
                 // 回送信息
                 $this->replyWithMessage(

+ 0 - 43
src/Utils/Telegram/Message.php

@@ -10,7 +10,6 @@ use Telegram\Bot\Api;
 use Telegram\Bot\Exceptions\TelegramSDKException;
 use function in_array;
 use function json_decode;
-use function strlen;
 
 final class Message
 {
@@ -57,48 +56,6 @@ final class Message
         $this->Message = $Message;
         $this->MessageID = $Message->getMessageId();
 
-        if ($this->Message->getText() !== null) {
-            // 消息内容
-            $MessageData = trim($this->Message->getText());
-            if ($this->ChatID > 0 && strlen($MessageData) === 16) {
-                // 私聊
-                $Uid = TelegramTools::verifyBindSession($MessageData);
-                if ($Uid === 0) {
-                    $text = '绑定失败了呢,经检查发现:【' .
-                        $MessageData . '】的有效期为 10 分钟,你可以在我们网站上的 **资料编辑** 页面刷新后重试.';
-                } else {
-                    $BinsUser = TelegramTools::getUser($Uid, 'id');
-                    $BinsUser->telegram_id = $this->triggerUser['id'];
-                    $BinsUser->im_type = 4;
-                    if ($this->triggerUser['username'] === null) {
-                        $BinsUser->im_value = '用戶名未设置';
-                    } else {
-                        $BinsUser->im_value = $this->triggerUser['username'];
-                    }
-                    $BinsUser->save();
-                    if ($BinsUser->is_admin === 1) {
-                        $text = '尊敬的**管理员**你好,恭喜绑定成功。' . PHP_EOL . '当前绑定邮箱为:' . $BinsUser->email;
-                    } else {
-                        if ($BinsUser->class >= 1) {
-                            $text = '尊敬的 **VIP ' . $BinsUser->class .
-                                '** 用户你好.' . PHP_EOL . '恭喜你绑定成功,当前绑定邮箱为:' . $BinsUser->email;
-                        } else {
-                            $text = '绑定成功了,你的邮箱为:' . $BinsUser->email;
-                        }
-                    }
-                }
-
-                $this->bot->sendMessage(
-                    [
-                        'chat_id' => $this->ChatID,
-                        'text' => $text,
-                        'parse_mode' => 'Markdown',
-                    ]
-                );
-            }
-            return;
-        }
-
         if ($this->Message->getNewChatParticipant() !== null) {
             $this->newChatParticipant();
         }

+ 2 - 49
src/Utils/Telegram/TelegramTools.php

@@ -6,10 +6,6 @@ namespace App\Utils\Telegram;
 
 use App\Models\Setting;
 use App\Models\User;
-use App\Services\Cache;
-use App\Utils\Tools;
-use RedisException;
-use voku\helper\AntiXSS;
 use function curl_close;
 use function curl_exec;
 use function curl_init;
@@ -29,9 +25,9 @@ final class TelegramTools
      * @param int $value  搜索值
      * @param string $method 查找列
      */
-    public static function getUser(int $value, string $method = 'telegram_id')
+    public static function getUser(int $value, string $method = 'im_value')
     {
-        return User::where($method, $value)->first();
+        return User::where('im_type', 4)->where($method, $value)->first();
     }
 
     /**
@@ -54,47 +50,4 @@ final class TelegramTools
         curl_exec($C);
         curl_close($C);
     }
-
-    /**
-     * @param $token
-     *
-     * @return int
-     *
-     * @throws RedisException
-     */
-    public static function verifyBindSession($token): int
-    {
-        $antiXss = new AntiXSS();
-        $redis = Cache::initRedis();
-        $uid = $redis->get('telegram_bind:' . $antiXss->xss_clean($token));
-
-        if (! $uid) {
-            return 0;
-        }
-
-        $redis->del('telegram_bind:' . $token);
-
-        return (int) $uid;
-    }
-
-    /**
-     * @param $user
-     *
-     * @return string
-     *
-     * @throws RedisException
-     */
-    public static function addBindSession($user): string
-    {
-        $redis = Cache::initRedis();
-        $token = Tools::genRandomChar(16);
-
-        $redis->setex(
-            'telegram_bind:' . $token,
-            600,
-            $user->id
-        );
-
-        return $token;
-    }
 }