f9e5ce61e3
- 站内改昵称/邮箱/头像后,用自己的 access_token 写回 Casimir(update-user,字段每批≤2,401 自动 refresh_token 续期) - 头像不再本地存储:上传直调 Casimir upload-resource (tag=avatar),成功后自动写回 user.Avatar,仅落库返回 URL - me.patch 头像仅存档本地,避免 update-user 重复同步 - 头像上传仅走 Casimir,未配置 Storage provider 时报错提示 - exchangeCodeForIdentity 补 owner/displayName/token,昵称优先 displayName - 新增类型检查依赖 typescript/vue-tsc 与 typecheck 脚本
144 lines
5.2 KiB
TypeScript
144 lines
5.2 KiB
TypeScript
import { SDK } from 'casdoor-nodejs-sdk'
|
||
import { getCasdoorConfig } from './casdoorConfig'
|
||
import { getConfig } from './config'
|
||
|
||
/**
|
||
* Casdoor 统一认证封装(服务端)。
|
||
*
|
||
* - 登录 URL、code->token 交换、JWT 验签全部走官方 casdoor-nodejs-sdk
|
||
* - 配置(serverUrl/clientId/clientSecret/证书)由后台写入 settings 表,不依赖环境变量
|
||
* - 登录成功后再通过 get-account 补齐邮箱/头像等字段(拿不到也不阻塞登录)
|
||
* - 前台用户一律视为普通用户;后台权限由独立 admin_users 表管理
|
||
*/
|
||
let _sdk: SDK | null = null
|
||
let _sdkKey = ''
|
||
|
||
function getSDK(): SDK {
|
||
const cfg = getCasdoorConfig()
|
||
const key = [cfg.serverUrl, cfg.clientId, cfg.clientSecret, cfg.orgName, cfg.appName, cfg.certificate].join('|')
|
||
if (!_sdk || _sdkKey !== key) {
|
||
_sdk = new SDK({
|
||
endpoint: cfg.serverUrl,
|
||
clientId: cfg.clientId,
|
||
clientSecret: cfg.clientSecret,
|
||
certificate: cfg.certificate,
|
||
orgName: cfg.orgName,
|
||
appName: cfg.appName || undefined,
|
||
})
|
||
_sdkKey = key
|
||
}
|
||
return _sdk
|
||
}
|
||
|
||
/** 用 refresh_token 换取新的 access_token/refresh_token(写回资料过期时自动续期) */
|
||
export async function refreshCasdoorToken(refreshToken: string): Promise<{ access_token: string; refresh_token: string } | null> {
|
||
if (!refreshToken) return null
|
||
try {
|
||
const res = await getSDK().refreshToken(refreshToken)
|
||
if (res?.access_token) {
|
||
return { access_token: res.access_token, refresh_token: res.refresh_token || '' }
|
||
}
|
||
return null
|
||
} catch {
|
||
return null
|
||
}
|
||
}
|
||
|
||
/** 构造 Casdoor 登录授权地址(redirect_uri = 本站回调) */
|
||
export function getCasdoorSignInUrl(): string {
|
||
const cfg = getCasdoorConfig()
|
||
const redirectUri = getConfig().siteUrl + cfg.callbackPath
|
||
return getSDK().getSignInUrl(redirectUri)
|
||
}
|
||
|
||
/** 构造 Casdoor 注册页地址(在 Casdoor 侧完成注册) */
|
||
export function getCasdoorSignUpUrl(): string {
|
||
const cfg = getCasdoorConfig()
|
||
return `${cfg.serverUrl}/signup/${cfg.appName}`
|
||
}
|
||
|
||
/** 单点登出地址(访问后跳回 redirectUri;未配置则返回空串) */
|
||
export function getCasdoorLogoutUrl(): string {
|
||
const cfg = getCasdoorConfig()
|
||
if (!cfg.serverUrl || !cfg.clientId) return ''
|
||
const redirectUri = getConfig().siteUrl + cfg.callbackPath
|
||
return `${cfg.serverUrl}/logout?client_id=${cfg.clientId}&redirect_uri=${encodeURIComponent(redirectUri)}`
|
||
}
|
||
|
||
/** 登录回调校验的期望 state(casdoor SDK 以 appName 作为 state 返回) */
|
||
export function getCasdoorState(): string {
|
||
return getCasdoorConfig().appName
|
||
}
|
||
|
||
export interface CasdoorIdentity {
|
||
/** 唯一用户标识(Casdoor 用户 UUID,即 JWT 的 sub) */
|
||
providerId: string
|
||
provider: string
|
||
username: string
|
||
email: string
|
||
avatar: string
|
||
/** Casdoor 组织名(owner) */
|
||
casdoorOwner: string
|
||
/** Casdoor 登录账号名(name,不可改,用于 update-user 的 id=owner/name) */
|
||
casdoorName: string
|
||
/** Casdoor 昵称(displayName) */
|
||
casdoorNickname: string
|
||
/** 用户自己的 access_token(写回资料用) */
|
||
accessToken: string
|
||
/** 用户自己的 refresh_token(自动续期用) */
|
||
refreshToken: string
|
||
}
|
||
|
||
/**
|
||
* 交换授权码并验签,返回可落库的身份信息。
|
||
* @throws 交换失败 / 验签失败 / 缺少 sub
|
||
*/
|
||
export async function exchangeCodeForIdentity(code: string): Promise<CasdoorIdentity> {
|
||
if (!code) {
|
||
throw new Error('缺少授权码')
|
||
}
|
||
const { access_token, refresh_token } = await getSDK().getAuthToken(code)
|
||
if (!access_token) {
|
||
throw new Error('Casdoor 未返回 access_token')
|
||
}
|
||
|
||
const claims = getSDK().parseJwtToken(access_token)
|
||
const account = await getAccountProfile(access_token).catch(() => null)
|
||
|
||
const providerId = String(account?.sub || (claims as any).sub || (claims as any).id || '')
|
||
if (!providerId) {
|
||
throw new Error('Casdoor token 缺少用户标识(sub)')
|
||
}
|
||
|
||
const casdoorOwner = String(account?.owner || (claims as any).owner || '').trim()
|
||
const casdoorName = String(account?.name || (claims as any).name || (claims as any).preferred_username || '').trim()
|
||
const casdoorNickname = String(account?.displayName || (claims as any).displayName || '').trim()
|
||
|
||
const username = casdoorNickname || casdoorName || 'user'
|
||
const email = String(account?.email || (claims as any).email || '').trim().toLowerCase()
|
||
const avatar = String(account?.avatar || (claims as any).avatar || (claims as any).picture || '').trim()
|
||
|
||
return {
|
||
providerId,
|
||
provider: 'casdoor',
|
||
username,
|
||
email,
|
||
avatar,
|
||
casdoorOwner,
|
||
casdoorName,
|
||
casdoorNickname,
|
||
accessToken: access_token,
|
||
refreshToken: refresh_token || '',
|
||
}
|
||
}
|
||
|
||
/** 通过 get-account 接口补齐完整账号信息(含邮箱/头像);失败不阻塞登录 */
|
||
async function getAccountProfile(accessToken: string): Promise<Record<string, unknown> | null> {
|
||
const cfg = getCasdoorConfig()
|
||
const url = `${cfg.serverUrl}/api/get-account?access_token=${encodeURIComponent(accessToken)}`
|
||
const res = await fetch(url)
|
||
if (!res.ok) return null
|
||
const body = (await res.json()) as { status?: string; data?: Record<string, unknown> }
|
||
if (body?.status !== 'ok') return null
|
||
return body.data ?? null
|
||
} |