feat: 登录改为 Casdoor 统一身份认证(SSO),重建用户体系
- 移除内置密码注册/登录/改密/删号/头像,统一走 Casdoor OIDC 授权码 - 服务端 casdoor-nodejs-sdk:code 换 token + 证书公钥验签 + get-account 补齐资料 - 用户表重建为 provider+provider_id(Casdoor sub 为准),邮箱不再唯一 - 管理员由 Casdoor token 的 isAdmin/IsAdmin 字段或 admin 角色判定,删除角色切换接口 - 前端登录弹窗改为申统认证跳转,注册去 Casdoor;后台用户列表只读角色 - 会话沿用 an_session httpOnly Cookie,requireUser/requireAdmin 守卫保留 - 配置注入 deploy.sh/.env.example;新增 casdoor 单测,删除 password 单测
This commit is contained in:
@@ -7,7 +7,7 @@ import { getDb } from '../../utils/db'
|
||||
export default defineEventHandler((event) => {
|
||||
requireAdmin(event)
|
||||
const users = getDb()
|
||||
.prepare('SELECT id, username, email, phone, role, created_at AS createdAt FROM users ORDER BY id DESC')
|
||||
.prepare('SELECT id, provider, provider_id, username, email, role, created_at AS createdAt FROM users ORDER BY id DESC')
|
||||
.all()
|
||||
return { users }
|
||||
})
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { readBody, createError, getRouterParam } from 'h3'
|
||||
import { requireAdmin } from '../../../utils/auth'
|
||||
import { getDb } from '../../../utils/db'
|
||||
import { writeAudit } from '../../../utils/audit'
|
||||
|
||||
/**
|
||||
* 后台更新用户(角色切换)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const me = requireAdmin(event)
|
||||
const id = Number(getRouterParam(event, 'id'))
|
||||
const body = await readBody(event)
|
||||
const db = getDb()
|
||||
|
||||
if (me.id === id) {
|
||||
throw createError({ statusCode: 400, message: '不能修改自己的角色', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const target = db.prepare('SELECT id FROM users WHERE id = ?').get(id)
|
||||
if (!target) {
|
||||
throw createError({ statusCode: 404, message: '用户不存在', data: { code: 'NOT_FOUND' } })
|
||||
}
|
||||
if (body?.role !== undefined) {
|
||||
if (!['user', 'admin'].includes(body.role)) {
|
||||
throw createError({ statusCode: 400, message: '角色不合法', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
db.prepare('UPDATE users SET role = ? WHERE id = ?').run(body.role, id)
|
||||
}
|
||||
writeAudit(event, 'update', `user:${id}`)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -1,55 +0,0 @@
|
||||
import { readMultipartFormData, readBody, createError } from 'h3'
|
||||
import { requireUser, toPublicUser, type UserRow } from '../../utils/auth'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { saveImage, IMAGE_EXT_BY_TYPE, UploadError } from '../../utils/upload'
|
||||
|
||||
/**
|
||||
* 修改头像:
|
||||
* - multipart/form-data(字段 file)-> 上传图片到 OSS/本地,保存 URL
|
||||
* - JSON { clear: true } -> 清除头像(回退默认生成头像)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
const db = getDb()
|
||||
const contentType = event.headers.get('content-type') || ''
|
||||
|
||||
if (contentType.includes('multipart/form-data')) {
|
||||
const parts = await readMultipartFormData(event)
|
||||
const file = parts?.find((p) => p.name === 'file' && p.data?.length)
|
||||
if (!file?.data) {
|
||||
throw createError({ statusCode: 400, message: '缺少文件', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const type = file.type || ''
|
||||
if (!IMAGE_EXT_BY_TYPE[type]) {
|
||||
throw createError({ statusCode: 400, message: '仅支持图片(png/jpg/gif/webp/svg/avif)', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
let url: string
|
||||
try {
|
||||
url = await saveImage(Buffer.from(file.data), type, 'avatars')
|
||||
} catch (err) {
|
||||
if (err instanceof UploadError) {
|
||||
throw createError({ statusCode: 400, message: err.message, data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
db.prepare('UPDATE users SET avatar = ? WHERE id = ?').run(url, user.id)
|
||||
const updated = db
|
||||
.prepare('SELECT id, username, email, phone, avatar, role, created_at FROM users WHERE id = ?')
|
||||
.get(user.id) as UserRow
|
||||
return { ok: true, user: toPublicUser(updated) }
|
||||
}
|
||||
|
||||
// JSON:清除头像
|
||||
const body = await readBody(event).catch(() => ({}))
|
||||
if (body?.clear) {
|
||||
db.prepare('UPDATE users SET avatar = NULL WHERE id = ?').run(user.id)
|
||||
} else {
|
||||
throw createError({ statusCode: 400, message: '请上传图片或传入 clear', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
const updated = db
|
||||
.prepare('SELECT id, username, email, phone, avatar, role, created_at FROM users WHERE id = ?')
|
||||
.get(user.id) as UserRow
|
||||
return { ok: true, user: toPublicUser(updated) }
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
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/config'
|
||||
|
||||
/**
|
||||
* 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)
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { getQuery, setCookie, sendRedirect, createError } from 'h3'
|
||||
import { getCasdoorSignInUrl, getCasdoorState } from '../../utils/casdoor'
|
||||
import { isCasdoorEnabled } from '../../utils/config'
|
||||
|
||||
/**
|
||||
* 统一认证入口:跳转到 Casdoor 登录页。
|
||||
* - 记录期望 state 和回跳路径(短时效 Cookie,callback 消费)
|
||||
* - next 仅允许站内相对路径,防开放重定向
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
if (!isCasdoorEnabled()) {
|
||||
throw createError({ statusCode: 503, message: '未配置 Casdoor 统一认证', data: { code: 'CASDOOR_NOT_CONFIGURED' } })
|
||||
}
|
||||
|
||||
const query = getQuery(event)
|
||||
const next = String(query?.next ?? '/')
|
||||
const safeNext = next.startsWith('/') && !next.startsWith('//') ? next : '/'
|
||||
|
||||
setCookie(event, 'an_oauth_state', getCasdoorState(), {
|
||||
path: '/', httpOnly: true, sameSite: 'lax', maxAge: 600,
|
||||
})
|
||||
setCookie(event, 'an_oauth_next', safeNext, {
|
||||
path: '/', httpOnly: true, sameSite: 'lax', maxAge: 600,
|
||||
})
|
||||
return sendRedirect(event, getCasdoorSignInUrl())
|
||||
})
|
||||
@@ -1,30 +0,0 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { verifyPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth'
|
||||
|
||||
/**
|
||||
* 登录:账号(用户名或邮箱)+ 密码 -> 校验 -> 建立会话
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const account = String(body?.account ?? '').trim()
|
||||
const password = String(body?.password ?? '')
|
||||
|
||||
if (!account || !password) {
|
||||
throw createError({ statusCode: 400, message: '请输入账号与密码', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const db = getDb()
|
||||
const user = db
|
||||
.prepare('SELECT * FROM users WHERE username = ? OR email = ?')
|
||||
.get(account, account.toLowerCase()) as (UserRow & { password_hash: string }) | undefined
|
||||
|
||||
if (!user || !(await verifyPassword(password, user.password_hash))) {
|
||||
throw createError({ statusCode: 401, message: '账号或密码错误', data: { code: 'INVALID_CREDENTIALS' } })
|
||||
}
|
||||
|
||||
const token = createSession(user.id)
|
||||
setSessionCookie(event, token)
|
||||
|
||||
return { user: toPublicUser(user) }
|
||||
})
|
||||
@@ -1,23 +0,0 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { requireUser, verifyPassword, clearSessionCookie } from '../../utils/auth'
|
||||
|
||||
/**
|
||||
* 自助删除账号(需验证当前密码;删除后登出,级联清理会话/评论/收藏)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
const body = await readBody(event)
|
||||
const password = String(body?.password ?? '')
|
||||
|
||||
const row = getDb().prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as
|
||||
| { password_hash: string }
|
||||
| undefined
|
||||
if (!row || !(await verifyPassword(password, row.password_hash))) {
|
||||
throw createError({ statusCode: 400, message: '密码不正确', data: { code: 'WRONG_PASSWORD' } })
|
||||
}
|
||||
|
||||
getDb().prepare('DELETE FROM users WHERE id = ?').run(user.id) // 外键级联:sessions/comments/favorites
|
||||
clearSessionCookie(event)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -1,10 +1,10 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { requireUser, toPublicUser, type UserRow } from '../../utils/auth'
|
||||
import { isValidUsername, isValidPhone } from '../../utils/validation'
|
||||
import { isValidUsername } from '../../utils/validation'
|
||||
|
||||
/**
|
||||
* 更新当前用户资料(用户名/手机号)
|
||||
* 更新当前用户资料(仅用户名;邮箱/头像/角色均由 Casdoor 管理)
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
@@ -25,17 +25,9 @@ export default defineEventHandler(async (event) => {
|
||||
db.prepare('UPDATE users SET username = ? WHERE id = ?').run(username, user.id)
|
||||
}
|
||||
|
||||
if (body?.phone !== undefined) {
|
||||
const phone = String(body.phone).trim()
|
||||
if (!isValidPhone(phone)) {
|
||||
throw createError({ statusCode: 400, message: '手机号格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
db.prepare('UPDATE users SET phone = ? WHERE id = ?').run(phone || null, user.id)
|
||||
}
|
||||
|
||||
const updated = db
|
||||
.prepare('SELECT id, username, email, phone, role, created_at FROM users WHERE id = ?')
|
||||
.prepare('SELECT id, provider, provider_id, username, email, avatar, role, created_at FROM users WHERE id = ?')
|
||||
.get(user.id) as UserRow
|
||||
|
||||
return { user: toPublicUser(updated) }
|
||||
})
|
||||
})
|
||||
@@ -1,28 +0,0 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { requireUser, verifyPassword, hashPassword } from '../../utils/auth'
|
||||
import { isValidPassword } from '../../utils/validation'
|
||||
|
||||
/**
|
||||
* 修改密码:校验当前密码 -> 新密码强度 -> 更新
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = requireUser(event)
|
||||
const body = await readBody(event)
|
||||
const currentPassword = String(body?.currentPassword ?? '')
|
||||
const newPassword = String(body?.newPassword ?? '')
|
||||
|
||||
const row = getDb().prepare('SELECT password_hash FROM users WHERE id = ?').get(user.id) as
|
||||
| { password_hash: string }
|
||||
| undefined
|
||||
if (!row || !(await verifyPassword(currentPassword, row.password_hash))) {
|
||||
throw createError({ statusCode: 400, message: '当前密码不正确', data: { code: 'WRONG_PASSWORD' } })
|
||||
}
|
||||
if (!isValidPassword(newPassword)) {
|
||||
throw createError({ statusCode: 400, message: '新密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(newPassword)
|
||||
getDb().prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(passwordHash, user.id)
|
||||
return { ok: true }
|
||||
})
|
||||
@@ -1,57 +0,0 @@
|
||||
import { readBody, createError } from 'h3'
|
||||
import { getDb } from '../../utils/db'
|
||||
import { hashPassword, createSession, setSessionCookie, toPublicUser, type UserRow } from '../../utils/auth'
|
||||
import { isAdminEmail } from '../../utils/config'
|
||||
import { isValidUsername, isValidEmail, isValidPassword, isValidPhone } from '../../utils/validation'
|
||||
|
||||
/**
|
||||
* 注册:校验 -> scrypt 哈希 -> 落库 -> 建立会话
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const username = String(body?.username ?? '').trim()
|
||||
const email = String(body?.email ?? '').trim().toLowerCase()
|
||||
const phone = String(body?.phone ?? '').trim()
|
||||
const password = String(body?.password ?? '')
|
||||
|
||||
if (!isValidUsername(username)) {
|
||||
throw createError({ statusCode: 400, message: '用户名需为 2-20 位字符', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (!isValidEmail(email)) {
|
||||
throw createError({ statusCode: 400, message: '邮箱格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (!isValidPassword(password)) {
|
||||
throw createError({ statusCode: 400, message: '密码至少需要 8 位', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
if (phone && !isValidPhone(phone)) {
|
||||
throw createError({ statusCode: 400, message: '手机号格式不正确', data: { code: 'VALIDATION_ERROR' } })
|
||||
}
|
||||
|
||||
const db = getDb()
|
||||
const existing = db
|
||||
.prepare('SELECT username, email FROM users WHERE username = ? OR email = ?')
|
||||
.get(username, email) as { username: string; email: string } | undefined
|
||||
|
||||
if (existing) {
|
||||
if (existing.username === username) {
|
||||
throw createError({ statusCode: 400, message: '用户名已被使用', data: { code: 'USERNAME_TAKEN' } })
|
||||
}
|
||||
throw createError({ statusCode: 400, message: '该邮箱已被注册', data: { code: 'EMAIL_TAKEN' } })
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password)
|
||||
// 管理员邮箱白名单命中者自动授予 admin 角色(后续可后台切换)
|
||||
const role = isAdminEmail(email) ? 'admin' : 'user'
|
||||
const info = db
|
||||
.prepare('INSERT INTO users (username, email, phone, password_hash, role) VALUES (?, ?, ?, ?, ?)')
|
||||
.run(username, email, phone || null, passwordHash, role)
|
||||
|
||||
const user = db
|
||||
.prepare('SELECT id, username, email, phone, role, created_at FROM users WHERE id = ?')
|
||||
.get(info.lastInsertRowid) as UserRow
|
||||
|
||||
const token = createSession(user.id)
|
||||
setSessionCookie(event, token)
|
||||
|
||||
return { user: toPublicUser(user) }
|
||||
})
|
||||
Reference in New Issue
Block a user