chore: initial commit of sso-mock SSO login service

Next.js + Mantine mock SSO service providing account/password, phone
verify-code, and Feishu QR login. Issues a one-time sso_code that the
external app exchanges for user info.

Includes:
- Feishu callback fix: guard against duplicate/concurrent /api/login
  submissions of the same single-use authorization code (feishuLogin
  once-guard + memoized onLoginSuccess to stop effect re-fire).
- ADAPTATION_GUIDE.md: how to switch from the in-memory code store to
  the real backend auth/index + inner_get_user_info endpoints.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
zhangheng
2026-07-06 18:09:30 +08:00
commit 37f10118d3
33 changed files with 3058 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
.list {
position: relative;
margin-bottom: var(--mantine-spacing-md);
}
.indicator {
border-bottom: 2px solid var(--mantine-color-blue-6);
top: 2px;
@mixin dark {
border-color: var(--mantine-color-blue-4);
}
}
.tab {
z-index: 1;
font-weight: 500;
transition: color 100ms ease;
color: var(--mantine-color-gray-7);
&[data-active] {
color: var(--mantine-color-black);
}
@mixin dark {
color: var(--mantine-color-dark-1);
&[data-active] {
color: var(--mantine-color-white);
}
}
}

View File

@@ -0,0 +1,36 @@
export const DigitalIcon = () => {
return (
<svg
width="32"
height="32"
viewBox="0 0 32 32"
fill="none"
xmlns="http://www.w3.org/2000/svg">
<rect width="32" height="32" rx="6.4" fill="#1F65FF" />
<path
d="M18.8274 10.2358C17.1727 9.51456 15.2092 9.56087 13.526 10.5327C11.533 11.6833 10.4672 13.8231 10.5906 15.9739C9.43935 15.5275 8.1034 15.5877 6.95081 16.2531C6.41165 16.5644 5.96713 16.9766 5.62734 17.4522C4.91523 13.1111 6.89492 8.58834 10.9301 6.25862C14.0914 4.43344 17.7876 4.37384 20.8768 5.77385C21.2809 5.98109 21.6159 6.32477 21.8599 6.74734C22.5348 7.91635 22.1343 9.41116 20.9653 10.0861C20.2877 10.4772 19.5008 10.5072 18.8275 10.2356L18.8274 10.2358Z"
fill="white"
/>
<path
d="M27.1744 17.0864C26.7514 20.333 24.8747 23.3531 21.8203 25.1165C17.7851 27.4463 12.8784 26.8994 9.47497 24.1121C10.0567 24.0556 10.636 23.8768 11.1751 23.5655C12.3277 22.9 13.0478 21.7732 13.2368 20.5529C15.0378 21.7352 17.4238 21.8821 19.4168 20.7314C21.0984 19.7605 22.12 18.0854 22.324 16.2936C22.4243 15.5728 22.8441 14.9041 23.5231 14.5121C24.6921 13.8372 26.1869 14.2377 26.8619 15.4067C27.1674 15.9358 27.2528 16.4847 27.1744 17.0864Z"
fill="white"
/>
<path
d="M7.71583 17.3525C8.60142 16.8412 9.64534 16.852 10.4907 17.2896C11.1047 17.6075 11.6765 17.627 12.181 17.5259C12.3868 17.4776 12.5799 17.4028 12.7535 17.3026C13.3325 16.9683 13.7899 16.4562 13.9352 15.5682C13.9365 15.5428 13.9373 15.5167 13.9394 15.4914C14.0025 14.7188 14.4317 13.9883 15.1537 13.5713C16.3227 12.8966 17.817 13.2976 18.4919 14.4665C19.1666 15.6354 18.7668 17.1301 17.5981 17.805C16.8759 18.2218 16.0287 18.2283 15.328 17.8966C15.3057 17.8861 15.2842 17.8738 15.2621 17.8625C14.4195 17.5433 13.7469 17.6831 13.1674 18.0176C12.9954 18.1169 12.8343 18.2445 12.6905 18.3967C12.4263 18.6954 12.2051 19.0654 12.1036 19.5384C12.0736 19.6801 12.0535 19.8289 12.0464 19.9841C12.0437 20.0434 12.0389 20.1025 12.0325 20.1613C11.9371 21.0467 11.4348 21.8764 10.6045 22.3558L10.6032 22.3555L10.6037 22.3563C9.22241 23.1534 7.45586 22.6807 6.65814 21.2998C6.5878 21.178 6.53153 21.0511 6.48071 20.9242C6.43658 20.8141 6.39903 20.7031 6.36924 20.5905C6.2986 20.323 6.26795 20.0511 6.27515 19.781C6.27878 19.6429 6.28994 19.5056 6.31305 19.3701C6.34384 19.19 6.39063 19.013 6.4546 18.8418C6.61633 18.4088 6.88218 18.0125 7.24107 17.6943C7.31295 17.6306 7.38849 17.5698 7.46774 17.5127C7.5468 17.4557 7.62961 17.4023 7.71583 17.3525Z"
fill="url(#paint0_linear_3567_2455)"
/>
<defs>
<linearGradient
id="paint0_linear_3567_2455"
x1="5.9905"
y1="21.684"
x2="19.3253"
y2="13.9852"
gradientUnits="userSpaceOnUse">
<stop stopColor="#FF6C6C" />
<stop offset="1" stopColor="#FFF1CE" />
</linearGradient>
</defs>
</svg>
)
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

View File

@@ -0,0 +1,131 @@
import { useCallback, useEffect, useRef } from 'react'
import { Flex } from '@mantine/core'
import { showErrorMsg } from '@/utils/message'
import { useLoginStore } from '../../store'
import {
getQueryVariable,
qr_load,
qr_login,
encrypt,
APP_ID,
TENANT,
} from '../../util'
/**
* 飞书二维码登录组件sso-mock 版本)
*
* 流程:
* 1. 加载飞书 SDK渲染真实二维码
* 2. 用户扫码后飞书 OAuth 回调到 /login?code=xxx&state=sso_app_id
* 3. 用 code 调用 /api/login?type=feishu 完成真实认证
* 4. 登录成功后跳转回外部应用(带 mock sso_code
*/
const QrLogin = ({
onLoginSuccess,
}: {
onLoginSuccess: (res: any) => void
}) => {
// 飞书 OAuth 回调地址:始终指向 sso-mock 自己的 /login
const redirect_url =
window.location.protocol +
'//' +
window.location.host +
`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/login`
// state 参数:传递 SSO 的 app_id回调后用它查找 app_url
// 飞书 OAuth 回调后 URL 里不再有 app_id从 localStorage 取
const ssoAppId =
(getQueryVariable('app_id') as string) ||
(typeof window !== 'undefined' ? localStorage.getItem('sso_app_id') || '' : '')
const fingerprint = useLoginStore((state) => state.fingerprint)
// 飞书 authorization code 只能用一次:守卫,防止重复渲染/StrictMode 重复提交
const feishuLoginTriggered = useRef(false)
// 渲染二维码
const renderCode = useCallback(async () => {
await qr_load()
// APP_ID: 飞书应用 ID
// redirect_url: 飞书 OAuth 回调地址sso-mock 自身)
// state: SSO 的 app_id传给飞书回调时原样返回
qr_login(APP_ID, redirect_url, ssoAppId)
}, [redirect_url, ssoAppId])
// 飞书扫码成功后,用返回的 code 调用真实后端登录
const feishuLogin = useCallback(async () => {
try {
const feishuCode = getQueryVariable('code')
if (!feishuCode) return
// 同一个 code 只提交一次避免并发请求撞上飞书“code 已使用”而报错
if (feishuLoginTriggered.current) return
feishuLoginTriggered.current = true
const res = await fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/api/login`,
{
method: 'POST',
body: JSON.stringify(
encrypt(
JSON.stringify({
code: feishuCode,
redirect_uri: redirect_url,
tenant: TENANT,
type: 'feishu',
fingerprint,
// SSO 参数:从 state即 app_id关联的 localStorage 取 app_url
...(ssoAppId
? {
client_id: ssoAppId,
client_redirect_uri: localStorage.getItem(ssoAppId) || '',
}
: {}),
})
)
),
}
)
.then((r) => r.text())
.then((t) => JSON.parse(t))
if (res?.error) {
showErrorMsg(res.error)
return
}
onLoginSuccess(res)
} catch (err: any) {
showErrorMsg(err?.message || '飞书登录失败')
}
}, [fingerprint, redirect_url, ssoAppId, onLoginSuccess])
// 初始化二维码
useEffect(() => {
void renderCode()
}, [renderCode])
// 如果 URL 带有 ?code=xxx飞书 OAuth 回调),自动执行登录
useEffect(() => {
if (getQueryVariable('code') && fingerprint) {
void feishuLogin()
}
}, [feishuLogin, fingerprint])
return (
<Flex align="center" justify="center" w={'100%'} h={'100%'}>
<div
id={'login_container'}
style={{
width: '200px',
height: '210px',
display: 'flex',
justifyContent: 'center',
scale: 0.7,
}}
/>
</Flex>
)
}
export default QrLogin

490
components/login/index.tsx Normal file
View File

@@ -0,0 +1,490 @@
'use client'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useForm } from '@mantine/form'
import {
Box,
TextInput,
PasswordInput,
Paper,
Text,
Button,
LoadingOverlay,
Stack,
Flex,
BackgroundImage,
Tabs,
FloatingIndicator,
Input,
useComputedColorScheme,
} from '@mantine/core'
import { showErrorMsg, showSuccessMsg } from '@/utils/message'
import { useLoginStore } from './store'
import DarkBgImage from './components/images/dark-login-bg.png'
import LightBgImage from './components/images/light-login-bg.png'
import loginBg2Dark from './components/images/login-bg2-dark.png'
import loginBg2Light from './components/images/login-bg2-light.png'
import LogoDigImage from './components/images/logo-dig.png'
import tabClasses from './Tab.module.css'
import { DigitalIcon } from './components/icons/digital'
import { encrypt, getQueryVariable, validatePhoneNumber } from './util'
import QrLogin from './components/login/qr-login'
const HeaderIcon = DigitalIcon
const headerTitle = '酷哇数字化平台'
const fixedTenant = 'coowa'
export default function LoginPage() {
const colorScheme = useComputedColorScheme()
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [addrMap, setAddrMap] = useState<Record<string, string>>({})
const [activeTab, setActiveTab] = useState<string | null>(() => {
// 飞书 OAuth 回调URL 带 ?code=xxx时自动切到飞书 tab
if (typeof window !== 'undefined' && getQueryVariable('code')) {
return 'feishu'
}
return 'account'
})
const [rootRef, setRootRef] = useState<HTMLDivElement | null>(null)
const controlsRefs = useRef<Record<string, HTMLButtonElement | null>>({})
const setControlRef = (val: string) => (node: HTMLButtonElement) => {
controlsRefs.current[val] = node
}
const { fingerprint, setFingerprint } = useLoginStore()
// SSO 跳转参数
const isClient = typeof window !== 'undefined'
const appId = isClient ? (getQueryVariable('app_id') as string) || '' : ''
const appUrl = isClient
? decodeURIComponent((getQueryVariable('app_url') as string) || '')
: ''
// 持久化 SSO 参数:飞书 OAuth 跳转后会丢失 URL 参数,存 localStorage
useEffect(() => {
if (appId && appUrl) {
localStorage.setItem(appId, appUrl) // app_id -> app_url
localStorage.setItem('sso_app_id', appId) // 记住当前 app_id
}
}, [appId, appUrl])
// 获取租户简称列表(与 uirefbase 一致)
useEffect(() => {
fetch(`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/api/front/getAbbrList`, {
method: 'GET',
headers: { 'Content-type': 'application/json' },
})
.then((response) => response.json())
.then((res) => {
setAddrMap(res?.data?.keys || {})
})
.catch(() => {})
}, [])
// 生成浏览器指纹
useEffect(() => {
const ua = navigator.userAgent
const screenInfo = `${screen.width}x${screen.height}`
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
const raw = `${ua}|${screenInfo}|${timezone}`
let hash = 0
for (let i = 0; i < raw.length; i++) {
hash = (hash << 5) - hash + raw.charCodeAt(i)
hash |= 0
}
setFingerprint(Math.abs(hash).toString(36))
}, [setFingerprint])
// ============ 登录成功后跳转回外部应用 ============
const handleLoginSuccess = useCallback((res: any) => {
if (res?.error) {
setError(res.error || '登录失败,请重试')
return
}
if (!res?.user_info?.account) {
setError('登录失败:后端未返回有效用户信息')
return
}
// 从 localStorage 获取外部应用地址
const storedAppId = appId || localStorage.getItem('sso_app_id') || ''
const targetUrl =
appUrl || (storedAppId ? localStorage.getItem(storedAppId) || '' : '')
if (res?.code && targetUrl) {
const separator = targetUrl.includes('?') ? '&' : '?'
window.location.href = `${targetUrl}${separator}sso_code=${res.code}`
return
}
// 无外部应用地址 — sso-mock 不提供本地登录
setError('缺少外部应用回调地址app_url无法完成 SSO 跳转')
}, [appId, appUrl])
// ============ 统一调用 /api/login ============
// SSO 参数优先取 URL其次取 localStorage飞书 OAuth 回调后 URL 参数丢失)
const postLogin = async (payload: object) => {
const effectiveAppId = appId || localStorage.getItem('sso_app_id') || ''
const effectiveAppUrl =
appUrl || (effectiveAppId ? localStorage.getItem(effectiveAppId) || '' : '')
const res = await fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/api/login`,
{
method: 'POST',
body: JSON.stringify(
encrypt(
JSON.stringify({
...payload,
fingerprint,
...(effectiveAppId ? { client_id: effectiveAppId } : {}),
...(effectiveAppUrl ? { client_redirect_uri: effectiveAppUrl } : {}),
})
)
),
}
)
.then((r) => r.text())
.then((t) => JSON.parse(t))
return res
}
// ============ Tab 1: 账户登录 ============
const accountForm = useForm({
initialValues: { username: '', password: '' },
validate: {
username: (v) => (!v ? '账户名不能为空' : null),
password: (v) => (!v ? '密码不能为空' : null),
},
validateInputOnChange: true,
validateInputOnBlur: true,
clearInputErrorOnChange: true,
})
const handleAccountSubmit = accountForm.onSubmit(async (values) => {
setLoading(true)
setError(null)
try {
const res = await postLogin({
account: values.username,
password: values.password,
abbr: fixedTenant,
type: 'account',
})
handleLoginSuccess(res)
} catch (err) {
setError(err instanceof Error ? err.message : '登录失败,请重试')
} finally {
setLoading(false)
}
})
// ============ Tab 2: 手机号登录 ============
const [codeTime, setCodeTime] = useState(0)
const handleCountDown = () => {
setCodeTime(60)
const timer = setInterval(() => {
setCodeTime((t) => {
if (t <= 1) {
clearInterval(timer)
return 0
}
return t - 1
})
}, 1000)
}
const handleGetCode = async () => {
if (!validatePhoneNumber(phoneForm.values.phone)) {
setError('请输入正确的手机号')
return
}
try {
const tntkey = addrMap?.[fixedTenant] || ''
if (!tntkey) {
showErrorMsg('请输入正确的租户')
return
}
const res: any = await fetch(
`${process.env.NEXT_PUBLIC_BASE_PATH || ''}/api/getVerifyCode`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
phone: phoneForm.values.phone.startsWith('+86')
? phoneForm.values.phone
: `+86${phoneForm.values.phone}`,
tntkey,
}),
}
).then((r) => r.json())
if (res?.code === 200) {
showSuccessMsg('验证码已发送, 请注意查收')
handleCountDown()
} else {
showErrorMsg(res?.message || '验证码发送失败')
}
} catch {
showSuccessMsg('验证码已发送')
handleCountDown()
}
}
const phoneForm = useForm({
initialValues: { phone: '', code: '' },
validate: {
phone: (v) => {
if (!v) return '手机号不能为空'
if (v.length !== 11) return '手机号必须为11位'
return null
},
code: (v) => {
if (!v) return '验证码不能为空'
if (v.length !== 6) return '验证码必须为6位'
return null
},
},
validateInputOnChange: true,
validateInputOnBlur: true,
clearInputErrorOnChange: true,
})
const handlePhoneSubmit = phoneForm.onSubmit(async (values) => {
setLoading(true)
setError(null)
try {
const tntkey = addrMap?.[fixedTenant] || ''
if (!tntkey) {
setError('请输入正确的租户')
setLoading(false)
return
}
const res = await postLogin({
phone: values.phone.startsWith('+86')
? values.phone
: `+86${values.phone}`,
verify_code: values.code,
tntkey,
type: 'phone',
})
handleLoginSuccess(res)
} catch (err) {
setError(err instanceof Error ? err.message : '登录失败,请重试')
} finally {
setLoading(false)
}
})
// ============ 错误提示 ============
useEffect(() => {
if (error) showErrorMsg(error)
}, [error])
const bgImage = useMemo(
() => (colorScheme === 'dark' ? DarkBgImage : LightBgImage),
[colorScheme]
)
const stackBg2Image = useMemo(
() => (colorScheme === 'dark' ? loginBg2Dark : loginBg2Light),
[colorScheme]
)
// 飞书 OAuth 回调中:显示 loading不渲染表单
const isFeishuCallback = isClient && !!getQueryVariable('code')
if (isFeishuCallback) {
return (
<Stack
align="center"
justify="center"
h={'100vh'}
w="100%"
bg={`url(${bgImage.src})`}
bgsz="cover"
bgp="center"
bgr="no-repeat">
<Paper withBorder shadow="md" radius="md" p="xl">
<Stack align="center" gap="md">
<LoadingOverlay visible />
<Text size="sm" c="dimmed">...</Text>
</Stack>
</Paper>
{/* QrLogin 仍在后台执行 feishuLogin */}
<Box style={{ position: 'absolute', opacity: 0, pointerEvents: 'none' }}>
<QrLogin onLoginSuccess={handleLoginSuccess} />
</Box>
</Stack>
)
}
return (
<Stack
align="center"
justify="center"
h={'100vh'}
w="100%"
bg={`url(${bgImage.src})`}
bgsz="cover"
bgp="center"
bgr="no-repeat">
<Paper
withBorder
shadow="md"
radius="md"
h={520}
maw={'100%'}
style={{ borderColor: 'rgba(255, 255, 255, 0.5)' }}>
<Flex w="100%" h={'100%'}>
{/* 左侧装饰区域 */}
<Stack
w={600}
p={32}
visibleFrom="md"
style={{ position: 'relative' }}>
<Box
w="100%"
h="100%"
style={{ position: 'absolute', top: 0, left: 0 }}>
<BackgroundImage src={stackBg2Image.src} w="100%" h="100%" />
</Box>
<Flex
justify="center"
align="center"
h="100%"
style={{ zIndex: 11 }}>
<BackgroundImage
src={LogoDigImage.src}
radius="xs"
w={432}
h={310}
visibleFrom="md"
/>
</Flex>
</Stack>
{/* 右侧登录表单 */}
<Stack h={'100%'} w={380} p={'54px 32px'} gap={0}>
<Flex mb={'2rem'} gap={8} justify="center" align={'center'}>
<HeaderIcon />
<Text size="xxl">{headerTitle}</Text>
</Flex>
{/* SSO 来源提示 */}
{appId && (
<Text size="xs" c="dimmed" ta="center" mb="sm">
{appId}
</Text>
)}
<Tabs variant="none" value={activeTab} onChange={setActiveTab}>
<Tabs.List ref={setRootRef} className={tabClasses.list}>
<Tabs.Tab
value="account"
ref={setControlRef('account')}
className={tabClasses.tab}>
</Tabs.Tab>
<Tabs.Tab
value="phone"
ref={setControlRef('phone')}
className={tabClasses.tab}>
</Tabs.Tab>
<Tabs.Tab
value="feishu"
ref={setControlRef('feishu')}
className={tabClasses.tab}>
</Tabs.Tab>
<FloatingIndicator
target={activeTab ? controlsRefs.current[activeTab] : null}
parent={rootRef}
className={tabClasses.indicator}
/>
</Tabs.List>
{/* 账户登录 */}
<Tabs.Panel value="account">
<form
onSubmit={handleAccountSubmit}
style={{ marginTop: '30px' }}>
<LoadingOverlay visible={loading} />
<TextInput
withAsterisk
label="账户名"
placeholder="请输入账户名"
mt="md"
{...accountForm.getInputProps('username')}
/>
<PasswordInput
withAsterisk
label="密码"
placeholder="请输入密码"
mt="md"
{...accountForm.getInputProps('password')}
/>
<Button type="submit" fullWidth mt="xl" disabled={loading}>
{loading ? '登录中...' : '登录'}
</Button>
</form>
</Tabs.Panel>
{/* 手机号登录 */}
<Tabs.Panel value="phone">
<form
onSubmit={handlePhoneSubmit}
style={{ marginTop: '30px' }}>
<LoadingOverlay visible={loading} />
<TextInput
withAsterisk
label="手机号"
placeholder="请输入手机号"
mt="md"
{...phoneForm.getInputProps('phone')}
/>
<Input.Wrapper
label="验证码"
withAsterisk
mt="md"
error={phoneForm.errors.code}>
<Flex align="center" gap={18}>
<Input
placeholder="请输入验证码"
style={{ flex: 1 }}
{...phoneForm.getInputProps('code')}
/>
<Button
style={{ flexShrink: 0 }}
type="button"
disabled={
!validatePhoneNumber(phoneForm.values.phone) ||
!!codeTime
}
onClick={handleGetCode}>
{codeTime !== 0 ? `${codeTime}秒后获取` : '获取验证码'}
</Button>
</Flex>
</Input.Wrapper>
<Button type="submit" fullWidth mt="xl" disabled={loading}>
{loading ? '登录中...' : '登录'}
</Button>
</form>
</Tabs.Panel>
{/* 飞书扫码(真实二维码) */}
<Tabs.Panel value="feishu">
{isClient && (
<QrLogin onLoginSuccess={handleLoginSuccess} />
)}
</Tabs.Panel>
</Tabs>
</Stack>
</Flex>
</Paper>
</Stack>
)
}

17
components/login/store.ts Normal file
View File

@@ -0,0 +1,17 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface LoginState {
fingerprint: string
setFingerprint: (fingerprint: string) => void
}
export const useLoginStore = create(
persist<LoginState>(
(set) => ({
fingerprint: '',
setFingerprint: (fingerprint) => set({ fingerprint }),
}),
{ name: 'login-store' }
)
)

100
components/login/util.ts Normal file
View File

@@ -0,0 +1,100 @@
import CryptoJS from 'crypto-js'
const CODE_CRYPTO_KEY = 'k#8Mp$2Qr&9Tz@4W'
export const APP_ID = 'cli_a56577acb2f3d00c' // 飞书应用 ID与 uirefbase 相同)
export const TENANT = 'coowa'
export const validatePhoneNumber = (str: string) => {
const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
return reg.test(str)
}
/** 获取 url 中的某个参数值 */
export const getQueryVariable = (variable: string) => {
if (typeof window === 'undefined') return false
const query = window.location.search.substring(1)
const vars = query.split('&')
for (let i = 0; i < vars.length; i++) {
const pair = vars[i].split('=')
if (pair[0] === variable) {
return pair[1]
}
}
return false
}
/** 加载飞书二维码 SDK */
export function qr_load() {
return new Promise<void>((resolve, reject) => {
// 如果已加载则跳过
if ((window as any).QRLogin) {
resolve()
return
}
const script = document.createElement('script')
script.type = 'text/javascript'
script.src =
'https://sf3-cn.feishucdn.com/obj/feishu-static/lark/passport/qrcode/LarkSSOSDKWebQRCode-1.0.2.js'
script.onerror = reject
script.onload = () => resolve()
document.head.appendChild(script)
})
}
/** 初始化飞书二维码 */
export async function qr_login(
appId: string,
redirect_url: string,
state: string
) {
const gotoUrl = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${appId}&redirect_uri=${encodeURIComponent(
redirect_url
)}&response_type=code&state=${encodeURIComponent(state)}`
const QRLogin = (window as any).QRLogin
const QRLoginObj = QRLogin({
id: 'login_container',
goto: gotoUrl,
style: `width: 270px;height: 270px;border: 0;border-radius:12px;
background-image:
radial-gradient(at 47% 33%, hsl(212.37, 72%, 59%) 0, transparent 59%),
radial-gradient(at 82% 65%, hsl(198.00, 100%, 50%) 0, transparent 55%);`,
})
const handleMessage = function (event: any) {
const origin = event.origin
if (
QRLoginObj.matchOrigin(origin) &&
window.location.href.indexOf('login') > -1
) {
const loginTmpCode = event.data
window.location.href = `${gotoUrl}&tmp_code=${loginTmpCode}`
}
}
if (typeof window.addEventListener !== 'undefined') {
window.addEventListener('message', handleMessage, false)
} else if (typeof (window as any).attachEvent !== 'undefined') {
;(window as any).attachEvent('onmessage', handleMessage)
}
}
/** 加密 — 与 uirefbase 客户端保持一致 */
export const encrypt = (data: string) => {
try {
return CryptoJS.AES.encrypt(data, CODE_CRYPTO_KEY).toString()
} catch (error) {
return data
}
}
/** 解密 */
export const decrypt = (data: string) => {
try {
const bytes = CryptoJS.AES.decrypt(data, CODE_CRYPTO_KEY)
return bytes.toString(CryptoJS.enc.Utf8)
} catch (error) {
return data
}
}