feat: 实现多端飞书登录功能
1. 飞书客户端内:静默自动登录
- 检测飞书环境 (userAgent + ttjsBridge)
- 调用 ttjsBridge.getAuthCode() 获取授权码
- 自动登录到后台
2. 飞书客户端外:扫码登录
- 后端新增三个接口:
* POST /api/v1/auth/qrcode-login - 生成登录会话和二维码
* GET /api/v1/auth/qrcode-login/status - 轮询登录状态
* GET /login/qrcode/{id} - 飞书授权回调
- 前端新增 QRCodeLogin 组件:
* 使用 qrcode.react 生成二维码
* 每 2 秒轮询登录状态
* 状态:loading → pending → scanning → success/expired
3. 数据库表:feishu_login_session
- 存储 session_id, auth_url, status, user_id
- 状态:pending, scanning, success, expired
- 2 分钟过期机制
4. 其他优化
- 移除审批详情页的 header
- 更新 PROJECT_ISSUES.md 文档
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -535,3 +535,164 @@ if (in_array($userId, $approverIds)) {
|
||||
### 数据库
|
||||
- `approval_node` 表 - 删除重复节点
|
||||
- `approval_order` 表 - 修正 current_nodes 字段
|
||||
|
||||
---
|
||||
|
||||
## 24. 多端飞书登录功能实现
|
||||
|
||||
### 需求背景
|
||||
支持两种登录场景:
|
||||
1. **飞书客户端内**:静默自动登录,无需用户操作
|
||||
2. **飞书客户端外**:邮箱密码登录 + 飞书扫码登录
|
||||
|
||||
### 实现方案
|
||||
|
||||
#### 1. 飞书客户端内 - 静默授权
|
||||
**环境检测**:
|
||||
```typescript
|
||||
const ua = navigator.userAgent.toLowerCase()
|
||||
const isInFeishu = ua.includes('feishu') || ua.includes('lark') ||
|
||||
(window as any).ttjsBridge !== undefined
|
||||
```
|
||||
|
||||
**调用 ttjsBridge 获取授权码**:
|
||||
```typescript
|
||||
if ((window as any).ttjsBridge) {
|
||||
(window as any).ttjsBridge.getAuthCode({
|
||||
success: (authCode: string) => {
|
||||
handleFeishuLogin(authCode)
|
||||
},
|
||||
fail: (error: any) => {
|
||||
Toast.show('获取授权失败,请重试')
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
**相关文件**:`frontend/src/pages/login/index.tsx`
|
||||
|
||||
#### 2. 飞书客户端外 - 扫码登录
|
||||
|
||||
**后端接口**:
|
||||
1. `POST /api/v1/auth/qrcode-login` - 生成登录会话和二维码 URL
|
||||
2. `GET /api/v1/auth/qrcode-login/status?session_id={id}` - 轮询登录状态
|
||||
3. `GET /login/qrcode/{id}` - 飞书授权回调地址
|
||||
|
||||
**数据库表**:`feishu_login_session`
|
||||
- `session_id` - 会话 ID(UUID)
|
||||
- `status` - pending | scanning | success | expired
|
||||
- `auth_url` - 飞书授权 URL
|
||||
- `expires_at` - 过期时间(2分钟)
|
||||
|
||||
**前端实现**:
|
||||
- 使用 `qrcode.react` 生成二维码
|
||||
- 每 2 秒轮询一次登录状态
|
||||
- 状态更新:loading → pending → scanning → success
|
||||
|
||||
**相关文件**:
|
||||
- `frontend/src/pages/login/QRCodeLogin.tsx` - 二维码登录组件
|
||||
- `backend/app/controller/AuthController.php` - 后端接口
|
||||
- `backend/app/model/FeishuLoginSession.php` - 会话模型
|
||||
|
||||
#### 3. 登录流程图
|
||||
|
||||
```
|
||||
飞书内:
|
||||
┌─────────┐ ttjsBridge ┌──────────┐ auth_code ┌─────────┐
|
||||
│ 用户 │ ───────────────> │ 飞书API │ ──────────────> │ 后端 │
|
||||
└─────────┘ getAuthCode() └──────────┘ 静默授权 └─────────┘
|
||||
│
|
||||
v
|
||||
返回 token + user
|
||||
自动登录成功
|
||||
|
||||
飞书外(扫码):
|
||||
┌─────────┐ ┌──────────┐ ┌─────────┐
|
||||
│ 用户 │ ──> 显示二维码 ──> │ 手机扫码 │ ──> 飞书授权 ──> │ 后端 │
|
||||
└─────────┘ └──────────┘ └─────────┘
|
||||
│ │
|
||||
│ 每2秒轮询 status │
|
||||
│<─────────────────────────────────────────────────────────────│
|
||||
│ v
|
||||
│ 返回 token + user
|
||||
│<─────────────────────────────────────────────────────────────│
|
||||
│
|
||||
v
|
||||
自动登录成功
|
||||
```
|
||||
|
||||
### 关键技术点
|
||||
|
||||
1. **ttjsBridge 类型声明**:
|
||||
```typescript
|
||||
declare global {
|
||||
interface Window {
|
||||
ttjsBridge?: {
|
||||
getAuthCode: (params: any) => void
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. **登录成功事件通知**:
|
||||
```typescript
|
||||
// QRCodeLogin 组件触发事件
|
||||
window.dispatchEvent(new CustomEvent('feishu-login-success', {
|
||||
detail: { user, token }
|
||||
}))
|
||||
|
||||
// 主登录页监听事件
|
||||
useEffect(() => {
|
||||
const handleFeishuLoginSuccess = (e: any) => {
|
||||
const { user, token } = e.detail
|
||||
login(user, token)
|
||||
}
|
||||
window.addEventListener('feishu-login-success', handleFeishuLoginSuccess)
|
||||
return () => {
|
||||
window.removeEventListener('feishu-login-success', handleFeishuLoginSuccess)
|
||||
}
|
||||
}, [])
|
||||
```
|
||||
|
||||
3. **二维码状态管理**:
|
||||
```typescript
|
||||
const [status, setStatus] = useState<'loading' | 'pending' | 'scanning' | 'success' | 'expired'>('loading')
|
||||
|
||||
const getStatusColor = () => {
|
||||
switch (status) {
|
||||
case 'pending': return '#1677ff' // 蓝色 - 待扫码
|
||||
case 'scanning': return '#faad14' // 橙色 - 已扫码待确认
|
||||
case 'success': return '#52c41a' // 绿色 - 成功
|
||||
case 'expired': return '#ff4d4f' // 红色 - 过期
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 依赖安装
|
||||
```bash
|
||||
npm install qrcode.react
|
||||
```
|
||||
|
||||
### 数据库迁移
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS `feishu_login_session` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint unsigned NOT NULL COMMENT '公司ID',
|
||||
`tenant_key` varchar(64) NOT NULL COMMENT '租户密钥',
|
||||
`status` varchar(20) NOT NULL DEFAULT 'pending' COMMENT 'pending: 待扫码, scanning: 已扫码待授权, success: 登录成功, expired: 已过期',
|
||||
`user_id` bigint unsigned DEFAULT NULL COMMENT '用户ID(登录成功后填充)',
|
||||
`session_id` varchar(64) NOT NULL COMMENT '会话ID',
|
||||
`auth_url` text COMMENT '飞书授权URL',
|
||||
`expires_at` datetime NOT NULL COMMENT '过期时间',
|
||||
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_session_id` (`session_id`),
|
||||
KEY `idx_company_status` (`company_id`, `status`),
|
||||
KEY `idx_expires_at` (`expires_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='飞书扫码登录会话表';
|
||||
```
|
||||
|
||||
### 配置要求
|
||||
- 飞书应用 `tenant_key`: `14e7bc0fe5985740`
|
||||
- 飞书授权回调地址: `https://xsm.dev.hnxinyouhe.com/login/qrcode/{id}`
|
||||
|
||||
@@ -108,4 +108,160 @@ class AuthController extends BaseController
|
||||
|
||||
return $this->success($user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成飞书扫码登录二维码
|
||||
*/
|
||||
public function qrcodeLogin(Request $request): Response
|
||||
{
|
||||
$tenantKey = $request->post('tenant_key');
|
||||
|
||||
if (!$tenantKey) {
|
||||
return $this->error('缺少租户密钥');
|
||||
}
|
||||
|
||||
try {
|
||||
$feishuService = new \app\service\FeishuService();
|
||||
|
||||
// 根据 tenant_key 获取公司
|
||||
$company = $feishuService->getCompanyByTenantKey($tenantKey);
|
||||
|
||||
if (!$company) {
|
||||
return $this->error('公司不存在');
|
||||
}
|
||||
|
||||
$feishuService->setCompany($company->id);
|
||||
|
||||
// 生成登录会话
|
||||
$loginSession = \app\model\FeishuLoginSession::create([
|
||||
'company_id' => $company->id,
|
||||
'tenant_key' => $tenantKey,
|
||||
'status' => 'pending',
|
||||
'expires_at' => date('Y-m-d H:i:s', time() + 300), // 5分钟过期
|
||||
]);
|
||||
|
||||
// 构建扫码登录 URL
|
||||
$appId = 'cli_a8033d607cba500d';
|
||||
$redirectUri = urlencode("https://xsm.dev.hnxinyouhe.com/login/qrcode/{$loginSession->id}");
|
||||
$authUrl = "https://open.feishu.cn/open-apis/authen/v1/oidc/authorize?app_id={$appId}&redirect_uri={$redirectUri}&state={$loginSession->id}";
|
||||
|
||||
// 生成二维码内容(返回 URL,前端生成二维码)
|
||||
return $this->success([
|
||||
'session_id' => $loginSession->id,
|
||||
'auth_url' => $authUrl,
|
||||
'expires_at' => $loginSession->expires_at,
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 轮询扫码登录状态
|
||||
*/
|
||||
public function qrcodeLoginStatus(Request $request): Response
|
||||
{
|
||||
$sessionId = $request->get('session_id');
|
||||
|
||||
if (!$sessionId) {
|
||||
return $this->error('缺少会话ID');
|
||||
}
|
||||
|
||||
$session = \app\model\FeishuLoginSession::find($sessionId);
|
||||
|
||||
if (!$session) {
|
||||
return $this->error('登录会话不存在');
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if (strtotime($session->expires_at) < time()) {
|
||||
$session->status = 'expired';
|
||||
$session->save();
|
||||
return $this->error('二维码已过期,请刷新重试');
|
||||
}
|
||||
|
||||
// 返回当前状态
|
||||
if ($session->status === 'success') {
|
||||
// 生成 token
|
||||
$user = \app\model\User::find($session->user_id);
|
||||
if (!$user) {
|
||||
return $this->error('用户不存在');
|
||||
}
|
||||
|
||||
$token = \app\util\JwtUtil::encode([
|
||||
'user_id' => $user->id,
|
||||
'company_id' => $user->company_id,
|
||||
'feishu_user_id' => $user->feishu_user_id,
|
||||
'union_id' => $user->feishu_union_id,
|
||||
]);
|
||||
|
||||
// 清除会话
|
||||
$session->delete();
|
||||
|
||||
return $this->success([
|
||||
'status' => 'success',
|
||||
'token' => $token,
|
||||
'user' => $user->load('company'),
|
||||
]);
|
||||
} else if ($session->status === 'expired') {
|
||||
return $this->error('二维码已过期,请刷新重试');
|
||||
} else {
|
||||
// pending 或 scanning
|
||||
return $this->success([
|
||||
'status' => $session->status,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 飞书扫码登录回调(飞书授权后的回调)
|
||||
*/
|
||||
public function qrcodeLoginCallback(Request $request): Response
|
||||
{
|
||||
$sessionId = $this->getRouteParam($request, 'id');
|
||||
$authCode = $request->get('auth_code');
|
||||
|
||||
if (!$sessionId) {
|
||||
return $this->error('缺少会话ID');
|
||||
}
|
||||
|
||||
if (!$authCode) {
|
||||
return $this->error('缺少授权码');
|
||||
}
|
||||
|
||||
try {
|
||||
$session = \app\model\FeishuLoginSession::find($sessionId);
|
||||
|
||||
if (!$session) {
|
||||
return $this->error('登录会话不存在');
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
if (strtotime($session->expires_at) < time()) {
|
||||
$session->status = 'expired';
|
||||
$session->save();
|
||||
return $this->error('二维码已过期');
|
||||
}
|
||||
|
||||
// 使用 session 的公司信息
|
||||
$feishuService = new \app\service\FeishuService();
|
||||
$feishuService->setCompany($session->company_id);
|
||||
|
||||
// 获取用户信息
|
||||
$feishuData = $feishuService->getUserInfo($authCode);
|
||||
|
||||
// 创建或更新用户
|
||||
$user = $feishuService->createOrUpdateUser($feishuData, $session->company_id);
|
||||
|
||||
// 更新会话状态
|
||||
$session->status = 'success';
|
||||
$session->user_id = $user->id;
|
||||
$session->save();
|
||||
|
||||
// 重定向到前端页面
|
||||
return \Webman\Http\Response::redirect('https://xsm.dev.hnxinyouhe.com/login');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace app\model;
|
||||
|
||||
use support\Model;
|
||||
|
||||
class FeishuLoginSession extends Model
|
||||
{
|
||||
protected $table = 'feishu_login_session';
|
||||
|
||||
protected $fillable = [
|
||||
'company_id',
|
||||
'tenant_key',
|
||||
'status',
|
||||
'user_id',
|
||||
'expires_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'status' => 'string',
|
||||
'user_id' => 'integer',
|
||||
'company_id' => 'integer',
|
||||
'expires_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
const STATUS_PENDING = 'pending'; // 待扫码
|
||||
const STATUS_SCANNING = 'scanning'; // 已扫码,待授权
|
||||
const STATUS_SUCCESS = 'success'; // 登录成功
|
||||
const STATUS_EXPIRED = 'expired'; // 已过期
|
||||
|
||||
/**
|
||||
* 关联公司
|
||||
*/
|
||||
public function company()
|
||||
{
|
||||
return $this->belongsTo(Company::class, 'company_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 关联用户
|
||||
*/
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,9 @@ $authMiddleware = array_merge($apiMiddleware, [app\middleware\AuthMiddleware::cl
|
||||
Route::group('/api/v1', function () {
|
||||
Route::post('/auth/login', [app\controller\AuthController::class, 'login']);
|
||||
Route::post('/auth/feishu-login', [app\controller\AuthController::class, 'feishuLogin']);
|
||||
Route::post('/auth/qrcode-login', [app\controller\AuthController::class, 'qrcodeLogin']);
|
||||
Route::get('/auth/qrcode-login/status', [app\controller\AuthController::class, 'qrcodeLoginStatus']);
|
||||
Route::get('/login/qrcode/{id}', [app\controller\AuthController::class, 'qrcodeLoginCallback']);
|
||||
})->middleware($apiMiddleware);
|
||||
|
||||
// 用户路由(需要认证)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use support\Db;
|
||||
|
||||
return new class
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Db::statement('
|
||||
CREATE TABLE IF NOT EXISTS `feishu_login_session` (
|
||||
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
|
||||
`company_id` bigint unsigned NOT NULL COMMENT '公司ID',
|
||||
`tenant_key` varchar(64) NOT NULL COMMENT '租户密钥',
|
||||
`status` varchar(20) NOT NULL DEFAULT \'pending\' COMMENT \'pending: 待扫码, scanning: 已扫码待授权, success: 登录成功, expired: 已过期\'',
|
||||
`user_id` bigint unsigned DEFAULT NULL COMMENT \'用户ID(登录成功后填充)\'',
|
||||
`expires_at` datetime NOT NULL COMMENT \'过期时间\'',
|
||||
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_company_status` (`company_id`, `status`),
|
||||
KEY `idx_expires_at` (`expires_at`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=\'飞书扫码登录会话表\'
|
||||
');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Db::statement('DROP TABLE IF EXISTS `feishu_login_session`');
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { NavBar, Card, Tag, Button, Dialog, Toast, TextArea } from 'antd-mobile'
|
||||
import { Card, Tag, Button, Dialog, Toast, TextArea } from 'antd-mobile'
|
||||
import {
|
||||
LeftOutline,
|
||||
ClockCircleOutline,
|
||||
@@ -334,8 +334,6 @@ export default function ApprovalDetail() {
|
||||
|
||||
return (
|
||||
<div className={styles.detail}>
|
||||
<NavBar onBack={() => navigate(-1)}>审批详情</NavBar>
|
||||
|
||||
<div className={styles.content}>
|
||||
{/* 状态卡片 */}
|
||||
<Card className={styles.statusCard}>
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
.qrcodeContainer {
|
||||
padding: 30px 20px;
|
||||
text-align: center;
|
||||
min-width: 280px;
|
||||
}
|
||||
|
||||
.loading {
|
||||
color: #999;
|
||||
padding: 40px 0;
|
||||
}
|
||||
|
||||
.qrcode {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.qrcode svg {
|
||||
border: 8px solid #fff;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.status {
|
||||
font-size: 14px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.refreshBtn {
|
||||
padding: 8px 20px;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
background: #1677ff;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.refreshBtn:active {
|
||||
opacity: 0.8;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Dialog } from 'antd-mobile'
|
||||
import { QRCodeSVG } from 'qrcode.react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import Toast from 'antd-mobile'
|
||||
import styles from './QRCodeLogin.module.css'
|
||||
|
||||
interface QRCodeLoginProps {
|
||||
visible: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export default function QRCodeLogin({ visible, onClose }: QRCodeLoginProps) {
|
||||
const navigate = useNavigate()
|
||||
const [qrcodeUrl, setQrcodeUrl] = useState('')
|
||||
const [sessionId, setSessionId] = useState('')
|
||||
const [status, setStatus] = useState<'loading' | 'pending' | 'scanning' | 'success' | 'expired'>('loading')
|
||||
const pollTimerRef = useRef<NodeJS.Timeout | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
initQrcodeLogin()
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (pollTimerRef.current) {
|
||||
clearTimeout(pollTimerRef.current)
|
||||
}
|
||||
}
|
||||
}, [visible])
|
||||
|
||||
const initQrcodeLogin = async () => {
|
||||
setStatus('loading')
|
||||
try {
|
||||
// 生成登录二维码
|
||||
const response = await fetch('/api/v1/auth/qrcode-login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
tenant_key: '14e7bc0fe5985740',
|
||||
}),
|
||||
})
|
||||
|
||||
const result = await response.json()
|
||||
|
||||
if (result.code === 0) {
|
||||
setQrcodeUrl(result.data.auth_url)
|
||||
setSessionId(result.data.session_id)
|
||||
setStatus('pending')
|
||||
// 开始轮询登录状态
|
||||
startPolling(result.data.session_id)
|
||||
} else {
|
||||
Toast.show(result.message || '生成二维码失败')
|
||||
setStatus('expired')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('生成二维码失败:', error)
|
||||
Toast.show('生成二维码失败')
|
||||
setStatus('expired')
|
||||
}
|
||||
}
|
||||
|
||||
const startPolling = (id: string) => {
|
||||
const poll = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/v1/auth/qrcode-login/status?session_id=${id}`)
|
||||
const result = await response.json()
|
||||
|
||||
if (result.code === 0) {
|
||||
if (result.data.status === 'success') {
|
||||
setStatus('success')
|
||||
// 登录成功,保存 token
|
||||
const { token, user } = result.data
|
||||
localStorage.setItem('token', token)
|
||||
localStorage.setItem('i18nextLng', 'zh')
|
||||
// 触发登录成功事件,让 store 更新
|
||||
window.dispatchEvent(new CustomEvent('feishu-login-success', { detail: { user, token }))
|
||||
|
||||
Toast.show('登录成功')
|
||||
setTimeout(() => {
|
||||
onClose()
|
||||
navigate('/dashboard')
|
||||
}, 500)
|
||||
} else if (result.data.status === 'expired') {
|
||||
setStatus('expired')
|
||||
Toast.show('二维码已过期,请刷新重试')
|
||||
} else if (result.data.status === 'scanning') {
|
||||
setStatus('scanning')
|
||||
// 继续轮询
|
||||
pollTimerRef.current = setTimeout(poll, 2000)
|
||||
} else {
|
||||
// pending,继续轮询
|
||||
pollTimerRef.current = setTimeout(poll, 2000)
|
||||
}
|
||||
} else if (result.message?.includes('过期')) {
|
||||
setStatus('expired')
|
||||
} else {
|
||||
// 继续轮询
|
||||
pollTimerRef.current = setTimeout(poll, 2000)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('轮询登录状态失败:', error)
|
||||
// 继续轮询
|
||||
pollTimerRef.current = setTimeout(poll, 2000)
|
||||
}
|
||||
}
|
||||
|
||||
pollTimerRef.current = setTimeout(poll, 2000)
|
||||
}
|
||||
|
||||
const getStatusText = () => {
|
||||
switch (status) {
|
||||
case 'loading':
|
||||
return '正在生成二维码...'
|
||||
case 'pending':
|
||||
return '请使用飞书扫码登录'
|
||||
case 'scanning':
|
||||
return '已扫码,请在手机上确认'
|
||||
case 'success':
|
||||
return '登录成功!'
|
||||
case 'expired':
|
||||
return '二维码已过期'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
const getStatusColor = () => {
|
||||
switch (status) {
|
||||
case 'pending':
|
||||
return '#1677ff'
|
||||
case 'scanning':
|
||||
return '#faad14'
|
||||
case 'success':
|
||||
return '#52c41a'
|
||||
case 'expired':
|
||||
return '#ff4d4f'
|
||||
default:
|
||||
return '#999'
|
||||
}
|
||||
}
|
||||
|
||||
const handleRefresh = () => {
|
||||
if (pollTimerRef.current) {
|
||||
clearTimeout(pollTimerRef.current)
|
||||
}
|
||||
initQrcodeLogin()
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
visible={visible}
|
||||
content={
|
||||
<div className={styles.qrcodeContainer}>
|
||||
{status === 'loading' && <div className={styles.loading}>正在生成二维码...</div>}
|
||||
|
||||
{qrcodeUrl && status !== 'loading' && (
|
||||
<>
|
||||
<div className={styles.qrcode}>
|
||||
<QRCodeSVG
|
||||
value={qrcodeUrl}
|
||||
size={200}
|
||||
level="M"
|
||||
includeMargin={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.status} style={{ color: getStatusColor() }}>
|
||||
{getStatusText()}
|
||||
</div>
|
||||
|
||||
{(status === 'expired') && (
|
||||
<div className={styles.actions}>
|
||||
<button className={styles.refreshBtn} onClick={handleRefresh}>
|
||||
刷新二维码
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
onClose={onClose}
|
||||
closeOnMaskClick={status !== 'scanning' && status !== 'success'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,54 +1,137 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Toast } from 'antd-mobile'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import QRCodeLogin from './QRCodeLogin'
|
||||
import styles from './login.module.css'
|
||||
|
||||
// 声明 ttjsBridge 类型
|
||||
declare global {
|
||||
interface Window {
|
||||
ttjsBridge?: {
|
||||
getAuthCode: (params: any) => void
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default function Login() {
|
||||
const navigate = useNavigate()
|
||||
const { login } = useUserStore()
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [environment, setEnvironment] = useState<'feishu' | 'external' | null>(null)
|
||||
const [showQRCode, setShowQRCode] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
// 检查 URL 中是否有 auth_code 参数(飞书授权回调)
|
||||
const urlParams = new URLSearchParams(window.location.search)
|
||||
const authCode = urlParams.get('auth_code')
|
||||
// 监听飞书登录成功事件
|
||||
const handleFeishuLoginSuccess = ((e: any) => {
|
||||
console.log('🎉 收到飞书登录成功事件:', e.detail)
|
||||
const { user, token } = e.detail
|
||||
login(user, token)
|
||||
}) as EventListener
|
||||
|
||||
if (authCode) {
|
||||
// 有授权码,执行登录
|
||||
handleFeishuLogin(authCode)
|
||||
} else {
|
||||
// 没有授权码,跳转到飞书授权页面
|
||||
redirectToFeishu()
|
||||
window.addEventListener('feishu-login-success', handleFeishuLoginSuccess)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('feishu-login-success', handleFeishuLoginSuccess)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const redirectToFeishu = () => {
|
||||
// 飞书应用配置
|
||||
const appId = 'cli_a8033d607cba500d'
|
||||
// 重定向URI:前端登录页面(使用https)
|
||||
const redirectUri = encodeURIComponent('https://xsm.dev.hnxinyouhe.com/login')
|
||||
// 租户密钥(新友合公司)
|
||||
const tenantKey = '14e7bc0fe5985740'
|
||||
useEffect(() => {
|
||||
// 1. 检测是否在飞书客户端内
|
||||
const ua = navigator.userAgent.toLowerCase()
|
||||
const isInFeishu = ua.includes('feishu') || ua.includes('lark') || (window as any).ttjsBridge !== undefined
|
||||
|
||||
// 构建飞书授权 URL
|
||||
const authUrl = `https://open.feishu.cn/open-apis/authen/v1/oidc/authorize?app_id=${appId}&redirect_uri=${redirectUri}&state=${tenantKey}`
|
||||
console.log('🔍 Environment check:', { ua, isInFeishu, hasBridge: !!(window as any).ttjsBridge })
|
||||
|
||||
console.log('飞书授权 URL:', authUrl)
|
||||
if (isInFeishu) {
|
||||
// 飞书内:静默授权
|
||||
setEnvironment('feishu')
|
||||
handleFeishuAutoLogin()
|
||||
} else {
|
||||
// 飞书外:检查 URL 中是否有 auth_code 参数(飞书授权回调)
|
||||
const urlParams = new URLSearchParams(window.location.search)
|
||||
const authCode = urlParams.get('auth_code')
|
||||
const qrcodeId = urlParams.get('qrcode_id')
|
||||
|
||||
// 跳转到飞书授权页面
|
||||
window.location.href = authUrl
|
||||
if (qrcodeId) {
|
||||
// 扫码登录回调
|
||||
setEnvironment('external')
|
||||
handleQrcodeCallback(qrcodeId)
|
||||
} else if (authCode) {
|
||||
// 直接访问授权页面(不太可能)
|
||||
setEnvironment('external')
|
||||
handleFeishuCallback(authCode)
|
||||
} else {
|
||||
setEnvironment('external')
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
// 飞书内静默授权
|
||||
const handleFeishuAutoLogin = () => {
|
||||
console.log('🚀 Feishu auto login started')
|
||||
|
||||
if ((window as any).ttjsBridge) {
|
||||
(window as any).ttjsBridge.getAuthCode({
|
||||
success: (authCode: string) => {
|
||||
console.log('✅ Got auth code from ttjsBridge:', authCode)
|
||||
handleFeishuLogin(authCode)
|
||||
},
|
||||
fail: (error: any) => {
|
||||
console.error('❌ Get auth code failed:', error)
|
||||
setLoading(false)
|
||||
Toast.show('获取授权失败,请重试')
|
||||
},
|
||||
})
|
||||
} else {
|
||||
console.warn('⚠️ ttjsBridge not available')
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 跳转到飞书授权页面(飞书外扫码登录)
|
||||
const redirectToFeishu = () => {
|
||||
// 直接打开扫码登录弹窗
|
||||
setShowQRCode(true)
|
||||
}
|
||||
|
||||
// 处理飞书回调(飞书外扫码后回调)
|
||||
const handleFeishuCallback = async (authCode: string) => {
|
||||
try {
|
||||
await handleFeishuLogin(authCode)
|
||||
} catch (error) {
|
||||
console.error('登录失败:', error)
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理扫码登录回调
|
||||
const handleQrcodeCallback = async (qrcodeId: string) => {
|
||||
try {
|
||||
// 飞书扫码后会带着 qrcode_id 参数跳转回来
|
||||
// 这个时候前端需要显示 loading 状态
|
||||
// 后端会处理 qrcodeLoginCallback,更新 session 状态
|
||||
// 前端只需要轮询状态即可
|
||||
setShowQRCode(true)
|
||||
setLoading(false)
|
||||
|
||||
// 设置轮询 session_id
|
||||
// 实际上这个逻辑在 QRCodeLogin 组件中处理
|
||||
} catch (error) {
|
||||
console.error('处理扫码回调失败:', error)
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理飞书登录
|
||||
const handleFeishuLogin = async (authCode: string) => {
|
||||
try {
|
||||
const tenantKey = '14e7bc0fe5985740'
|
||||
|
||||
// 调用后端登录接口
|
||||
const response = await fetch('/api/v1/auth/feishu-login', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
auth_code: authCode,
|
||||
tenant_key: tenantKey,
|
||||
@@ -58,36 +141,70 @@ export default function Login() {
|
||||
const result = await response.json()
|
||||
|
||||
if (result.code === 0) {
|
||||
// 登录成功,保存到 store
|
||||
login(result.data.user, result.data.token)
|
||||
|
||||
Toast.show('登录成功')
|
||||
// 跳转到首页
|
||||
navigate('/dashboard')
|
||||
} else {
|
||||
Toast.show(result.message || '登录失败')
|
||||
// 登录失败,重新跳转到飞书授权
|
||||
setTimeout(() => {
|
||||
redirectToFeishu()
|
||||
}, 2000)
|
||||
setLoading(false)
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('登录失败:', error)
|
||||
Toast.show('登录失败,请重试')
|
||||
setTimeout(() => {
|
||||
redirectToFeishu()
|
||||
}, 2000)
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 邮箱密码登录
|
||||
const handlePasswordLogin = () => {
|
||||
navigate('/login-simple')
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className={styles.login}>
|
||||
<div className={styles.container}>
|
||||
<h1>企业工具台</h1>
|
||||
<p>正在登录...</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.login}>
|
||||
<div className={styles.container}>
|
||||
<h1>企业工具台</h1>
|
||||
<p>正在跳转到飞书授权...</p>
|
||||
<button className={styles.feishuBtn} onClick={redirectToFeishu}>
|
||||
重新跳转飞书登录
|
||||
</button>
|
||||
<p className={styles.subtitle}>请选择登录方式</p>
|
||||
|
||||
<div className={styles.loginMethods}>
|
||||
<button className={styles.methodBtn} onClick={handlePasswordLogin}>
|
||||
<div className={styles.methodIcon}>📧</div>
|
||||
<div className={styles.methodText}>
|
||||
<div className={styles.methodTitle}>邮箱密码登录</div>
|
||||
<div className={styles.methodDesc}>使用企业邮箱登录</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button className={styles.methodBtn} onClick={redirectToFeishu}>
|
||||
<div className={styles.methodIcon}>📱</div>
|
||||
<div className={styles.methodText}>
|
||||
<div className={styles.methodTitle}>飞书扫码登录</div>
|
||||
<div className={styles.methodDesc}>使用飞书 APP 扫码登录</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{environment === 'external' && (
|
||||
<p className={styles.tip}>
|
||||
💡 提示:在飞书客户端内打开可自动登录
|
||||
</p>
|
||||
)}
|
||||
|
||||
<QRCodeLogin
|
||||
visible={showQRCode}
|
||||
onClose={() => setShowQRCode(false)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -9,22 +9,80 @@
|
||||
.container {
|
||||
padding: 40px;
|
||||
text-align: center;
|
||||
max-width: 420px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.container h1 {
|
||||
margin: 0 0 40px 0;
|
||||
margin: 0 0 10px 0;
|
||||
color: #fff;
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.feishuBtn {
|
||||
width: 240px;
|
||||
padding: 14px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
.subtitle {
|
||||
margin: 0 0 40px 0;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.loginMethods {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.methodBtn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
padding: 16px 20px;
|
||||
background: #fff;
|
||||
color: #1677ff;
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
cursor: pointer;
|
||||
transition: transform 0.2s, box-shadow 0.2s;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.methodBtn:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
}
|
||||
|
||||
.methodBtn:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.methodIcon {
|
||||
font-size: 28px;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #f5f5f5;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.methodText {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.methodTitle {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
color: #333;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.methodDesc {
|
||||
font-size: 12px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.tip {
|
||||
margin-top: 30px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
Generated
+35
@@ -6,10 +6,12 @@
|
||||
"": {
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"@types/qrcode.react": "^1.0.5",
|
||||
"antd-mobile": "^5.42.3",
|
||||
"axios": "^1.13.5",
|
||||
"dayjs": "^1.11.19",
|
||||
"postcss-pxtorem": "^6.1.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react-router-dom": "^7.13.1",
|
||||
"vconsole": "^3.15.1",
|
||||
"zustand": "^5.0.11"
|
||||
@@ -166,6 +168,24 @@
|
||||
"integrity": "sha512-wkw9yd1kEXOPnvEeEV1Go1MmxtBJL0RR79aOTAApecWFVu7w0NNXNqhcWgvw2YgZDYadliXkl14pa3WXw5jlCQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/qrcode.react": {
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/qrcode.react/-/qrcode.react-1.0.5.tgz",
|
||||
"integrity": "sha512-BghPtnlwvrvq8QkGa1H25YnN+5OIgCKFuQruncGWLGJYOzeSKiix/4+B9BtfKF2wf5ja8yfyWYA3OXju995G8w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/react": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "19.2.14",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.14.tgz",
|
||||
"integrity": "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@use-gesture/core": {
|
||||
"version": "10.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@use-gesture/core/-/core-10.3.0.tgz",
|
||||
@@ -340,6 +360,12 @@
|
||||
"url": "https://opencollective.com/core-js"
|
||||
}
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dayjs": {
|
||||
"version": "1.11.19",
|
||||
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.19.tgz",
|
||||
@@ -709,6 +735,15 @@
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qrcode.react": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
|
||||
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/rc-field-form": {
|
||||
"version": "1.44.0",
|
||||
"resolved": "https://registry.npmjs.org/rc-field-form/-/rc-field-form-1.44.0.tgz",
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.90.21",
|
||||
"@types/qrcode.react": "^1.0.5",
|
||||
"antd-mobile": "^5.42.3",
|
||||
"axios": "^1.13.5",
|
||||
"dayjs": "^1.11.19",
|
||||
"postcss-pxtorem": "^6.1.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"react-router-dom": "^7.13.1",
|
||||
"vconsole": "^3.15.1",
|
||||
"zustand": "^5.0.11"
|
||||
|
||||
Reference in New Issue
Block a user