fix admin invitations api url and account settings

This commit is contained in:
wlx committed 2026-09-18 19:06:18 +08:00
1 parent 7a18db2123
commit ed0cc75615
10 files changed
+201 -14

No files matched your search

@@ -16,6 +16,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@@ -59,6 +60,7 @@ public class AuthController {
public record RoleRequest(String role) {}
public record CreateUserRequest(String account, String password, String displayName) {}
public record AccountSettingsRequest(String displayName, String currentPassword, String newPassword) {}
@PostMapping("/admin/users")
public ResponseEntity<Map<String,Object>> createUser(@RequestBody CreateUserRequest input, HttpServletRequest request) {
@@ -102,6 +104,13 @@ public class AuthController {
return Map.of("user", authService.requireUser(sessionToken(request)));
}
@PatchMapping("/auth/account")
public Map<String, Object> updateAccount(@RequestBody AccountSettingsRequest input, HttpServletRequest request) {
return Map.of("user", authService.updateAccount(
sessionToken(request), input.displayName(), input.currentPassword(), input.newPassword(), meta(request)
));
}
@GetMapping("/admin/users")
public Map<String, Object> users(HttpServletRequest request) {
return Map.of("users", authService.listUsers(sessionToken(request)));
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.security.SecretCipher;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -18,6 +19,7 @@ import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@@ -31,17 +33,31 @@ public class AuthService {
private final PasswordHasher passwordHasher;
private final ObjectMapper objectMapper;
private final int sessionTtlHours;
private final SecretCipher secretCipher;
/** Kept for isolated unit tests that do not exercise encrypted invitation display. */
public AuthService(
JdbcTemplate jdbc,
PasswordHasher passwordHasher,
ObjectMapper objectMapper,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours
) {
this(jdbc, passwordHasher, objectMapper, sessionTtlHours, null);
}
@Autowired
public AuthService(
JdbcTemplate jdbc,
PasswordHasher passwordHasher,
ObjectMapper objectMapper,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
SecretCipher secretCipher
) {
this.jdbc = jdbc;
this.passwordHasher = passwordHasher;
this.objectMapper = objectMapper;
this.sessionTtlHours = sessionTtlHours;
this.secretCipher = secretCipher;
}
public record UserView(
@@ -209,6 +225,37 @@ public class AuthService {
return toView(findUserById(userId), null);
}
@Transactional
public UserView updateAccount(
String token,
String displayNameInput,
String currentPassword,
String newPassword,
RequestMeta meta
) {
UserRow user = requireUserRow(token);
String displayName = displayNameInput == null ? user.displayName() : displayNameInput.trim();
if (displayName.isBlank() || displayName.length() > 80) {
throw new ApiException("INVALID_NAME", "显示名称不能为空且最多 80 字符", 400);
}
boolean changingPassword = newPassword != null && !newPassword.isBlank();
if (changingPassword) {
if (currentPassword == null || currentPassword.isBlank() || !passwordHasher.matches(currentPassword, user.passwordHash())) {
throw new ApiException("INVALID_CURRENT_PASSWORD", "当前密码错误", 403);
}
if (newPassword.length() > 256 || (!"super_admin".equals(user.role()) && newPassword.length() < 8)) {
throw new ApiException("WEAK_PASSWORD", "普通用户新密码长度为 8 至 256 位", 400);
}
}
if (changingPassword) {
jdbc.update("UPDATE users SET display_name = ?, password_hash = ?, updated_at = ? WHERE id = ?", displayName, passwordHasher.hash(newPassword), now(), user.id());
} else {
jdbc.update("UPDATE users SET display_name = ?, updated_at = ? WHERE id = ?", displayName, now(), user.id());
}
audit("user.account_updated", user.id(), meta, Map.of("passwordChanged", changingPassword));
return toView(findUserById(user.id()), null);
}
private boolean isAdminRole(String role) {
return "admin".equals(role) || "super_admin".equals(role);
}
@@ -267,8 +314,9 @@ public class AuthService {
OffsetDateTime createdAt = now();
int allowedUses = maxUses == null ? 1 : Math.max(1, maxUses);
jdbc.update(
"INSERT INTO invitation_codes (id, code_hash, code_prefix, label, max_uses, used_count, expires_at, created_by, created_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)",
"INSERT INTO invitation_codes (id, code_hash, code_prefix, code_ciphertext, label, max_uses, used_count, expires_at, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?)",
id, hashSecret(code), code.substring(0, Math.min(code.length(), 10)),
secretCipher == null ? null : secretCipher.encrypt(code),
label == null || label.isBlank() ? "内测邀请码" : label.trim(), allowedUses, expiresAt, admin.id(), createdAt
);
audit("invitation.created", admin.id(), meta, Map.of("invitationId", id));
@@ -276,19 +324,20 @@ public class AuthService {
"code", code,
"invitation", invitationView(id, code.substring(0, Math.min(code.length(), 10)),
label == null || label.isBlank() ? "内测邀请码" : label.trim(), allowedUses, 0,
expiresAt, null, admin.id(), createdAt)
expiresAt, null, admin.id(), createdAt, code)
);
}
public List<Map<String, Object>> listInvitations(String token) {
requireAdmin(token);
return jdbc.query(
"SELECT id, code_prefix, label, max_uses, used_count, expires_at, disabled_at, created_by, created_at FROM invitation_codes ORDER BY created_at DESC",
"SELECT id, code_prefix, code_ciphertext, label, max_uses, used_count, expires_at, disabled_at, created_by, created_at FROM invitation_codes ORDER BY created_at DESC",
(resultSet, rowNumber) -> invitationView(
resultSet.getObject("id", UUID.class), resultSet.getString("code_prefix"), resultSet.getString("label"),
resultSet.getInt("max_uses"), resultSet.getInt("used_count"),
resultSet.getObject("expires_at", OffsetDateTime.class), resultSet.getObject("disabled_at", OffsetDateTime.class),
resultSet.getObject("created_by", UUID.class), resultSet.getObject("created_at", OffsetDateTime.class)
resultSet.getObject("created_by", UUID.class), resultSet.getObject("created_at", OffsetDateTime.class),
decryptInvitationCode(resultSet.getString("code_ciphertext"))
)
);
}
@@ -398,11 +447,12 @@ public class AuthService {
private Map<String, Object> invitationView(
UUID id, String prefix, String label, int maxUses, int usedCount, OffsetDateTime expiresAt,
OffsetDateTime disabledAt, UUID createdBy, OffsetDateTime createdAt
OffsetDateTime disabledAt, UUID createdBy, OffsetDateTime createdAt, String code
) {
Map<String, Object> result = new java.util.LinkedHashMap<>();
result.put("id", id);
result.put("codePrefix", prefix);
if (code != null && !code.isBlank()) result.put("code", code);
result.put("label", label);
result.put("maxUses", maxUses);
result.put("usedCount", usedCount);
@@ -413,6 +463,11 @@ public class AuthService {
return result;
}
private String decryptInvitationCode(String ciphertext) {
if (ciphertext == null || ciphertext.isBlank() || secretCipher == null) return null;
return secretCipher.decrypt(ciphertext);
}
private Map<String, Object> readJson(String value) {
try {
return objectMapper.readValue(value, new TypeReference<>() {});
@@ -0,0 +1,5 @@
ALTER TABLE invitation_codes
ADD COLUMN IF NOT EXISTS code_ciphertext text;
COMMENT ON COLUMN invitation_codes.code_ciphertext IS
'Reversible encrypted invitation code for authorized admin display; code_hash remains the lookup value.';
+2
View File
@@ -19,6 +19,7 @@
| `POST /api/auth/login` | 公开 | 账号密码登录 |
| `POST /api/auth/register` | 公开 | 邀请码注册 |
| `GET /api/auth/me` | 登录用户 | 当前会话用户 |
| `PATCH /api/auth/account` | 登录用户 | 修改显示名称或密码 |
| `POST /api/auth/logout` | 登录用户 | 撤销当前会话 |
| `GET /api/models` | 登录用户 | 用户端模型广场目录 |
| `GET/POST /api/projects` | 登录用户 | 工作区/项目基础管理 |
@@ -54,6 +55,7 @@
- `V6__seed_catalog.sql`:本地首批模型目录初始数据,可由管理员继续增删改造。
- `V7__async_tasks.sql`:3D/视频异步任务、状态和结果元数据。
- `V8__usage_payload_audit.sql`:调用/任务输入输出、分发 Key、供应商、错误、管理员备注和软删除字段。
- `V11__invitation_secrets_and_account_settings.sql`:保存新邀请码的加密副本,支持管理端记录页再次复制。
Java 版本沿用现有 TypeScript 服务的表命名,便于后续迁移 RDS;供应商密钥只返回掩码,数据库保存 AES-GCM 密文,主密钥由 `CREDENTIAL_ENCRYPTION_KEY` 注入。生产环境应进一步使用 KMS/RAM 托管该主密钥。
+4 -1
View File
@@ -8,12 +8,15 @@
- Key:先选模型,再勾选该模型的分组,可继续切换模型配置其他分组。授权只包含已保存的分组,不自动扩展到未来新增分组。清空授权后 Key 不能调用模型。
- 在线调试:模型和分组直接下拉选择;无需返回模型广场。
- 用户与额度:管理员可直接开通普通账号、创建邀请、发放人民币金额并查看流水;只有超级管理员能升降管理员角色。
- 邀请记录:新创建的邀请码会以加密形式保存在专用数据库中,管理员可在“用户与额度 → 邀请码记录”再次复制或停用;升级前已经创建的旧邀请码只保留哈希和前缀,不能恢复原文。
- 账号设置:用户菜单中的“账号设置”可以修改显示名称和密码;修改密码必须验证当前密码,普通用户新密码至少 8 位,超级管理员沿用其自定义长度规则。
- 统一 API 地址:生产前端按当前访问域名生成 `https://<域名>/v1`,本地开发仍使用开发环境的 Control Plane 地址。
`/api/models` 保留 `models`(分组/调用路由列表),新增 `logicalModels`(模型定义)。调用仍使用分组的 `id` 作为 `/v1/chat/completions` 的 `model` 值;`modelKey` 是可编辑的展示标识,不是自动路由或授权通配符。
## 旧数据升级
Flyway V10 自动将每条旧目录项转换为一个模型和一个既有分组;保留旧调用 ID、Key 权限及凭据。为避免错误合并,不按名称自动合并旧模型。需要合并时,在“编辑分组”中更改所属模型,再停用已无分组的旧模型即可。
Flyway V10 自动将每条旧目录项转换为一个模型和一个既有分组;V11 为新邀请码增加加密副本;保留旧调用 ID、Key 权限及凭据。为避免错误合并,不按名称自动合并旧模型。需要合并时,在“编辑分组”中更改所属模型,再停用已无分组的旧模型即可。
停用渠道、模型或分组后,对应调用立即不可用;旧 Key 的既有授权仍保留,重新启用后恢复。不能给 Key 新增已停用分组的权限。同一模型内分组名称不能重复。
+17 -2
View File
@@ -17,6 +17,7 @@ import { adminNavigation, userNavigation } from './data'
import AuthView from './views/AuthView.vue'
import AdminConsole from './views/AdminConsole.vue'
import UserConsole from './views/UserConsole.vue'
import AccountSettings from './components/AccountSettings.vue'
import type { Portal } from './types'
import { authClient, type AuthUser } from './services/auth'
@@ -30,6 +31,7 @@ const authUser = ref<AuthUser>()
const accountMenuOpen = ref(false)
const userName = ref('')
const availableCredit = ref<number>()
const accountSettingsOpen = ref(false)
onMounted(async () => {
try {
@@ -93,8 +95,13 @@ function logout() {
function openAccountSettings() {
accountMenuOpen.value = false
if (portal.value === 'admin') navigate('admin-settings')
else notify('账号设置将在后续阶段开放')
accountSettingsOpen.value = true
}
function accountSaved(user: AuthUser) {
authUser.value = user
userName.value = user.displayName
accountSettingsOpen.value = false
}
</script>
@@ -173,5 +180,13 @@ function openAccountSettings() {
</div>
<AccountSettings
v-if="accountSettingsOpen && authUser"
:user="authUser"
@close="accountSettingsOpen = false"
@saved="accountSaved"
@notify="notify"
/>
<Transition name="toast"><div v-if="toastMessage" class="toast"><ShieldCheck :size="17" /><span>{{ toastMessage }}</span><button @click="toastMessage = ''"><X :size="15" /></button></div></Transition>
</template>
+27 -5
View File
@@ -1,13 +1,14 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { Plus, KeyRound, CircleDollarSign, RefreshCcw, Search, ShieldCheck, List } from 'lucide-vue-next'
import { catalogClient, type AdminCatalogUser, type WalletEntry } from '../services/catalog'
import { Plus, KeyRound, CircleDollarSign, RefreshCcw, Search, ShieldCheck, List, Copy, Ban } from 'lucide-vue-next'
import { catalogClient, type AdminCatalogUser, type AdminInvitation, type WalletEntry } from '../services/catalog'
import type { AuthUser } from '../services/auth'
import UiModal from './UiModal.vue'
import SlidePanel from './SlidePanel.vue'
const props = defineProps<{ currentUser?: AuthUser }>()
const emit = defineEmits<{ notify: [message: string] }>()
const users = ref<AdminCatalogUser[]>([])
const invitations = ref<AdminInvitation[]>([])
const balances = ref<Record<string, number>>({})
const query = ref('')
const loading = ref(false)
@@ -34,9 +35,10 @@ async function refresh() {
loading.value = true
error.value = ''
try {
const [userResult, walletResult] = await Promise.all([catalogClient.listAdminUsers(), catalogClient.listWallets()])
const [userResult, walletResult, invitationResult] = await Promise.all([catalogClient.listAdminUsers(), catalogClient.listWallets(), catalogClient.listAdminInvitations()])
users.value = userResult.users
balances.value = Object.fromEntries(walletResult.wallets.map(item => [item.userId, Number(item.balance)]))
invitations.value = invitationResult.invitations
} catch (e) { error.value = e instanceof Error ? e.message : '加载失败' }
finally { loading.value = false }
}
@@ -63,6 +65,7 @@ async function save() {
} else if (editor.value === 'invite') {
inviteCode.value = (await catalogClient.createAdminInvitation({ label: inviteLabel.value, maxUses: 1 })).code
emit('notify', '邀请码已创建')
await refresh()
return
} else if (editor.value === 'role' && target.value) {
await catalogClient.changeUserRole(target.value.id, role.value)
@@ -77,6 +80,20 @@ async function save() {
} catch (e) { emit('notify', e instanceof Error ? e.message : '操作失败') }
finally { saving.value = false }
}
async function revokeInvitation(invitation: AdminInvitation) {
if (saving.value || invitation.disabledAt) return
saving.value = true
try {
await catalogClient.revokeAdminInvitation(invitation.id)
await refresh()
emit('notify', '邀请码已停用')
} catch (e) { emit('notify', e instanceof Error ? e.message : '停用邀请码失败') }
finally { saving.value = false }
}
async function copyText(value: string) {
try { await navigator.clipboard.writeText(value); emit('notify', '邀请码已复制') }
catch { emit('notify', '复制失败,请手动选择邀请码') }
}
</script>
<template>
@@ -84,11 +101,12 @@ async function save() {
<div class="account-summary"><span>用户 <strong>{{ users.length }}</strong></span><span>人民币余额合计 <strong>{{ money(totalBalance) }}</strong></span></div>
<label class="search-input account-search"><Search :size="16" /><input v-model="query" placeholder="搜索账号或姓名" /></label>
<p v-if="error" role="alert">{{ error }}</p><p v-if="loading">加载中…</p>
<div class="responsive-table"><table><thead><tr><th>用户</th><th>角色</th><th>人民币余额</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="user in filteredUsers" :key="user.id"><td><strong>{{ user.displayName }}</strong><small class="account-secondary">{{ user.account }}</small></td><td>{{ roleName(user.role) }}</td><td>{{ money(balances[user.id]) }}</td><td>{{ user.status === 'active' ? '正常' : '已停用' }}</td><td><div class="heading-actions"><button class="button secondary small" :disabled="user.status !== 'active'" @click="credit(user)"><CircleDollarSign :size="15" />发放额度</button><button class="icon-button" :title="`${user.account} 额度流水`" @click="ledger(user)"><List :size="16" /></button><button v-if="props.currentUser?.role === 'super_admin' && user.role !== 'super_admin'" class="icon-button" :title="`${user.account} 修改角色`" @click="editRole(user)"><ShieldCheck :size="16" /></button></div></td></tr><tr v-if="!filteredUsers.length && !loading"><td colspan="5">暂无用户</td></tr></tbody></table></div>
<div class="responsive-table"><table><thead><tr><th>用户</th><th>角色</th><th>人民币余额</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="user in filteredUsers" :key="user.id"><td><strong>{{ user.displayName }}</strong><small class="account-secondary">{{ user.account }}</small></td><td>{{ roleName(user.role) }}</td><td>{{ money(balances[user.id]) }}</td><td>{{ user.status === 'active' ? '正常' : '已停用' }}</td><td><div class="heading-actions"><button class="button secondary small" :disabled="user.status !== 'active'" @click="credit(user)"><CircleDollarSign :size="15" />发放额度</button><button class="button secondary small" @click="editRole(user)" v-if="props.currentUser?.role === 'super_admin' && user.role !== 'super_admin'"><ShieldCheck :size="15" />修改角色</button><button class="icon-button" :title="`${user.account} 额度流水`" @click="ledger(user)"><List :size="16" /></button></div></td></tr><tr v-if="!filteredUsers.length && !loading"><td colspan="5">暂无用户</td></tr></tbody></table></div>
<section class="panel invitation-panel"><header class="panel-header"><div><span>INVITATION RECORDS</span><h3>邀请码记录</h3></div><small>{{ invitations.length }} 条</small></header><div class="responsive-table"><table><thead><tr><th>邀请码</th><th>备注</th><th>使用情况</th><th>创建时间</th><th>操作</th></tr></thead><tbody><tr v-for="invitation in invitations" :key="invitation.id"><td><code>{{ invitation.code || `${invitation.codePrefix}…(旧记录仅保留前缀)` }}</code><button v-if="invitation.code" class="icon-button" title="复制邀请码" @click="copyText(invitation.code)"><Copy :size="14" /></button></td><td>{{ invitation.label }}</td><td>{{ invitation.usedCount }} / {{ invitation.maxUses }}{{ invitation.disabledAt ? ' · 已停用' : '' }}</td><td>{{ new Date(invitation.createdAt).toLocaleString('zh-CN') }}</td><td><button v-if="!invitation.disabledAt" class="button danger small" :disabled="saving" @click="revokeInvitation(invitation)"><Ban :size="14" />停用</button><span v-else>—</span></td></tr><tr v-if="!invitations.length"><td colspan="5">暂无邀请码记录</td></tr></tbody></table></div></section>
<UiModal v-if="editor" :title="editor === 'account' ? '开通账号' : editor === 'invite' ? '创建邀请' : editor === 'credit' ? '发放人民币额度' : '修改角色'" @close="!saving && (editor = '')">
<form id="account-editor" @submit.prevent="save">
<template v-if="editor === 'account'"><label class="form-label" for="new-account">账号</label><input id="new-account" v-model="account.account" class="text-input" required maxlength="254" autocomplete="off" placeholder="用户名、邮箱或手机号" /><label class="form-label" for="new-display">显示名称</label><input id="new-display" v-model="account.displayName" class="text-input" maxlength="80" /><label class="form-label" for="new-password">初始密码</label><input id="new-password" v-model="account.password" type="password" class="text-input" required minlength="8" maxlength="256" autocomplete="new-password" /></template>
<template v-else-if="editor === 'invite'"><label class="form-label" for="invite-label">邀请备注</label><input id="invite-label" v-model="inviteLabel" class="text-input" :disabled="!!inviteCode" /><label v-if="inviteCode" class="form-label" for="invite-code">邀请码(仅显示一次)</label><input v-if="inviteCode" id="invite-code" :value="inviteCode" class="text-input" readonly /></template>
<template v-else-if="editor === 'invite'"><label class="form-label" for="invite-label">邀请备注</label><input id="invite-label" v-model="inviteLabel" class="text-input" :disabled="!!inviteCode" /><label v-if="inviteCode" class="form-label" for="invite-code">邀请码</label><input v-if="inviteCode" id="invite-code" :value="inviteCode" class="text-input" readonly /><p v-if="inviteCode" class="form-hint">邀请码已保存到下方记录,可稍后再次复制。</p></template>
<template v-else-if="editor === 'credit'"><p>{{ target?.displayName }} · {{ target?.account }}</p><p>当前余额:{{ money(balances[target?.id || '']) }}</p><label class="form-label" for="grant-amount">发放金额(人民币元)</label><input id="grant-amount" v-model="amount" class="text-input" required type="number" min="0.01" max="1000000" step="0.01" :disabled="!!submittedGrant" /><label class="form-label" for="grant-reason">发放原因</label><textarea id="grant-reason" v-model="reason" class="text-input" required maxlength="500" :disabled="!!submittedGrant" /><p>本次增加:{{ money(Number(amount)) }}</p></template>
<template v-else><p>{{ target?.displayName }} · {{ target?.account }}</p><label class="form-label" for="account-role">角色</label><select id="account-role" v-model="role" class="text-input"><option value="user">普通用户</option><option value="admin">管理员</option></select></template>
</form>
@@ -102,5 +120,9 @@ async function save() {
.account-search { max-width: 420px; }
.account-secondary { display: block; margin-top: 5px; color: #687378; }
.wallet-entry { border-bottom: 1px solid #dce3e5; padding: 16px 0; overflow-wrap: anywhere; }
.invitation-panel { margin-top: 24px; }
.invitation-panel code { overflow-wrap: anywhere; }
.invitation-panel .icon-button { margin-left: 8px; vertical-align: middle; }
.form-hint { color: #687378; font-size: 13px; }
@media(max-width: 700px) { .heading-actions { flex-wrap: wrap; } }
</style>
@@ -0,0 +1,60 @@
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { authClient, type AuthUser } from '../services/auth'
import UiModal from './UiModal.vue'
const props = defineProps<{ user: AuthUser }>()
const emit = defineEmits<{ close: []; saved: [user: AuthUser]; notify: [message: string] }>()
const form = reactive({ displayName: props.user.displayName, currentPassword: '', newPassword: '', confirmPassword: '' })
const saving = ref(false)
async function save() {
if (saving.value) return
if (!form.displayName.trim()) return emit('notify', '显示名称不能为空')
if (form.newPassword || form.confirmPassword || form.currentPassword) {
if (!form.currentPassword) return emit('notify', '修改密码需要填写当前密码')
if (form.newPassword !== form.confirmPassword) return emit('notify', '两次输入的新密码不一致')
if (!form.newPassword) return emit('notify', '新密码不能为空')
}
saving.value = true
try {
const user = await authClient.updateAccount({
displayName: form.displayName.trim(),
currentPassword: form.currentPassword || undefined,
newPassword: form.newPassword || undefined,
})
emit('saved', user)
emit('notify', '账号设置已保存')
} catch (error) {
emit('notify', error instanceof Error ? error.message : '账号设置保存失败')
} finally {
saving.value = false
}
}
</script>
<template>
<UiModal title="账号设置" eyebrow="ACCOUNT SETTINGS" @close="!saving && emit('close')">
<form id="account-settings" @submit.prevent="save">
<p class="account-settings-account">账号:{{ props.user.account }}</p>
<label class="form-label" for="account-display-name">显示名称</label>
<input id="account-display-name" v-model="form.displayName" class="text-input" maxlength="80" required />
<label class="form-label" for="account-current-password">当前密码</label>
<input id="account-current-password" v-model="form.currentPassword" type="password" class="text-input" autocomplete="current-password" placeholder="仅修改密码时需要" />
<label class="form-label" for="account-new-password">新密码</label>
<input id="account-new-password" v-model="form.newPassword" type="password" class="text-input" maxlength="256" autocomplete="new-password" placeholder="留空表示不修改" />
<label class="form-label" for="account-confirm-password">确认新密码</label>
<input id="account-confirm-password" v-model="form.confirmPassword" type="password" class="text-input" maxlength="256" autocomplete="new-password" placeholder="留空表示不修改" />
<p class="form-hint">普通用户新密码至少 8 位;超级管理员按实际设置保存。</p>
</form>
<template #footer>
<button class="button secondary" :disabled="saving" @click="emit('close')">取消</button>
<button class="button primary" type="submit" form="account-settings" :disabled="saving">{{ saving ? '保存中…' : '保存设置' }}</button>
</template>
</UiModal>
</template>
<style scoped>
.account-settings-account { color: #687378; margin: 0 0 18px; }
.form-hint { color: #687378; font-size: 13px; margin: 14px 0 0; }
</style>
+9
View File
@@ -31,6 +31,7 @@ export interface AuthClient {
login(input: LoginInput): Promise<AuthUser>
register(input: RegisterInput): Promise<AuthUser>
currentUser(): Promise<AuthUser | undefined>
updateAccount(input: { displayName: string; currentPassword?: string; newPassword?: string }): Promise<AuthUser>
logout(): Promise<void>
}
@@ -77,6 +78,14 @@ class HttpAuthClient implements AuthClient {
}
}
async updateAccount(input: { displayName: string; currentPassword?: string; newPassword?: string }) {
const payload = await this.request<{ user: AuthUser }>('/api/auth/account', {
method: 'PATCH',
body: JSON.stringify(input),
})
return payload.user
}
async logout() {
await this.request('/api/auth/logout', { method: 'POST' })
}
+8 -1
View File
@@ -161,6 +161,7 @@ export interface AdminAuditEvent {
export interface AdminInvitation {
id: string
codePrefix: string
code?: string
label: string
maxUses: number
usedCount: number
@@ -343,6 +344,10 @@ class HttpCatalogClient {
return this.request<{ code: string; invitation: AdminInvitation }>('/api/admin/invitations', { method: 'POST', body: JSON.stringify(input) })
}
async revokeAdminInvitation(id: string) {
await this.request(`/api/admin/invitations/${encodeURIComponent(id)}/revoke`, { method: 'POST' })
}
async listAdminProviders() {
return this.request<{ providers: CatalogProvider[] }>('/api/admin/providers')
}
@@ -387,4 +392,6 @@ class HttpCatalogClient {
const controlPlaneUrl = (import.meta.env.VITE_CONTROL_PLANE_URL || 'http://127.0.0.1:8787').replace(/\/$/, '')
export const catalogClient = new HttpCatalogClient(controlPlaneUrl)
export const platformApiBaseUrl = (import.meta.env.VITE_PUBLIC_API_BASE_URL || `${controlPlaneUrl}/v1`).replace(/\/$/, '')
const runtimeOrigin = typeof window !== 'undefined' ? window.location.origin : ''
const publicApiOrigin = import.meta.env.VITE_CONTROL_PLANE_URL === '/' ? runtimeOrigin : controlPlaneUrl
export const platformApiBaseUrl = (import.meta.env.VITE_PUBLIC_API_BASE_URL || `${publicApiOrigin}/v1`).replace(/\/$/, '')