feat: 后台管理员独立账号体系,Casdoor 配置改为后台管理

- 新增 admin_users/admin_sessions 表与 adminAuth 工具(scrypt 密码 + 独立会话 Cookie)
- /admin/init 初始化首个管理员,未初始化时服务端/客户端双守卫引导
- 后台鉴权改为管理员会话,前台 Casdoor 用户一律普通用户、与后台解耦
- Casdoor 配置改存 settings 表并由「统一认证」页管理,移除全部 CASDOOR 环境变量
- 侧边栏增加统一认证/管理员入口与登出;LoginModal 感知 SSO 启用状态
- 补充 adminAuth 测试,重写 casdoor 测试,全部 23 项通过
This commit is contained in:
2026-08-09 02:01:14 +08:00
parent 337eb4f05a
commit 541e24c6f4
42 changed files with 1505 additions and 307 deletions
+287
View File
@@ -0,0 +1,287 @@
<script setup lang="ts">
/**
* 后台管理员账号管理(/admin/admins):
* 独立于前台 Casdoor 用户的后台账号,列表 + 新建 + 改密 + 删除(不能删自己)。
*/
import { computed, onMounted, ref } from 'vue'
import { useAdminStore } from '~/stores/admin'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '管理员' })
interface AdminRow {
id: number
username: string
createdAt: string
}
const toast = useToastStore()
const adminStore = useAdminStore()
const meId = computed(() => adminStore.admin?.id ?? -1)
/* ---------- 列表 ---------- */
const admins = ref<AdminRow[]>([])
const loading = ref(true)
const loadError = ref('')
const loadAdmins = async () => {
loading.value = true
loadError.value = ''
try {
const data = await $fetch<{ admins: AdminRow[] }>('/api/admin/admin-users')
admins.value = data.admins
} catch (err: any) {
loadError.value = err?.data?.message || '加载失败,请重试'
} finally {
loading.value = false
}
}
onMounted(loadAdmins)
/* ---------- 新建 ---------- */
const showCreate = ref(false)
const createForm = reactive({
username: '',
password: '',
confirm: '',
error: '',
})
const openCreate = () => {
createForm.username = ''
createForm.password = ''
createForm.confirm = ''
createForm.error = ''
showCreate.value = true
}
const doCreate = async () => {
createForm.error = ''
if (!/^[a-zA-Z0-9_]{2,20}$/.test(createForm.username.trim())) {
createForm.error = '用户名需为 2-20 位字母、数字或下划线'
return
}
if (createForm.password.length < 8) {
createForm.error = '密码至少需要 8 位'
return
}
if (createForm.password !== createForm.confirm) {
createForm.error = '两次输入的密码不一致'
return
}
try {
const data = await $fetch<{ admin: AdminRow }>('/api/admin/admin-users', {
method: 'POST',
body: { username: createForm.username.trim(), password: createForm.password },
})
admins.value = [...admins.value, data.admin].sort((a, b) => a.id - b.id)
showCreate.value = false
toast.success(`已添加管理员「${data.admin.username}」`)
} catch (err: any) {
createForm.error = err?.data?.message || '创建失败,请重试'
}
}
/* ---------- 修改密码 ---------- */
const editTarget = ref<AdminRow | null>(null)
const editForm = reactive({ password: '', confirm: '', error: '' })
const openEdit = (a: AdminRow) => {
editTarget.value = a
editForm.password = ''
editForm.confirm = ''
editForm.error = ''
}
const doEdit = async () => {
const a = editTarget.value
if (!a) return
editForm.error = ''
if (editForm.password.length < 8) {
editForm.error = '密码至少需要 8 位'
return
}
if (editForm.password !== editForm.confirm) {
editForm.error = '两次输入的密码不一致'
return
}
try {
await $fetch(`/api/admin/admin-users/${a.id}`, { method: 'PATCH', body: { password: editForm.password } })
toast.success(`已更新「${a.username}」的密码`)
editTarget.value = null
} catch (err: any) {
editForm.error = err?.data?.message || '更新失败,请重试'
}
}
/* ---------- 删除 ---------- */
const confirmDelete = ref<AdminRow | null>(null)
const deleting = ref(false)
const doDelete = async () => {
const a = confirmDelete.value
if (!a) return
deleting.value = true
try {
await $fetch(`/api/admin/admin-users/${a.id}`, { method: 'DELETE' })
admins.value = admins.value.filter((x) => x.id !== a.id)
toast.success(`已删除管理员「${a.username}」`)
confirmDelete.value = null
} catch (err: any) {
toast.error(err?.data?.message || '删除失败,请重试')
} finally {
deleting.value = false
}
}
const formatDate = (raw?: string) => {
if (!raw) return ''
const d = new Date(String(raw).replace(' ', 'T') + 'Z')
if (Number.isNaN(d.getTime())) return raw
return new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: 'short', day: 'numeric' }).format(d)
}
</script>
<template>
<div>
<AdminPageHeader title="管理员" subtitle="后台账号独立于前台用户,负责内容与系统管理">
<template #actions>
<AdminButton variant="secondary" size="sm" @click="loadAdmins">
<Icon name="ph:arrows-clockwise" class="w-4 h-4" /> 刷新
</AdminButton>
<AdminButton size="sm" @click="openCreate">
<Icon name="ph:user-plus" class="w-4 h-4" /> 添加管理员
</AdminButton>
</template>
</AdminPageHeader>
<div class="mb-4">
<span class="text-sm text-gray-500">共 {{ admins.length }} 个管理员</span>
</div>
<AdminCard v-if="loading">
<AdminSkeleton :rows="4" />
</AdminCard>
<div v-else-if="loadError" class="rounded-2xl bg-white border border-gray-100 shadow-sm p-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton size="sm" @click="loadAdmins">重新加载</AdminButton>
</div>
<AdminEmptyState v-else-if="!admins.length" icon="ph:users-three" title="暂无管理员" description="还没有后台管理员账号。" />
<!-- 列表(桌面表格 + 移动端卡片) -->
<template v-else>
<div class="hidden md:block rounded-2xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<div class="overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-100 bg-gray-50">
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">ID</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider">用户名</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider whitespace-nowrap">创建时间</th>
<th class="px-5 py-4 font-semibold text-xs uppercase tracking-wider text-right">操作</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-50">
<tr v-for="a in admins" :key="a.id" class="hover:bg-gray-50/60 transition-colors">
<td class="px-5 py-4 text-gray-400 font-mono text-xs whitespace-nowrap">#{{ a.id }}</td>
<td class="px-5 py-4 font-semibold text-black whitespace-nowrap">
{{ a.username }}
<AdminBadge v-if="a.id === meId" tone="black" class="ml-2">当前账号</AdminBadge>
</td>
<td class="px-5 py-4 text-gray-500 text-xs whitespace-nowrap">{{ formatDate(a.createdAt) }}</td>
<td class="px-5 py-4">
<div class="flex items-center justify-end gap-2">
<AdminButton size="sm" variant="secondary" @click="openEdit(a)">
<Icon name="ph:key" class="w-3.5 h-3.5" /> 改密
</AdminButton>
<AdminButton v-if="a.id !== meId" size="sm" variant="danger" @click="confirmDelete = a">
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</AdminButton>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- 移动端卡片 -->
<div class="md:hidden space-y-3">
<div v-for="a in admins" :key="a.id" class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4">
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-3 min-w-0">
<div class="w-10 h-10 rounded-full bg-black text-white flex items-center justify-center font-bold flex-shrink-0">
{{ (a.username || '?').charAt(0).toUpperCase() }}
</div>
<div class="min-w-0">
<p class="font-semibold text-black truncate">
{{ a.username }}
<AdminBadge v-if="a.id === meId" tone="black" class="ml-1">当前</AdminBadge>
</p>
<p class="text-xs text-gray-400 font-mono">#{{ a.id }}</p>
</div>
</div>
</div>
<dl class="mt-3 space-y-1.5 text-sm">
<div class="flex justify-between gap-3">
<dt class="text-gray-400 flex-shrink-0">创建时间</dt>
<dd class="text-gray-700 text-right">{{ formatDate(a.createdAt) }}</dd>
</div>
</dl>
<div class="mt-4 flex flex-wrap items-center gap-2">
<AdminButton size="sm" variant="secondary" class="min-h-10" @click="openEdit(a)">
<Icon name="ph:key" class="w-3.5 h-3.5" /> 修改密码
</AdminButton>
<AdminButton v-if="a.id !== meId" size="sm" variant="danger" class="min-h-10" @click="confirmDelete = a">
<Icon name="ph:trash" class="w-3.5 h-3.5" /> 删除
</AdminButton>
</div>
</div>
</div>
</template>
<!-- 新建弹窗 -->
<AdminModal :open="showCreate" title="添加管理员" @update:open="showCreate = $event">
<div class="space-y-4">
<AdminInput v-model="createForm.username" label="用户名" placeholder="2-20 位字母、数字或下划线" />
<AdminInput v-model="createForm.password" label="登录密码" type="password" placeholder="至少 8 位" autocomplete="new-password" />
<AdminInput v-model="createForm.confirm" label="确认密码" type="password" placeholder="再次输入密码" autocomplete="new-password" />
<p v-if="createForm.error" class="text-sm text-red-600">{{ createForm.error }}</p>
</div>
<template #footer>
<AdminButton variant="secondary" size="sm" @click="showCreate = false">取消</AdminButton>
<AdminButton size="sm" @click="doCreate">创建</AdminButton>
</template>
</AdminModal>
<!-- 改密弹窗 -->
<AdminModal :open="!!editTarget" :title="`修改密码 · ${editTarget?.username ?? ''}`" @update:open="editTarget = null">
<div class="space-y-4">
<AdminInput v-model="editForm.password" label="新密码" type="password" placeholder="至少 8 位" autocomplete="new-password" />
<AdminInput v-model="editForm.confirm" label="确认密码" type="password" placeholder="再次输入密码" autocomplete="new-password" />
<p v-if="editForm.error" class="text-sm text-red-600">{{ editForm.error }}</p>
</div>
<template #footer>
<AdminButton variant="secondary" size="sm" @click="editTarget = null">取消</AdminButton>
<AdminButton size="sm" @click="doEdit">保存</AdminButton>
</template>
</AdminModal>
<!-- 删除确认 -->
<AdminConfirm
:open="!!confirmDelete"
:loading="deleting"
danger
:message="`确定删除管理员「${confirmDelete?.username}」吗?此操作不可恢复。`"
@update:open="confirmDelete = null"
@confirm="doDelete"
/>
</div>
</template>
+127
View File
@@ -0,0 +1,127 @@
<script setup lang="ts">
/**
* 后台统一认证配置页(/admin/casdoor):
* 管理 Casdoor 登录所需配置(服务器地址、Client 凭据、证书、回调路径)。
* 配置持久化到 settings 表;保存后前台登录入口即时生效。
*/
import { onMounted, reactive, ref } from 'vue'
import { useAdminStore } from '~/stores/admin'
import { useToastStore } from '~/stores/toast'
definePageMeta({ middleware: 'admin', layout: 'admin' })
useHead({ title: '统一认证' })
interface CasdoorConfigForm {
enabled: boolean
serverUrl: string
clientId: string
clientSecret: string
orgName: string
appName: string
certificate: string
callbackPath: string
}
const toast = useToastStore()
const adminStore = useAdminStore()
const loading = ref(true)
const loadError = ref('')
const saving = ref(false)
const form = reactive<CasdoorConfigForm>({
enabled: false,
serverUrl: '',
clientId: '',
clientSecret: '',
orgName: '',
appName: '',
certificate: '',
callbackPath: '/api/auth/callback',
})
const loadConfig = async () => {
loading.value = true
loadError.value = ''
try {
const data = await $fetch<{ config: CasdoorConfigForm }>('/api/admin/casdoor-config')
Object.assign(form, data.config)
} catch (err: any) {
loadError.value = err?.data?.message || '配置加载失败'
} finally {
loading.value = false
}
}
onMounted(loadConfig)
const save = async () => {
saving.value = true
try {
await $fetch('/api/admin/casdoor-config', { method: 'PATCH', body: { config: { ...form } } })
toast.success('统一认证配置已保存')
} catch (err: any) {
toast.error(err?.data?.message || '保存失败,请重试')
} finally {
saving.value = false
}
}
</script>
<template>
<div>
<AdminPageHeader title="统一认证" subtitle="配置 Casdoor 单点登录(SSO),前台登录入口将跳转认证中心">
<template #actions>
<AdminButton :loading="saving" :disabled="loading || !!loadError" @click="save">
<Icon v-if="!saving" name="ph:floppy-disk" class="w-4 h-4" />
{{ saving ? '保存中…' : '保存配置' }}
</AdminButton>
</template>
</AdminPageHeader>
<div v-if="loading" class="space-y-6 max-w-5xl">
<AdminCard title="">
<AdminSkeleton :rows="6" />
</AdminCard>
</div>
<div v-else-if="loadError" class="max-w-5xl rounded-2xl bg-white border border-gray-100 shadow-sm p-10 text-center">
<Icon name="ph:warning-circle" class="w-10 h-10 text-gray-300 mx-auto mb-4" />
<p class="text-gray-500 mb-4">{{ loadError }}</p>
<AdminButton variant="secondary" @click="loadConfig">
<Icon name="ph:arrow-clockwise" class="w-4 h-4" /> 重新加载
</AdminButton>
</div>
<div v-else class="space-y-6 max-w-5xl">
<!-- 启用开关 -->
<AdminCard title="启用统一认证" subtitle="开启后前台登录入口跳转 Casdoor 认证中心">
<template #actions><Icon name="ph:plug" class="w-5 h-5 text-gray-300" /></template>
<div class="flex items-center gap-3">
<AdminToggle v-model="form.enabled" />
<span class="text-sm text-gray-600">{{ form.enabled ? '已开启,前台登录走 Casdoor' : '未开启,前台登录不可用' }}</span>
</div>
</AdminCard>
<!-- 连接信息 -->
<AdminCard title="连接信息" subtitle="必填:服务器地址、Client ID、组织名与应用名">
<template #actions><Icon name="ph:link" class="w-5 h-5 text-gray-300" /></template>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<AdminInput v-model="form.serverUrl" label="服务器地址" placeholder="https://casdoor.example.com" />
<AdminInput v-model="form.clientId" label="Client ID" />
<AdminInput v-model="form.clientSecret" label="Client Secret" type="password" placeholder="留空则保留旧值" />
<AdminInput v-model="form.orgName" label="组织名 (orgName)" />
<AdminInput v-model="form.appName" label="应用名 (appName)" />
<AdminInput v-model="form.callbackPath" label="回调路径" placeholder="/api/auth/callback" />
</div>
</AdminCard>
<!-- 证书 -->
<AdminCard title="证书" subtitle="用于验证 Casdoor 签发的 JWT,可在认证中心复制 PEM 原文或 base64">
<template #actions><Icon name="ph:certificate" class="w-5 h-5 text-gray-300" /></template>
<AdminTextarea v-model="form.certificate" label="证书公钥 (JWT 证书 PEM)" :rows="6" placeholder="-----BEGIN CERTIFICATE-----……" />
</AdminCard>
</div>
</div>
</template>
+75
View File
@@ -0,0 +1,75 @@
<script setup lang="ts">
/**
* 首个管理员初始化页(/admin/init):
* 系统尚未创建任何管理员时展示,输入用户名/密码创建首个管理员账号,
* 成功后建立管理员会话并进入后台。
*/
import { ref } from 'vue'
import { navigateTo } from '#app'
import { useAdminStore } from '~/stores/admin'
import { useToastStore } from '~/stores/toast'
definePageMeta({ layout: 'login' })
useHead({ title: '初始化管理员' })
const adminStore = useAdminStore()
const toast = useToastStore()
const username = ref('')
const password = ref('')
const confirm = ref('')
const submitting = ref(false)
const fieldError = ref('')
const submit = async () => {
fieldError.value = ''
if (!/^[a-zA-Z0-9_]{2,20}$/.test(username.value.trim())) {
fieldError.value = '用户名需为 2-20 位字母、数字或下划线'
return
}
if (password.value.length < 8) {
fieldError.value = '密码至少需要 8 位'
return
}
if (password.value !== confirm.value) {
fieldError.value = '两次输入的密码不一致'
return
}
submitting.value = true
try {
await $fetch('/api/auth/admin-init', { method: 'POST', body: { username: username.value.trim(), password: password.value } })
adminStore.needsInit = false
await adminStore.restoreAdmin()
toast.success('管理员已创建,欢迎进入后台')
await navigateTo('/admin')
} catch (err: any) {
toast.error(err?.data?.message || '初始化失败,请重试')
} finally {
submitting.value = false
}
}
</script>
<template>
<div class="min-h-screen flex items-center justify-center px-4 py-12">
<div class="w-full max-w-md">
<div class="text-center mb-8">
<div class="mx-auto w-12 h-12 rounded-full bg-black text-white flex items-center justify-center font-bold text-xl mb-4">A</div>
<h1 class="text-2xl font-bold text-black">初始化管理员</h1>
<p class="mt-2 text-sm text-gray-500">系统尚未创建后台管理员,请设置首个管理员账号以开启后台。</p>
</div>
<form class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 space-y-4" @submit.prevent="submit">
<AdminInput v-model="username" label="用户名" placeholder="2-20 位字母、数字或下划线" autocomplete="username" />
<AdminInput v-model="password" label="登录密码" type="password" placeholder="至少 8 位" autocomplete="new-password" />
<AdminInput v-model="confirm" label="确认密码" type="password" placeholder="再次输入密码" autocomplete="new-password" />
<p v-if="fieldError" class="text-sm text-red-600">{{ fieldError }}</p>
<AdminButton type="submit" block :loading="submitting">
{{ submitting ? '创建中…' : '创建并进入后台' }}
</AdminButton>
</form>
</div>
</div>
</template>
+61
View File
@@ -0,0 +1,61 @@
<script setup lang="ts">
/**
* 后台管理员登录页(/admin/login):
* 独立于前台 Casdoor 认证,使用 admin_users 表账号登录。
*/
import { ref } from 'vue'
import { navigateTo } from '#app'
import { useAdminStore } from '~/stores/admin'
import { useToastStore } from '~/stores/toast'
definePageMeta({ layout: 'login' })
useHead({ title: '后台登录' })
const adminStore = useAdminStore()
const toast = useToastStore()
const username = ref('')
const password = ref('')
const submitting = ref(false)
const submit = async () => {
if (!username.value.trim() || !password.value) return
submitting.value = true
try {
const res = await adminStore.login(username.value.trim(), password.value)
if (res.success) {
toast.success('欢迎回来')
await navigateTo('/admin')
} else {
toast.error('用户名或密码错误')
}
} finally {
submitting.value = false
}
}
</script>
<template>
<div class="min-h-screen flex items-center justify-center px-4 py-12">
<div class="w-full max-w-md">
<div class="text-center mb-8">
<div class="mx-auto w-12 h-12 rounded-full bg-black text-white flex items-center justify-center font-bold text-xl mb-4">A</div>
<h1 class="text-2xl font-bold text-black">后台登录</h1>
<p class="mt-2 text-sm text-gray-500">请使用后台管理员账号登录</p>
</div>
<form class="bg-white rounded-2xl border border-gray-100 shadow-sm p-6 space-y-4" @submit.prevent="submit">
<AdminInput v-model="username" label="用户名" placeholder="管理员用户名" autocomplete="username" />
<AdminInput v-model="password" label="密码" type="password" placeholder="登录密码" autocomplete="current-password" />
<AdminButton type="submit" block :loading="submitting">
{{ submitting ? '登录中…' : '登录' }}
</AdminButton>
</form>
<p class="mt-6 text-center text-sm text-gray-400">
<NuxtLink to="/" class="hover:text-gray-600">← 返回前台</NuxtLink>
</p>
</div>
</div>
</template>