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:
root
2026-02-26 09:58:19 +08:00
parent 8110b1e5e6
commit df07b16c7a
12 changed files with 892 additions and 51 deletions
+1 -3
View File
@@ -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;
}
+187
View File
@@ -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'}
/>
)
}
+157 -40
View File
@@ -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>
)
+66 -8
View File
@@ -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;
}