feat: add unique super administrator and role management

This commit is contained in:
wlx committed 2026-09-17 19:03:51 +08:00
1 parent 9e731e47b9
commit 386d15cde2
16 files changed
+455 -24

No files matched your search

@@ -45,6 +45,8 @@ public class AuthController {
public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {} public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
public record RoleRequest(String role) {}
@PostMapping("/auth/login") @PostMapping("/auth/login")
public Map<String, Object> login( public Map<String, Object> login(
@RequestBody LoginRequest input, @RequestBody LoginRequest input,
@@ -86,6 +88,15 @@ public class AuthController {
return Map.of("users", authService.listUsers(sessionToken(request))); return Map.of("users", authService.listUsers(sessionToken(request)));
} }
@PostMapping("/admin/users/{id}/role")
public Map<String, Object> changeRole(
@PathVariable UUID id,
@RequestBody RoleRequest input,
HttpServletRequest request
) {
return Map.of("user", authService.changeRole(sessionToken(request), id, input.role(), meta(request)));
}
@GetMapping("/admin/invitations") @GetMapping("/admin/invitations")
public Map<String, Object> invitations(HttpServletRequest request) { public Map<String, Object> invitations(HttpServletRequest request) {
return Map.of("invitations", authService.listInvitations(sessionToken(request))); return Map.of("invitations", authService.listInvitations(sessionToken(request)));
@@ -13,6 +13,7 @@ import java.time.OffsetDateTime;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.util.Base64; import java.util.Base64;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -73,17 +74,31 @@ public class AuthService {
@Transactional @Transactional
public void ensureAdmin(String accountInput, String password, String displayName) { public void ensureAdmin(String accountInput, String password, String displayName) {
String account = normalizeAccount(accountInput); String account = normalizeAccount(accountInput);
if (account.isBlank() || password.isBlank()) { if (account.isBlank() || password == null || password.isBlank()) {
throw new ApiException("INVALID_ADMIN_CONFIG", "管理员初始配置无效", 500); throw new ApiException("INVALID_ADMIN_CONFIG", "管理员初始配置无效", 500);
} }
if (findUserByAccount(account) != null) { // Serialize bootstrap across replicas, including the first creation.
jdbc.execute("LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE");
List<String> owners = jdbc.queryForList("SELECT account FROM users WHERE role = 'super_admin'", String.class);
if (!owners.isEmpty()) {
if (!owners.getFirst().equals(account)) {
throw new IllegalStateException("ADMIN_ACCOUNT differs from the existing super administrator; refusing to create another owner.");
}
return;
}
UserRow existing = findUserByAccount(account);
if (existing != null) {
if (!"admin".equals(existing.role()) || !"active".equals(existing.status())) {
throw new IllegalStateException("Bootstrap account must be an active administrator; refusing to promote an ordinary or disabled user.");
}
jdbc.update("UPDATE users SET role = 'super_admin', updated_at = ? WHERE id = ?", now(), existing.id());
return; return;
} }
OffsetDateTime now = now(); OffsetDateTime now = now();
jdbc.update( jdbc.update(
"INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'admin', 'active', ?, ?)", "INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'super_admin', 'active', ?, ?)",
UUID.randomUUID(), account, accountKind(account), passwordHasher.hash(password), UUID.randomUUID(), account, accountKind(account), passwordHasher.hash(password),
displayName == null || displayName.isBlank() ? "平台管理员" : displayName.trim(), now, now displayName == null || displayName.isBlank() ? "超级管理员" : displayName.trim(), now, now
); );
} }
@@ -155,12 +170,49 @@ public class AuthService {
public UserView requireAdmin(String token) { public UserView requireAdmin(String token) {
UserRow user = requireUserRow(token); UserRow user = requireUserRow(token);
if (!"admin".equals(user.role())) { if (!isAdminRole(user.role())) {
throw new ApiException("FORBIDDEN", "需要管理员权限", 403); throw new ApiException("FORBIDDEN", "需要管理员权限", 403);
} }
return toView(user, null); return toView(user, null);
} }
public UserView requireSuperAdmin(String token) {
UserRow user = requireUserRow(token);
if (!"super_admin".equals(user.role())) {
throw new ApiException("FORBIDDEN", "需要超级管理员权限", 403);
}
return toView(user, null);
}
@Transactional
public UserView changeRole(String token, UUID userId, String requestedRole, RequestMeta meta) {
UserView actor = requireSuperAdmin(token);
String role = requestedRole == null ? "" : requestedRole.trim().toLowerCase(Locale.ROOT);
if (!role.equals("user") && !role.equals("admin")) {
throw new ApiException("INVALID_ROLE", "只能授予普通用户或管理员角色", 400);
}
if (actor.id().equals(userId)) {
throw new ApiException("SELF_ROLE_CHANGE", "超级管理员不能修改自己的角色", 400);
}
List<UserRow> targets = jdbc.query("SELECT * FROM users WHERE id = ? FOR UPDATE", this::mapUser, userId);
if (targets.isEmpty()) {
throw new ApiException("USER_NOT_FOUND", "用户不存在", 404);
}
UserRow target = targets.getFirst();
if ("super_admin".equals(target.role())) {
throw new ApiException("SUPER_ADMIN_PROTECTED", "超级管理员账号不可通过此接口降级", 403);
}
if (!role.equals(target.role())) {
jdbc.update("UPDATE users SET role = ?, updated_at = ? WHERE id = ?", role, now(), userId);
audit("user.role_changed", actor.id(), meta, Map.of("targetUserId", userId, "fromRole", target.role(), "role", role));
}
return toView(findUserById(userId), null);
}
private boolean isAdminRole(String role) {
return "admin".equals(role) || "super_admin".equals(role);
}
public void logout(String token, RequestMeta meta) { public void logout(String token, RequestMeta meta) {
if (token == null || token.isBlank()) { if (token == null || token.isBlank()) {
return; return;
@@ -0,0 +1,8 @@
-- Keep one protected platform owner while retaining a lower-privilege operator role.
ALTER TABLE users DROP CONSTRAINT IF EXISTS users_role_check;
ALTER TABLE users
ADD CONSTRAINT users_role_check CHECK (role IN ('user', 'admin', 'super_admin'));
CREATE UNIQUE INDEX IF NOT EXISTS users_single_super_admin_idx
ON users (role)
WHERE role = 'super_admin';
@@ -0,0 +1,112 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiExceptionHandler;
import jakarta.servlet.http.Cookie;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@EnabledIfEnvironmentVariable(named = "MOYI_AUTH_TEST_JDBC_URL", matches = "jdbc:postgresql://127\\.0\\.0\\.1:[0-9]+/.+")
class AuthPostgresTest {
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
static class Transactions {}
@Test
void migrationBootstrapRegistrationAndLiveRoleChanges() throws Exception {
String url = System.getenv("MOYI_AUTH_TEST_JDBC_URL");
String schema = "auth_test_" + UUID.randomUUID().toString().replace("-", "");
DriverManagerDataSource base = new DriverManagerDataSource(url, "moyi_role_test", "");
DriverManagerDataSource source = new DriverManagerDataSource(url + "?currentSchema=" + schema, "moyi_role_test", "");
JdbcTemplate jdbc = new JdbcTemplate(source);
PasswordHasher hasher = new PasswordHasher("isolated-test-pepper");
ObjectMapper json = new ObjectMapper().findAndRegisterModules();
UUID ownerId = UUID.randomUUID();
UUID operatorId = UUID.randomUUID();
try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) {
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).target("8").load().migrate();
String insert = "INSERT INTO users (id, account, account_kind, password_hash, display_name, role) VALUES (?, ?, 'username', ?, ?, 'admin')";
jdbc.update(insert, ownerId, "adimin", hasher.hash("test-password"), "Owner");
jdbc.update(insert, operatorId, "operator", hasher.hash("test-password"), "Operator");
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate();
context.register(Transactions.class);
context.registerBean(DataSource.class, () -> source);
context.registerBean(DataSourceTransactionManager.class, () -> new DataSourceTransactionManager(source));
context.registerBean(AuthService.class, () -> new AuthService(jdbc, hasher, json, 168));
context.refresh();
AuthService auth = context.getBean(AuthService.class);
try (var threads = Executors.newFixedThreadPool(2)) {
var first = threads.submit(() -> auth.ensureAdmin("adimin", "ignored-new-password", "Owner"));
var second = threads.submit(() -> auth.ensureAdmin("adimin", "ignored-new-password", "Owner"));
first.get(15, TimeUnit.SECONDS);
second.get(15, TimeUnit.SECONDS);
}
assertEquals(1, jdbc.queryForObject("SELECT count(*) FROM users WHERE role = 'super_admin'", Integer.class));
assertEquals("admin", jdbc.queryForObject("SELECT role FROM users WHERE id = ?", String.class, operatorId));
assertThrows(DataIntegrityViolationException.class, () -> jdbc.update("UPDATE users SET role = 'super_admin' WHERE id = ?", operatorId));
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("operator", "test-password", "Other"));
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth, 168, true))
.setControllerAdvice(new ApiExceptionHandler()).build();
var ownerCookie = login(http, "adimin", "super_admin");
var operatorCookie = login(http, "operator", "admin");
String inviteResponse = http.perform(post("/api/admin/invitations").cookie(ownerCookie).contentType("application/json").content("{}"))
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsString();
String code = json.readTree(inviteResponse).get("code").asText();
Map<String, String> registration = Map.of("invitationCode", code, "account", "member@example.test", "password", "test-password", "role", "super_admin");
var registered = http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(registration)))
.andExpect(status().isCreated()).andExpect(jsonPath("$.user.role").value("user"))
.andExpect(cookie().httpOnly("moyi_session", true)).andExpect(cookie().secure("moyi_session", true))
.andReturn().getResponse();
UUID memberId = UUID.fromString(json.readTree(registered.getContentAsString()).get("user").get("id").asText());
Cookie memberCookie = registered.getCookie("moyi_session");
http.perform(get("/api/auth/me").cookie(memberCookie)).andExpect(status().isOk()).andExpect(jsonPath("$.user.role").value("user"));
http.perform(get("/api/admin/users").cookie(memberCookie)).andExpect(status().isForbidden());
http.perform(get("/api/admin/users")).andExpect(status().isUnauthorized());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(operatorCookie).contentType("application/json").content("{\"role\":\"admin\"}"))
.andExpect(status().isForbidden());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"super_admin\"}"))
.andExpect(status().isBadRequest());
http.perform(post("/api/admin/users/" + ownerId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"user\"}"))
.andExpect(status().isBadRequest());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"admin\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.user.role").value("admin"));
http.perform(get("/api/admin/users").cookie(memberCookie)).andExpect(status().isOk());
http.perform(post("/api/admin/users/" + memberId + "/role").cookie(ownerCookie).contentType("application/json").content("{\"role\":\"user\"}"))
.andExpect(status().isOk());
http.perform(get("/api/admin/users").cookie(memberCookie)).andExpect(status().isForbidden());
assertEquals(2, jdbc.queryForObject("SELECT count(*) FROM auth_audit_log WHERE event_type = 'user.role_changed'", Integer.class));
registration = Map.of("invitationCode", code, "account", "another@example.test", "password", "test-password");
http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(registration)))
.andExpect(status().isForbidden());
} finally {
// Only remove the randomly named schema created by this test, never application data.
new JdbcTemplate(base).execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE");
}
}
private Cookie login(MockMvc http, String account, String role) throws Exception {
return http.perform(post("/api/auth/login").contentType("application/json")
.content("{\"account\":\"" + account + "\",\"password\":\"test-password\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.user.role").value(role))
.andReturn().getResponse().getCookie("moyi_session");
}
}
@@ -0,0 +1,139 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import java.sql.ResultSet;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class AuthRolesTest {
private final JdbcTemplate jdbc = mock(JdbcTemplate.class);
private final PasswordHasher hasher = mock(PasswordHasher.class);
private final AuthService auth = new AuthService(jdbc, hasher, new ObjectMapper(), 168);
private final AuthService.RequestMeta meta = new AuthService.RequestMeta("127.0.0.1", "test");
private final UUID ownerId = UUID.randomUUID();
private final UUID userId = UUID.randomUUID();
@Test
void bootstrapCreatesOneOwnerAndHashesPassword() {
doThrow(new EmptyResultDataAccessException(1)).when(jdbc).queryForObject(anyString(), any(RowMapper.class), any(Object[].class));
when(hasher.hash("test-password")).thenReturn("hashed-test-password");
auth.ensureAdmin("adimin", "test-password", "Owner");
verify(jdbc).execute("LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE");
verify(jdbc).update(contains("'super_admin', 'active'"), any(Object[].class));
verify(hasher).hash("test-password");
}
@Test
void bootstrapPromotesLegacyAdminWithoutReplacingPassword() throws Exception {
lookupUser(ownerId, "admin");
auth.ensureAdmin("adimin", "test-password", "Owner");
verify(jdbc).update(contains("SET role = 'super_admin'"), any(Object[].class));
verifyNoInteractions(hasher);
}
@Test
void repeatedBootstrapDoesNotResetPassword() {
when(jdbc.queryForList(contains("role = 'super_admin'"), eq(String.class))).thenReturn(List.of("adimin"));
auth.ensureAdmin("adimin", "different-password", "Owner");
verify(jdbc, never()).update(anyString(), any(Object[].class));
verifyNoInteractions(hasher);
}
@Test
void changingBootstrapAccountCannotCreateAnotherOwner() {
when(jdbc.queryForList(contains("role = 'super_admin'"), eq(String.class))).thenReturn(List.of("adimin"));
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("other", "test-password", "Owner"));
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void bootstrapCannotPromoteOrdinaryRegisteredUser() throws Exception {
lookupUser(userId, "user");
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("adimin", "test-password", "Owner"));
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void ownerAndAdminCanAccessOperationsButUserCannot() throws Exception {
sessionUser(ownerId, "super_admin");
assertEquals("super_admin", auth.requireAdmin("session").role());
sessionUser(userId, "admin");
assertEquals("admin", auth.requireAdmin("session").role());
sessionUser(userId, "user");
assertEquals(403, assertThrows(ApiException.class, () -> auth.requireAdmin("session")).getStatus());
}
@Test
void adminCannotChangeRolesEvenWithForgedRequest() throws Exception {
sessionUser(userId, "admin");
assertEquals(403, assertThrows(ApiException.class, () -> auth.changeRole("session", ownerId, "user", meta)).getStatus());
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void ownerCannotAssignAnotherOwnerOrDemoteSelf() throws Exception {
sessionUser(ownerId, "super_admin");
assertEquals("INVALID_ROLE", assertThrows(ApiException.class, () -> auth.changeRole("session", userId, "super_admin", meta)).getCode());
assertEquals("SELF_ROLE_CHANGE", assertThrows(ApiException.class, () -> auth.changeRole("session", ownerId, "user", meta)).getCode());
verify(jdbc, never()).update(anyString(), any(Object[].class));
}
@Test
void missingUserReturns404() throws Exception {
sessionUser(ownerId, "super_admin");
assertEquals(404, assertThrows(ApiException.class, () -> auth.changeRole("session", userId, "admin", meta)).getStatus());
}
@Test
void ownerCanPromoteAndDemoteWithAudit() throws Exception {
sessionUser(ownerId, "super_admin");
targetUser(userId, "user");
lookupUser(userId, "admin");
assertEquals("admin", auth.changeRole("session", userId, "admin", meta).role());
targetUser(userId, "admin");
lookupUser(userId, "user");
assertEquals("user", auth.changeRole("session", userId, "user", meta).role());
verify(jdbc, times(2)).update(startsWith("UPDATE users SET role = ?"), any(Object[].class));
verify(jdbc, times(2)).update(startsWith("INSERT INTO auth_audit_log"), any(Object[].class));
}
private void sessionUser(UUID id, String role) throws Exception {
ResultSet row = row(id, role);
doAnswer(call -> List.of(((RowMapper<?>) call.getArgument(1)).mapRow(row, 0)))
.when(jdbc).query(contains("JOIN users"), any(RowMapper.class), any(Object[].class));
}
private void targetUser(UUID id, String role) throws Exception {
ResultSet row = row(id, role);
doAnswer(call -> List.of(((RowMapper<?>) call.getArgument(1)).mapRow(row, 0)))
.when(jdbc).query(contains("FOR UPDATE"), any(RowMapper.class), any(Object[].class));
}
private void lookupUser(UUID id, String role) throws Exception {
ResultSet row = row(id, role);
doAnswer(call -> ((RowMapper<?>) call.getArgument(1)).mapRow(row, 0))
.when(jdbc).queryForObject(anyString(), any(RowMapper.class), any(Object[].class));
}
private ResultSet row(UUID id, String role) throws Exception {
ResultSet result = mock(ResultSet.class);
when(result.getObject("id", UUID.class)).thenReturn(id);
when(result.getString("account")).thenReturn("adimin");
when(result.getString("account_kind")).thenReturn("username");
when(result.getString("password_hash")).thenReturn("existing-hash");
when(result.getString("display_name")).thenReturn("Test");
when(result.getString("role")).thenReturn(role);
when(result.getString("status")).thenReturn("active");
when(result.getObject("created_at", OffsetDateTime.class)).thenReturn(OffsetDateTime.now());
return result;
}
}
+3 -1
View File
@@ -67,7 +67,9 @@ docker compose up -d
Invoke-WebRequest http://localhost:8080/health Invoke-WebRequest http://localhost:8080/health
``` ```
默认开发管理员来自 `.env`:`ADMIN_ACCOUNT=adimin`,首次启动时由 Java 服务创建。生产环境必须替换管理员密码、密码 Pepper、数据库密码和 Redis 密码。 默认开发管理员来自 `.env`:`ADMIN_ACCOUNT=adimin`。V9 起首次启动创建唯一 `super_admin`,现有同名且正常的 `admin` 自动升级,其他管理员保持 `admin`。服务器初始密码由 `deploy.py init` 随机生成并保存在 `.env.cloud` 的 `ADMIN_PASSWORD` 中,不是本地开发密码;启动不会覆盖已有密码。生产环境必须替换开发密码、密码 Pepper、数据库密码和 Redis 密码。
超级管理员可以通过用户详情调整其他用户的 `user` / `admin` 角色;普通管理员不能调用角色管理接口,也不能更改超级管理员。注册始终创建 `user`,不接受客户端指定角色。数据库通过唯一索引限制超级管理员数量。修改 `ADMIN_ACCOUNT` 不是转让超级管理员的方法,已有超级管理员与配置不一致时启动会拒绝创建第二个账号。
## 验收边界 ## 验收边界
+20
View File
@@ -162,6 +162,15 @@ sudo nano .env.cloud
`init` 自动生成随机管理员初始密码、密码 Pepper 和供应商凭证加密密钥,配置文件权限 600;已存在配置时拒绝覆盖。账号仍是已约定的 `adimin`,**云端不使用 `admin123`**。初始密码在服务器 `.env.cloud` 中查看,不会打印到日志。 `init` 自动生成随机管理员初始密码、密码 Pepper 和供应商凭证加密密钥,配置文件权限 600;已存在配置时拒绝覆盖。账号仍是已约定的 `adimin`,**云端不使用 `admin123`**。初始密码在服务器 `.env.cloud` 中查看,不会打印到日志。
### 超级管理员与登录注册
- 首次初始化创建唯一的 `super_admin`(超级管理员);`admin`(平台管理员)可以管理日常业务,但不能任免管理员。
- 从旧版升级时,`ADMIN_ACCOUNT` 对应的正常管理员自动升为超级管理员,账号、原密码和现有会话保留。其他管理员不会自动升级。
- 已存在超级管理员时,`ADMIN_ACCOUNT` 必须与其账号一致,否则启动拒绝继续;不要通过改账号创建第二个超级管理员。数据库唯一索引也会阻止第二个超级管理员。
- 用户通过邀请码注册,角色固定为普通用户;注册成功即登录。超级管理员进入“管理端 → 用户与额度”,点击用户行,再通过“调整角色”授予或撤销平台管理员身份。不能在此处降级自己或创建第二个超级管理员。角色变化写入审计,降级后原会话的管理接口权限立即失效。
- 查找当前初始账号与密码:在服务器运行 `sudo nano /opt/moyi/releases/20260911-151010-8cd7e410/infra/moyi/.env.cloud`,仅查看 `ADMIN_ACCOUNT`、`ADMIN_PASSWORD` 后退出,不要把文件或密码发送到聊天。升级后使用实际版本目录。
- `ADMIN_PASSWORD` 只在首次建号时使用,后续修改它不会重置数据库里的密码。本版本未提供自助密码找回;不要重新运行 `init`、删除用户或更换 Pepper 来恢复登录。
## 4. 环境变量怎么填 ## 4. 环境变量怎么填
| 分类 | 变量 | 本次要求 | | 分类 | 变量 | 本次要求 |
@@ -254,6 +263,17 @@ sudo python3 deploy.py reload-tls --mode https
执行新版本 `check`、备份 RDS 后再 `up`。构建失败时旧容器仍运行;数据库迁移及后端更新后发生的失败不能承诺自动回退。只有确认旧程序与新数据库结构兼容,才能回到旧版本目录用相同项目名启动;不兼容时需从 RDS 备份恢复到另一个测试库并重新验证。禁止用 `docker system prune`、`down -v`、删除旧库等方式“修复”发布失败。 执行新版本 `check`、备份 RDS 后再 `up`。构建失败时旧容器仍运行;数据库迁移及后端更新后发生的失败不能承诺自动回退。只有确认旧程序与新数据库结构兼容,才能回到旧版本目录用相同项目名启动;不兼容时需从 RDS 备份恢复到另一个测试库并重新验证。禁止用 `docker system prune`、`down -v`、删除旧库等方式“修复”发布失败。
### 从 20260911 版本升级角色功能
1. 先为 `moyi_control` 确认可恢复备份。该库与其他业务库共用 RDS,回退不能恢复整个共享实例覆盖其他系统。
2. 校验新压缩包 SHA256,解压到新的版本目录;在新目录运行 `python3 deploy.py verify`。
3. 将旧版本的 `.env.cloud` 和 `certs/fullchain.pem`、`certs/privkey.pem` 安全复制到新目录。保留原文件,配置和私钥权限为 `600`、证书目录为 `700`;不要重新运行 `init`。
4. 只把新目录 `.env.cloud` 的 `MOYI_IMAGE_TAG` 改为新发布清单中的 `release` 值。保留 `ADMIN_ACCOUNT`、所有密码、Pepper、加密密钥、Compose 项目名、已验证的镜像源和网络配置。
5. 在新目录执行 `python3 deploy.py check --mode https --network`,核对目标确实是 `moyi_control` 后执行 `python3 deploy.py up --mode https --accept-migrations`。
6. 执行 `python3 deploy.py smoke --mode https --login`;新版会检查初始账号的角色确实是超级管理员,再验证管理接口。浏览器刷新后使用原账号、原密码登录。
V9 迁移扩展角色约束、增加超级管理员唯一索引,应用启动时升级指定账号。旧程序只识别 `admin`,**V9 启用后不能直接切回旧版 JAR**;需要兼容新版角色的修复版本,或由维护人员将升级前备份恢复到独立测试库后验证回退。不要手工修改 Flyway 历史或删除唯一索引。
## 8. 还需提供的信息 ## 8. 还需提供的信息
- RDS 内网地址、端口、新库和账号名、所属 VPC;Tair 内网地址、端口、账号、TLS 状态及 VPC。 - RDS 内网地址、端口、新库和账号名、所属 VPC;Tair 内网地址、端口、账号、TLS 状态及 VPC。
+4 -3
View File
@@ -207,10 +207,11 @@ def smoke(config, mode, login=False):
if login: if login:
api = config["services"]["moyi-api"]["environment"] api = config["services"]["moyi-api"]["environment"]
request("/api/auth/login", payload={"account": api["ADMIN_ACCOUNT"], "password": api["ADMIN_PASSWORD"]}) request("/api/auth/login", payload={"account": api["ADMIN_ACCOUNT"], "password": api["ADMIN_PASSWORD"]})
if json.loads(request("/api/auth/me"))["user"]["role"] != "admin": if json.loads(request("/api/auth/me"))["user"]["role"] != "super_admin":
fail("Admin login/cookie verification failed.") fail("Super administrator login/cookie verification failed.")
request("/api/admin/users")
request("/api/auth/logout", 204, {}) request("/api/auth/logout", 204, {})
print("Initial admin login + session cookie OK. Audit records were created.") print("Initial super administrator login + session cookie OK. Audit records were created.")
print("Frontend, backend, authentication boundary and management endpoint checks passed.") print("Frontend, backend, authentication boundary and management endpoint checks passed.")
+35
View File
@@ -4,6 +4,7 @@ import shutil
import subprocess import subprocess
from pathlib import Path from pathlib import Path
import tempfile import tempfile
from types import SimpleNamespace
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
@@ -36,6 +37,40 @@ def configuration():
class DeploymentTests(unittest.TestCase): class DeploymentTests(unittest.TestCase):
def test_login_smoke_requires_super_admin_and_checks_management(self):
cfg = configuration()
cfg["services"]["moyi-api"]["environment"]["ADMIN_ACCOUNT"] = "adimin"
for role in ("super_admin", "admin", "user"):
paths = []
def response(request, timeout):
path = deploy.urllib.parse.urlsplit(request.full_url).path
paths.append(path)
if path == "/":
code, body = 200, b"<html></html>"
elif path == "/health":
code, body = 200, b'{"status":"ok"}'
elif path == "/api/auth/me" and paths.count(path) == 2:
code, body = 200, json.dumps({"user": {"role": role}}).encode()
elif path in ("/api/auth/me", "/v1/models"):
code, body = 401, b"{}"
elif path == "/actuator/health":
code, body = 404, b"{}"
elif path == "/api/auth/logout":
code, body = 204, b""
else:
code, body = 200, b"{}"
return SimpleNamespace(code=code, read=lambda: body)
with self.subTest(role=role), patch.object(deploy.urllib.request, "build_opener", return_value=SimpleNamespace(open=response)):
if role == "super_admin":
deploy.smoke(cfg, "tunnel", True)
self.assertIn("/api/admin/users", paths)
self.assertEqual(paths[-1], "/api/auth/logout")
else:
with self.assertRaisesRegex(ValueError, "Super administrator"):
deploy.smoke(cfg, "tunnel", True)
def test_tunnel_config(self): def test_tunnel_config(self):
deploy.validate_config(configuration(), "tunnel") deploy.validate_config(configuration(), "tunnel")
+4 -4
View File
@@ -54,7 +54,7 @@ function navigate(view: string) {
} }
function switchPortal() { function switchPortal() {
if (authUser.value?.role !== 'admin') { if (!['admin', 'super_admin'].includes(authUser.value?.role || '')) {
notify('当前账号没有管理端权限') notify('当前账号没有管理端权限')
return return
} }
@@ -154,10 +154,10 @@ function openAccountSettings() {
</div> </div>
<div class="topbar-actions"> <div class="topbar-actions">
<button class="global-search desktop-only" @click="notify('全局搜索将在接入真实数据后开放')"><Search :size="16" /><span>搜索模型、用户或任务</span><kbd>⌘ K</kbd></button> <button class="global-search desktop-only" @click="notify('全局搜索将在接入真实数据后开放')"><Search :size="16" /><span>搜索模型、用户或任务</span><kbd>⌘ K</kbd></button>
<button v-if="authUser?.role === 'admin'" class="portal-switch" @click="switchPortal"><ArrowLeftRight :size="16" /><span>{{ portal === 'admin' ? '返回用户端' : '进入管理端' }}</span></button> <button v-if="['admin', 'super_admin'].includes(authUser?.role || '')" class="portal-switch" @click="switchPortal"><ArrowLeftRight :size="16" /><span>{{ portal === 'admin' ? '返回用户端' : '进入管理端' }}</span></button>
<button class="icon-button desktop-only" aria-label="通知" @click="notify('当前没有新的通知')"><Bell :size="18" /></button> <button class="icon-button desktop-only" aria-label="通知" @click="notify('当前没有新的通知')"><Bell :size="18" /></button>
<div class="account-menu-wrap"> <div class="account-menu-wrap">
<button class="user-menu" :class="{ active: accountMenuOpen }" @click="accountMenuOpen = !accountMenuOpen"><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>{{ authUser?.role === 'admin' ? '平台管理员' : '普通用户' }}</small></div></button> <button class="user-menu" :class="{ active: accountMenuOpen }" @click="accountMenuOpen = !accountMenuOpen"><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>{{ authUser?.role === 'super_admin' ? '超级管理员' : authUser?.role === 'admin' ? '平台管理员' : '普通用户' }}</small></div></button>
<Transition name="menu-pop"><div v-if="accountMenuOpen" class="account-popover"><header><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>{{ authUser?.account }}</small></div></header><button @click="openAccountSettings"><Settings :size="16" />账号设置</button><button class="logout-button" @click="logout"><LogOut :size="16" />退出登录</button></div></Transition> <Transition name="menu-pop"><div v-if="accountMenuOpen" class="account-popover"><header><span>{{ userName.slice(0, 1) }}</span><div><strong>{{ userName }}</strong><small>{{ authUser?.account }}</small></div></header><button @click="openAccountSettings"><Settings :size="16" />账号设置</button><button class="logout-button" @click="logout"><LogOut :size="16" />退出登录</button></div></Transition>
</div> </div>
</div> </div>
@@ -165,7 +165,7 @@ function openAccountSettings() {
<main class="content"> <main class="content">
<UserConsole v-if="portal === 'user'" :view="activeView" :display-name="userName" @navigate="navigate" @notify="notify" /> <UserConsole v-if="portal === 'user'" :view="activeView" :display-name="userName" @navigate="navigate" @notify="notify" />
<AdminConsole v-else :view="activeView" @navigate="navigate" @notify="notify" /> <AdminConsole v-else :view="activeView" :current-user="authUser" @navigate="navigate" @notify="notify" />
</main> </main>
</div> </div>
+1 -1
View File
@@ -1,4 +1,4 @@
export type AuthRole = 'user' | 'admin' export type AuthRole = 'user' | 'admin' | 'super_admin'
export interface AuthUser { export interface AuthUser {
id: string id: string
+7 -1
View File
@@ -118,7 +118,7 @@ export interface AdminCatalogUser {
account: string account: string
accountKind: 'email' | 'phone' | 'username' accountKind: 'email' | 'phone' | 'username'
displayName: string displayName: string
role: 'user' | 'admin' role: 'user' | 'admin' | 'super_admin'
status: 'active' | 'disabled' status: 'active' | 'disabled'
createdAt: string createdAt: string
lastLoginAt?: string lastLoginAt?: string
@@ -286,6 +286,12 @@ class HttpCatalogClient {
return this.request<{ users: AdminCatalogUser[] }>('/api/admin/users') return this.request<{ users: AdminCatalogUser[] }>('/api/admin/users')
} }
async changeUserRole(id: string, role: 'user' | 'admin') {
return this.request<{ user: AdminCatalogUser }>(`/api/admin/users/${encodeURIComponent(id)}/role`, {
method: 'POST', body: JSON.stringify({ role }),
})
}
async listAdminAudit(limit = 100) { async listAdminAudit(limit = 100) {
return this.request<{ events: AdminAuditEvent[] }>(`/api/admin/audit?limit=${limit}`) return this.request<{ events: AdminAuditEvent[] }>(`/api/admin/audit?limit=${limit}`)
} }
+2
View File
@@ -161,6 +161,8 @@ td strong{font-size:12px}
.invite-notice small{color:#506f80;font-size:10px} .invite-notice small{color:#506f80;font-size:10px}
.register-channel button,.auth-code-row>button{font-size:11px} .register-channel button,.auth-code-row>button{font-size:11px}
.terms-row em{color:#5f6f83;font-size:10px} .terms-row em{color:#5f6f83;font-size:10px}
.auth-form .terms-row input{position:static;opacity:1;pointer-events:auto;width:16px;height:16px;flex:0 0 16px;margin:0;accent-color:#178ca2}
.auth-form .terms-row input:focus-visible{outline:2px solid #178ca2;outline-offset:2px}
.auth-back,.auth-support,.auth-support button{font-size:11px} .auth-back,.auth-support,.auth-support button{font-size:11px}
.reset-success p{font-size:12px} .reset-success p{font-size:12px}
.sidebar-brand{height:auto;min-height:50px;margin-bottom:24px}.brand-name strong{font-size:14px}.navigation{min-height:0} .sidebar-brand{height:auto;min-height:50px;margin-bottom:24px}.brand-name strong{font-size:14px}.navigation{min-height:0}
+2
View File
@@ -1,4 +1,5 @@
import type { Component } from 'vue' import type { Component } from 'vue'
import type { AuthRole } from './services/auth'
export type Portal = 'user' | 'admin' export type Portal = 'user' | 'admin'
export type ModelType = '文本' | '多模态' | '图像' | '3D' | '视频' | '音频' export type ModelType = '文本' | '多模态' | '图像' | '3D' | '视频' | '音频'
@@ -72,6 +73,7 @@ export interface AdminUser {
name: string name: string
email: string email: string
role: string role: string
roleCode: AuthRole
balance?: number balance?: number
usage?: string usage?: string
lastActive?: string lastActive?: string
+47 -4
View File
@@ -34,10 +34,11 @@ import {
import type { AdminUser, ModelItem, ProviderItem, RouteItem } from '../types' import type { AdminUser, ModelItem, ProviderItem, RouteItem } from '../types'
import { catalogClient, type AdminAuditEvent, type CatalogModel, type CatalogProvider, type UsageAuditRecord } from '../services/catalog' import { catalogClient, type AdminAuditEvent, type CatalogModel, type CatalogProvider, type UsageAuditRecord } from '../services/catalog'
import { copyText } from '../services/clipboard' import { copyText } from '../services/clipboard'
import type { AuthUser } from '../services/auth'
import SlidePanel from '../components/SlidePanel.vue' import SlidePanel from '../components/SlidePanel.vue'
import UiModal from '../components/UiModal.vue' import UiModal from '../components/UiModal.vue'
defineProps<{ view: string }>() const props = defineProps<{ view: string; currentUser?: AuthUser }>()
const emit = defineEmits<{ navigate: [view: string]; notify: [message: string] }>() const emit = defineEmits<{ navigate: [view: string]; notify: [message: string] }>()
const users = ref<AdminUser[]>([]) const users = ref<AdminUser[]>([])
@@ -48,6 +49,10 @@ const catalogConnected = ref(false)
const userQuery = ref('') const userQuery = ref('')
const userStatus = ref('全部') const userStatus = ref('全部')
const selectedUser = ref<AdminUser | null>(null) const selectedUser = ref<AdminUser | null>(null)
const roleTarget = ref<AdminUser | null>(null)
const roleChoice = ref<'user' | 'admin'>('user')
const savingRole = ref(false)
const canEditRole = computed(() => props.currentUser?.role === 'super_admin' && selectedUser.value?.roleCode !== 'super_admin' && selectedUser.value?.id !== props.currentUser.id)
const invitationOpen = ref(false) const invitationOpen = ref(false)
const inviteLabel = ref('') const inviteLabel = ref('')
const createdInviteCode = ref('') const createdInviteCode = ref('')
@@ -212,8 +217,32 @@ async function copyUserId(id: string) {
emit('notify', result === 'failed' ? '用户 ID 复制失败,请手动复制' : result === 'verified' ? '用户 ID 已复制并校验' : '用户 ID 已写入剪贴板') emit('notify', result === 'failed' ? '用户 ID 复制失败,请手动复制' : result === 'verified' ? '用户 ID 已复制并校验' : '用户 ID 已写入剪贴板')
} }
function mapUser(user: { id: string; account: string; displayName: string; role: 'user' | 'admin'; status: 'active' | 'disabled'; lastLoginAt?: string }): AdminUser { function mapUser(user: { id: string; account: string; displayName: string; role: 'user' | 'admin' | 'super_admin'; status: 'active' | 'disabled'; lastLoginAt?: string }): AdminUser {
return { id: user.id, name: user.displayName, email: user.account, role: user.role === 'admin' ? '平台管理员' : '普通用户', status: user.status === 'active' ? '正常' : '已停用' } return { id: user.id, name: user.displayName, email: user.account, role: user.role === 'super_admin' ? '超级管理员' : user.role === 'admin' ? '平台管理员' : '普通用户', roleCode: user.role, status: user.status === 'active' ? '正常' : '已停用' }
}
function openRoleEditor() {
if (!selectedUser.value || !canEditRole.value) return
roleTarget.value = selectedUser.value
roleChoice.value = selectedUser.value.roleCode === 'admin' ? 'admin' : 'user'
selectedUser.value = null
}
async function saveRole() {
if (!roleTarget.value || savingRole.value) return
savingRole.value = true
try {
const result = await catalogClient.changeUserRole(roleTarget.value.id, roleChoice.value)
const updated = mapUser(result.user)
users.value = users.value.map((user) => user.id === updated.id ? updated : user)
roleTarget.value = null
selectedUser.value = updated
emit('notify', '用户角色已更新')
} catch (error) {
emit('notify', error instanceof Error ? error.message : '角色更新失败')
} finally {
savingRole.value = false
}
} }
function mapAudit(event: AdminAuditEvent) { function mapAudit(event: AdminAuditEvent) {
@@ -397,7 +426,21 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
<section class="settings-grid"><article class="panel settings-card"><header class="panel-header"><div><span>ACCESS CONTROL</span><h3>用户注册策略</h3></div><KeyRound :size="18" /></header><p>第一版通过邀请码控制用户规模,手机号和邮箱公开注册保留开关。</p><div class="setting-list"><div><span><strong>邀请码注册</strong><small>策略接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.inviteOnly }"><span></span></button></div><div><span><strong>邮箱公开注册</strong><small>验证码服务尚未接入</small></span><button class="switch" disabled :class="{ active: settings.emailSignup }"><span></span></button></div><div><span><strong>手机号公开注册</strong><small>短信服务尚未接入</small></span><button class="switch" disabled :class="{ active: settings.phoneSignup }"><span></span></button></div></div></article><article class="panel settings-card"><header class="panel-header"><div><span>OPERATIONS</span><h3>内测运营策略</h3></div><Settings2 :size="18" /></header><p>配置新用户额度、维护公告和操作审计。</p><div class="setting-list"><div><span><strong>新用户自动发放额度</strong><small>额度账本接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.automaticCredit }"><span></span></button></div><div><span><strong>显示维护公告</strong><small>公告配置接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.maintenanceNotice }"><span></span></button></div><div><span><strong>保留操作审计</strong><small>当前仅展示认证服务审计</small></span><button class="switch" disabled :class="{ active: settings.auditRetention }"><span></span></button></div></div></article></section> <section class="settings-grid"><article class="panel settings-card"><header class="panel-header"><div><span>ACCESS CONTROL</span><h3>用户注册策略</h3></div><KeyRound :size="18" /></header><p>第一版通过邀请码控制用户规模,手机号和邮箱公开注册保留开关。</p><div class="setting-list"><div><span><strong>邀请码注册</strong><small>策略接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.inviteOnly }"><span></span></button></div><div><span><strong>邮箱公开注册</strong><small>验证码服务尚未接入</small></span><button class="switch" disabled :class="{ active: settings.emailSignup }"><span></span></button></div><div><span><strong>手机号公开注册</strong><small>短信服务尚未接入</small></span><button class="switch" disabled :class="{ active: settings.phoneSignup }"><span></span></button></div></div></article><article class="panel settings-card"><header class="panel-header"><div><span>OPERATIONS</span><h3>内测运营策略</h3></div><Settings2 :size="18" /></header><p>配置新用户额度、维护公告和操作审计。</p><div class="setting-list"><div><span><strong>新用户自动发放额度</strong><small>额度账本接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.automaticCredit }"><span></span></button></div><div><span><strong>显示维护公告</strong><small>公告配置接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.maintenanceNotice }"><span></span></button></div><div><span><strong>保留操作审计</strong><small>当前仅展示认证服务审计</small></span><button class="switch" disabled :class="{ active: settings.auditRetention }"><span></span></button></div></div></article></section>
</template> </template>
<SlidePanel v-if="selectedUser" :title="selectedUser.name" eyebrow="USER DETAILS" @close="selectedUser = null"><div class="user-profile"><span class="avatar-large">{{ selectedUser.name.slice(0, 1) }}</span><div><strong>{{ selectedUser.email }}</strong><small>{{ selectedUser.role }} · {{ selectedUser.status }}</small></div></div><dl class="detail-list"><div><dt>用户 ID</dt><dd><code>{{ selectedUser.id }}</code><button class="icon-button" title="复制用户 ID" @click="copyUserId(selectedUser.id)"><Copy :size="14" /></button></dd></div><div><dt>额度余额</dt><dd>{{ selectedUser.balance === undefined ? '--(账本未接入)' : `¥ ${selectedUser.balance.toFixed(2)}` }}</dd></div><div><dt>累计用量</dt><dd>{{ selectedUser.usage || '--(用量统计未接入)' }}</dd></div><div><dt>最近活跃</dt><dd>{{ selectedUser.lastActive || '--' }}</dd></div></dl><template #footer><button class="button primary full" @click="openCredit(selectedUser)"><CircleDollarSign :size="16" />发放额度</button><button class="button secondary full" @click="emit('notify', '用户状态接口尚未接入,当前不会修改状态')"><ShieldCheck :size="16" />{{ selectedUser.status === '已停用' ? '重新启用' : '停用用户' }}</button></template></SlidePanel> <SlidePanel v-if="selectedUser" :title="selectedUser.name" eyebrow="USER DETAILS" @close="selectedUser = null">
<div class="user-profile"><span class="avatar-large">{{ selectedUser.name.slice(0, 1) }}</span><div><strong>{{ selectedUser.email }}</strong><small>{{ selectedUser.role }} · {{ selectedUser.status }}</small></div></div>
<dl class="detail-list"><div><dt>用户 ID</dt><dd><code>{{ selectedUser.id }}</code><button class="icon-button" title="复制用户 ID" @click="copyUserId(selectedUser.id)"><Copy :size="14" /></button></dd></div><div><dt>额度余额</dt><dd>{{ selectedUser.balance === undefined ? '--(账本未接入)' : `¥ ${selectedUser.balance.toFixed(2)}` }}</dd></div><div><dt>累计用量</dt><dd>{{ selectedUser.usage || '--(用量统计未接入)' }}</dd></div><div><dt>最近活跃</dt><dd>{{ selectedUser.lastActive || '--' }}</dd></div></dl>
<template #footer>
<button v-if="canEditRole" class="button secondary full" @click="openRoleEditor"><ShieldCheck :size="16" />调整角色</button>
<button v-if="selectedUser.roleCode !== 'super_admin'" class="button primary full" @click="openCredit(selectedUser)"><CircleDollarSign :size="16" />发放额度</button>
<button v-if="selectedUser.roleCode === 'user'" class="button secondary full" @click="emit('notify', '用户状态接口尚未接入,当前不会修改状态')"><ShieldCheck :size="16" />{{ selectedUser.status === '已停用' ? '重新启用' : '停用用户' }}</button>
</template>
</SlidePanel>
<UiModal v-if="roleTarget" title="调整用户角色" @close="!savingRole && (roleTarget = null)">
<p>{{ roleTarget.email }}</p>
<label class="form-label" for="user-role">角色</label>
<select id="user-role" v-model="roleChoice" class="text-input" :disabled="savingRole"><option value="user">普通用户</option><option value="admin">平台管理员</option></select>
<template #footer><button class="button secondary" :disabled="savingRole" @click="roleTarget = null">取消</button><button class="button primary" :disabled="savingRole || roleChoice === roleTarget.roleCode" @click="saveRole"><Check :size="16" />{{ savingRole ? '保存中…' : '保存角色' }}</button></template>
</UiModal>
<SlidePanel v-if="selectedUsage" :title="selectedUsage.modelName || selectedUsage.modelId || '调用记录详情'" eyebrow="REQUEST TRACE" @close="selectedUsage = null"><dl class="detail-list usage-detail-list"><div><dt>记录 ID</dt><dd><code>{{ selectedUsage.id }}</code></dd></div><div><dt>请求时间</dt><dd>{{ new Date(selectedUsage.createdAt).toLocaleString('zh-CN') }}</dd></div><div><dt>用户 / Key</dt><dd>{{ selectedUsage.userName || selectedUsage.userAccount || '--' }} / {{ selectedUsage.keyName || selectedUsage.keyPrefix || '--' }}</dd></div><div><dt>模型 / 供应商</dt><dd>{{ selectedUsage.modelName || selectedUsage.modelId }} / {{ selectedUsage.providerName || selectedUsage.providerId || '--' }}</dd></div><div><dt>状态与耗时</dt><dd>{{ selectedUsage.status }} · {{ selectedUsage.latencyMs ?? '--' }} ms</dd></div><div><dt>输入 / 输出单位</dt><dd>{{ selectedUsage.inputUnits ?? 0 }} / {{ selectedUsage.outputUnits ?? 0 }}</dd></div></dl><label class="form-label">输入数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.input) }}</pre><label class="form-label">输出数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.output) }}</pre><div v-if="selectedUsage.errorMessage" class="notice warning-notice"><AlertTriangle :size="16" /><span>{{ selectedUsage.errorCode }} · {{ selectedUsage.errorMessage }}</span></div><label class="form-label">管理员备注</label><textarea v-model="usageNote" class="text-input modal-textarea" placeholder="记录排查结论或运营备注"></textarea><template #footer><button class="button secondary" @click="saveUsageNote"><Check :size="16" />保存备注</button><button class="button danger" @click="deleteUsage(selectedUsage.id)"><Trash2 :size="16" />删除记录</button><button class="button primary" @click="selectedUsage = null">关闭</button></template></SlidePanel> <SlidePanel v-if="selectedUsage" :title="selectedUsage.modelName || selectedUsage.modelId || '调用记录详情'" eyebrow="REQUEST TRACE" @close="selectedUsage = null"><dl class="detail-list usage-detail-list"><div><dt>记录 ID</dt><dd><code>{{ selectedUsage.id }}</code></dd></div><div><dt>请求时间</dt><dd>{{ new Date(selectedUsage.createdAt).toLocaleString('zh-CN') }}</dd></div><div><dt>用户 / Key</dt><dd>{{ selectedUsage.userName || selectedUsage.userAccount || '--' }} / {{ selectedUsage.keyName || selectedUsage.keyPrefix || '--' }}</dd></div><div><dt>模型 / 供应商</dt><dd>{{ selectedUsage.modelName || selectedUsage.modelId }} / {{ selectedUsage.providerName || selectedUsage.providerId || '--' }}</dd></div><div><dt>状态与耗时</dt><dd>{{ selectedUsage.status }} · {{ selectedUsage.latencyMs ?? '--' }} ms</dd></div><div><dt>输入 / 输出单位</dt><dd>{{ selectedUsage.inputUnits ?? 0 }} / {{ selectedUsage.outputUnits ?? 0 }}</dd></div></dl><label class="form-label">输入数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.input) }}</pre><label class="form-label">输出数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.output) }}</pre><div v-if="selectedUsage.errorMessage" class="notice warning-notice"><AlertTriangle :size="16" /><span>{{ selectedUsage.errorCode }} · {{ selectedUsage.errorMessage }}</span></div><label class="form-label">管理员备注</label><textarea v-model="usageNote" class="text-input modal-textarea" placeholder="记录排查结论或运营备注"></textarea><template #footer><button class="button secondary" @click="saveUsageNote"><Check :size="16" />保存备注</button><button class="button danger" @click="deleteUsage(selectedUsage.id)"><Trash2 :size="16" />删除记录</button><button class="button primary" @click="selectedUsage = null">关闭</button></template></SlidePanel>
<UiModal v-if="usageDeleteTarget" title="删除调用记录" eyebrow="DELETE REQUEST TRACE" @close="usageDeleteTarget = null"><p class="modal-description">删除后该记录不会再出现在查询和导出结果中,原始数据库记录会保留删除标记。</p><template #footer><button class="button secondary" @click="usageDeleteTarget = null">取消</button><button class="button danger" @click="deleteUsage(usageDeleteTarget); usageDeleteTarget = null">确认删除</button></template></UiModal> <UiModal v-if="usageDeleteTarget" title="删除调用记录" eyebrow="DELETE REQUEST TRACE" @close="usageDeleteTarget = null"><p class="modal-description">删除后该记录不会再出现在查询和导出结果中,原始数据库记录会保留删除标记。</p><template #footer><button class="button secondary" @click="usageDeleteTarget = null">取消</button><button class="button danger" @click="deleteUsage(usageDeleteTarget); usageDeleteTarget = null">确认删除</button></template></UiModal>
<UiModal v-if="usageBulkDeleteOpen" title="批量删除调用记录" eyebrow="BULK DELETE REQUESTS" @close="usageBulkDeleteOpen = false"><p class="modal-description">确认删除选中的 {{ usageSelectedIds.length }} 条记录?删除后不会再出现在查询和导出结果中。</p><template #footer><button class="button secondary" @click="usageBulkDeleteOpen = false">取消</button><button class="button danger" @click="usageBulkDeleteOpen = false; deleteSelectedUsage()">确认删除</button></template></UiModal> <UiModal v-if="usageBulkDeleteOpen" title="批量删除调用记录" eyebrow="BULK DELETE REQUESTS" @close="usageBulkDeleteOpen = false"><p class="modal-description">确认删除选中的 {{ usageSelectedIds.length }} 条记录?删除后不会再出现在查询和导出结果中。</p><template #footer><button class="button secondary" @click="usageBulkDeleteOpen = false">取消</button><button class="button danger" @click="usageBulkDeleteOpen = false; deleteSelectedUsage()">确认删除</button></template></UiModal>
+3 -5
View File
@@ -4,7 +4,6 @@ import {
ArrowLeft, ArrowLeft,
ArrowRight, ArrowRight,
Box, Box,
Check,
Eye, Eye,
EyeOff, EyeOff,
KeyRound, KeyRound,
@@ -75,8 +74,7 @@ async function submitRegister() {
password: password.value, password: password.value,
}) })
loading.value = false loading.value = false
switchMode('login') emit('success', user)
emit('notify', '注册成功,欢迎 ' + user.displayName + '。请使用新账号登录')
} catch (error) { } catch (error) {
loading.value = false loading.value = false
emit('notify', error instanceof AuthApiError ? error.message : '注册失败,请稍后重试') emit('notify', error instanceof AuthApiError ? error.message : '注册失败,请稍后重试')
@@ -145,7 +143,7 @@ onMounted(async () => {
<form v-if="mode === 'login'" class="auth-form" @submit.prevent="submitLogin"> <form v-if="mode === 'login'" class="auth-form" @submit.prevent="submitLogin">
<label><span>账号</span><div class="auth-input"><Mail :size="17" /><input v-model="account" autocomplete="username" placeholder="请输入用户名、邮箱或手机号" /></div></label> <label><span>账号</span><div class="auth-input"><Mail :size="17" /><input v-model="account" autocomplete="username" placeholder="请输入用户名、邮箱或手机号" /></div></label>
<label><span>登录密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="password" :type="showPassword ? 'text' : 'password'" autocomplete="current-password" placeholder="请输入密码" /><button type="button" aria-label="显示或隐藏密码" @click="showPassword = !showPassword"><EyeOff v-if="showPassword" :size="17" /><Eye v-else :size="17" /></button></div></label> <label><span>登录密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="password" :type="showPassword ? 'text' : 'password'" autocomplete="current-password" placeholder="请输入密码" /><button type="button" aria-label="显示或隐藏密码" @click="showPassword = !showPassword"><EyeOff v-if="showPassword" :size="17" /><Eye v-else :size="17" /></button></div></label>
<div class="auth-form-options login-help"><span>使用管理员分配的账号登录</span><button type="button" @click="switchMode('forgot')">忘记密码?</button></div> <div class="auth-form-options login-help"><span>账号密码登录</span><button type="button" @click="switchMode('forgot')">忘记密码?</button></div>
<button class="auth-submit" type="submit" :disabled="loading"><span v-if="loading" class="spinner"></span><template v-else>进入工作台<ArrowRight :size="17" /></template></button> <button class="auth-submit" type="submit" :disabled="loading"><span v-if="loading" class="spinner"></span><template v-else>进入工作台<ArrowRight :size="17" /></template></button>
</form> </form>
@@ -157,7 +155,7 @@ onMounted(async () => {
<label><span>验证码(公开注册开放后启用)</span><div class="auth-code-row"><div class="auth-input disabled"><ShieldCheck :size="17" /><input disabled placeholder="当前无需填写" /></div><button type="button" disabled @click="sendCode">暂未开放</button></div></label> <label><span>验证码(公开注册开放后启用)</span><div class="auth-code-row"><div class="auth-input disabled"><ShieldCheck :size="17" /><input disabled placeholder="当前无需填写" /></div><button type="button" disabled @click="sendCode">暂未开放</button></div></label>
<label><span>设置密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="password" :type="showPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="至少 8 位字符" /><button type="button" @click="showPassword = !showPassword"><EyeOff v-if="showPassword" :size="17" /><Eye v-else :size="17" /></button></div></label> <label><span>设置密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="password" :type="showPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="至少 8 位字符" /><button type="button" @click="showPassword = !showPassword"><EyeOff v-if="showPassword" :size="17" /><Eye v-else :size="17" /></button></div></label>
<label><span>确认密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="confirmPassword" :type="showConfirmPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="再次输入密码" /><button type="button" @click="showConfirmPassword = !showConfirmPassword"><EyeOff v-if="showConfirmPassword" :size="17" /><Eye v-else :size="17" /></button></div></label> <label><span>确认密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="confirmPassword" :type="showConfirmPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="再次输入密码" /><button type="button" @click="showConfirmPassword = !showConfirmPassword"><EyeOff v-if="showConfirmPassword" :size="17" /><Eye v-else :size="17" /></button></div></label>
<label class="check-row terms-row"><input v-model="agreeTerms" type="checkbox" /><span><Check :size="11" /></span><em>我已阅读并同意<a href="#" @click.prevent="emit('notify', '服务协议将在正式上线前补充')">《服务协议》</a>与<a href="#" @click.prevent="emit('notify', '隐私政策将在正式上线前补充')">《隐私政策》</a></em></label> <label class="check-row terms-row"><input v-model="agreeTerms" type="checkbox" /><em>我已阅读并同意<a href="#" @click.prevent="emit('notify', '服务协议将在正式上线前补充')">《服务协议》</a>与<a href="#" @click.prevent="emit('notify', '隐私政策将在正式上线前补充')">《隐私政策》</a></em></label>
<button class="auth-submit" type="submit" :disabled="loading"><span v-if="loading" class="spinner"></span><template v-else>创建账户<ArrowRight :size="17" /></template></button> <button class="auth-submit" type="submit" :disabled="loading"><span v-if="loading" class="spinner"></span><template v-else>创建账户<ArrowRight :size="17" /></template></button>
</form> </form>
</template> </template>