541e24c6f4
- 新增 admin_users/admin_sessions 表与 adminAuth 工具(scrypt 密码 + 独立会话 Cookie) - /admin/init 初始化首个管理员,未初始化时服务端/客户端双守卫引导 - 后台鉴权改为管理员会话,前台 Casdoor 用户一律普通用户、与后台解耦 - Casdoor 配置改存 settings 表并由「统一认证」页管理,移除全部 CASDOOR 环境变量 - 侧边栏增加统一认证/管理员入口与登出;LoginModal 感知 SSO 启用状态 - 补充 adminAuth 测试,重写 casdoor 测试,全部 23 项通过
36 lines
1.5 KiB
TypeScript
36 lines
1.5 KiB
TypeScript
import { getQuery, getCookie, deleteCookie, createError, sendRedirect } from 'h3'
|
|
import { exchangeCodeForIdentity, getCasdoorState } from '../../utils/casdoor'
|
|
import { upsertCasdoorUser, createSession, setSessionCookie } from '../../utils/auth'
|
|
import { isCasdoorEnabled } from '../../utils/casdoorConfig'
|
|
|
|
/**
|
|
* Casdoor OAuth 回调:
|
|
* code -> 交换 access_token -> JWT 验签 -> upsert 本地用户 -> 建立会话 -> 回跳。
|
|
*/
|
|
export default defineEventHandler(async (event) => {
|
|
if (!isCasdoorEnabled()) {
|
|
throw createError({ statusCode: 503, message: '未配置 Casdoor 统一认证', data: { code: 'CASDOOR_NOT_CONFIGURED' } })
|
|
}
|
|
|
|
const query = getQuery(event)
|
|
const code = String(query?.code ?? '')
|
|
const state = String(query?.state ?? '')
|
|
|
|
// state 校验(SDK 以 appName 为 state;登录端点已写入同值 Cookie)
|
|
const expectedState = getCasdoorState()
|
|
if (expectedState && state && state !== expectedState) {
|
|
throw createError({ statusCode: 400, message: 'state 校验失败', data: { code: 'OAUTH_STATE_MISMATCH' } })
|
|
}
|
|
|
|
const identity = await exchangeCodeForIdentity(code)
|
|
const user = upsertCasdoorUser(identity)
|
|
const token = createSession(user.id)
|
|
setSessionCookie(event, token)
|
|
|
|
const cookieNext = getCookie(event, 'an_oauth_next') || '/'
|
|
const safeNext = cookieNext.startsWith('/') && !cookieNext.startsWith('//') ? cookieNext : '/'
|
|
deleteCookie(event, 'an_oauth_state', { path: '/' })
|
|
deleteCookie(event, 'an_oauth_next', { path: '/' })
|
|
|
|
return sendRedirect(event, safeNext)
|
|
}) |