package com.moyi.controlplane.auth; 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; import java.sql.ResultSet; import java.sql.SQLException; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.Base64; import java.util.List; import java.util.Locale; 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; import org.springframework.transaction.annotation.Transactional; @Service public class AuthService { private static final Pattern EMAIL = Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$"); private static final Pattern PHONE = Pattern.compile("^\\+?[0-9][0-9\\s-]{6,19}$"); private final JdbcTemplate jdbc; private final PasswordHasher passwordHasher; private final ObjectMapper objectMapper; private final int sessionTtlHours; private final SecretCipher secretCipher; @Autowired private TotpService totp; /** 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( UUID id, String account, String accountKind, String displayName, String role, String status, OffsetDateTime createdAt, OffsetDateTime lastLoginAt ) {} public record AuthResult(String token, UserView user) {} public record RequestMeta(String ipAddress, String userAgent) {} private record UserRow( UUID id, String account, String accountKind, String passwordHash, String displayName, String role, String status, OffsetDateTime createdAt, OffsetDateTime lastLoginAt ) {} @Transactional public void ensureAdmin(String accountInput, String password, String displayName) { String account = normalizeAccount(accountInput); if (account.isBlank() || password == null || password.isBlank()) { throw new ApiException("INVALID_ADMIN_CONFIG", "管理员初始配置无效", 500); } // Serialize bootstrap across replicas, including the first creation. jdbc.execute("LOCK TABLE users IN SHARE ROW EXCLUSIVE MODE"); List 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; } OffsetDateTime now = now(); jdbc.update( "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), displayName == null || displayName.isBlank() ? "超级管理员" : displayName.trim(), now, now ); } public AuthResult login(String accountInput, String password, RequestMeta meta) { return login(accountInput,password,null,meta); } public AuthResult login(String accountInput,String password,String otp,RequestMeta meta) { UserRow user = findUserByAccount(normalizeAccount(accountInput)); if (user == null || !passwordHasher.matches(password, user.passwordHash())) { throw new ApiException("INVALID_CREDENTIALS", "账号或密码错误", 401); } if (!"active".equals(user.status())) { throw new ApiException("ACCOUNT_DISABLED", "账号已停用", 403); } if(totp!=null) totp.verifyLogin(user.id(),otp); OffsetDateTime loginAt = now(); jdbc.update("UPDATE users SET last_login_at = ?, updated_at = ? WHERE id = ?", loginAt, loginAt, user.id()); audit("user.logged_in", user.id(), meta, Map.of()); return new AuthResult(createSession(user.id(), meta), toView(user, loginAt)); } public void verifyPassword(UUID userId,String password) { String hash=jdbc.queryForObject("SELECT password_hash FROM users WHERE id=? AND status='active'",String.class,userId); if(password==null||!passwordHasher.matches(password,hash)) throw new ApiException("INVALID_CREDENTIALS","当前密码错误",401); } @Transactional public AuthResult register( String invitationCode, String accountInput, String password, String displayName, RequestMeta meta ) { String account = normalizeAccount(accountInput); validatePublicAccount(account); if (password == null || password.length() < 8) { throw new ApiException("WEAK_PASSWORD", "密码至少需要 8 位"); } if (invitationCode == null || invitationCode.isBlank()) { throw new ApiException("INVITATION_REQUIRED", "第一版注册需要邀请码"); } if (findUserByAccount(account) != null) { throw new ApiException("ACCOUNT_EXISTS", "账号已注册", 409); } List> invitations = jdbc.queryForList( "SELECT id, max_uses, used_count, expires_at, disabled_at FROM invitation_codes WHERE code_hash = ? FOR UPDATE", hashSecret(invitationCode.trim()) ); if (invitations.isEmpty()) { throw new ApiException("INVITATION_INVALID", "邀请码无效或已失效", 403); } Map invitation = invitations.getFirst(); OffsetDateTime now = now(); OffsetDateTime expiresAt = toOffsetDateTime(invitation.get("expires_at")); if (invitation.get("disabled_at") != null || (expiresAt != null && !expiresAt.isAfter(now)) || ((Number) invitation.get("used_count")).intValue() >= ((Number) invitation.get("max_uses")).intValue()) { throw new ApiException("INVITATION_EXHAUSTED", "邀请码无效、已用尽或账号已注册", 403); } UUID userId = UUID.randomUUID(); String name = displayName == null || displayName.isBlank() ? defaultDisplayName(account) : displayName.trim(); jdbc.update( "INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'user', 'active', ?, ?)", userId, account, accountKind(account), passwordHasher.hash(password), name, now, now ); UUID invitationId = (UUID) invitation.get("id"); jdbc.update("UPDATE invitation_codes SET used_count = used_count + 1 WHERE id = ?", invitationId); jdbc.update("INSERT INTO invitation_redemptions (invitation_id, user_id, redeemed_at) VALUES (?, ?, ?)", invitationId, userId, now); UserRow user = findUserById(userId); audit("user.registered", userId, meta, Map.of("invitationId", invitationId)); return new AuthResult(createSession(userId, meta), toView(user, null)); } public UserView requireUser(String token) { return toView(requireUserRow(token), null); } public UserView requireAdmin(String token) { UserRow user = requireUserRow(token); if (!isAdminRole(user.role())) { throw new ApiException("FORBIDDEN", "需要管理员权限", 403); } 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 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); } @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); } @Transactional public void resetPassword(String accountInput, String newPassword, RequestMeta meta) { String account = normalizeAccount(accountInput); UserRow user = findUserByAccount(account); if (user == null || !"active".equals(user.status())) { throw new ApiException("ACCOUNT_NOT_FOUND", "账号不存在或已停用", 404); } if (newPassword == null || newPassword.isBlank() || newPassword.length() > 256 || (!"super_admin".equals(user.role()) && newPassword.length() < 8)) { throw new ApiException("WEAK_PASSWORD", "普通用户新密码长度为 8 至 256 位", 400); } OffsetDateTime changedAt = now(); jdbc.update("UPDATE users SET password_hash=?, updated_at=? WHERE id=?", passwordHasher.hash(newPassword), changedAt, user.id()); jdbc.update("UPDATE auth_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL", changedAt, user.id()); audit("user.password_reset", user.id(), meta, Map.of()); } private boolean isAdminRole(String role) { return "admin".equals(role) || "super_admin".equals(role); } public void logout(String token, RequestMeta meta) { if (token == null || token.isBlank()) { return; } List> sessions = jdbc.queryForList( "SELECT id, user_id FROM auth_sessions WHERE token_hash = ? AND revoked_at IS NULL", hashSecret(token) ); if (sessions.isEmpty()) { return; } Map session = sessions.getFirst(); jdbc.update("UPDATE auth_sessions SET revoked_at = ? WHERE id = ?", now(), session.get("id")); audit("user.logged_out", (UUID) session.get("user_id"), meta, Map.of()); } public List listUsers(String token) { requireAdmin(token); return jdbc.query("SELECT * FROM users ORDER BY created_at DESC", this::mapUser).stream().map(user -> toView(user, null)).toList(); } @Transactional public UserView createUser(String token, String accountInput, String password, String displayName, RequestMeta meta) { UserView actor=requireAdmin(token); String account=normalizeAccount(accountInput); if(account.isBlank() || account.length()>254 || (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches() && !account.matches("[a-z0-9_]{3,64}"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱、手机号或 3 至 64 位字母数字下划线用户名"); if(password==null || password.length()<8 || password.length()>256) throw new ApiException("WEAK_PASSWORD","普通用户密码长度为 8 至 256 位"); if(findUserByAccount(account)!=null) throw new ApiException("ACCOUNT_EXISTS","账号已存在",409); String name=displayName==null || displayName.isBlank()?defaultDisplayName(account):displayName.trim(); if(name.length()>80) throw new ApiException("INVALID_NAME","显示名称最多 80 字符"); UUID id=UUID.randomUUID(); jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,role,status) VALUES (?,?,?,?,?,'user','active')",id,account,accountKind(account),passwordHasher.hash(password),name); authCreatedAudit(actor.id(),id,meta); return toView(findUserById(id),null); } private void authCreatedAudit(UUID actor, UUID user, RequestMeta meta) { audit("user.admin_created",actor,meta,Map.of("targetUserId",user)); } @Transactional public Map createInvitation( String token, String label, Integer maxUses, OffsetDateTime expiresAt, RequestMeta meta ) { UserView admin = requireAdmin(token); String code = "moyi_" + randomToken(12); UUID id = UUID.randomUUID(); OffsetDateTime createdAt = now(); int allowedUses = maxUses == null ? 1 : Math.max(1, maxUses); jdbc.update( "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)); return Map.of( "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, code) ); } public List> listInvitations(String token) { requireAdmin(token); return jdbc.query( "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), decryptInvitationCode(resultSet.getString("code_ciphertext")) ) ); } public void revokeInvitation(String token, UUID invitationId, RequestMeta meta) { UserView admin = requireAdmin(token); int changed = jdbc.update( "UPDATE invitation_codes SET disabled_at = ? WHERE id = ? AND disabled_at IS NULL", now(), invitationId ); if (changed == 0) { throw new ApiException("INVITATION_NOT_FOUND", "邀请码不存在或已停用", 404); } audit("invitation.revoked", admin.id(), meta, Map.of("invitationId", invitationId)); } public List> listAudit(String token, int requestedLimit) { requireAdmin(token); int limit = Math.min(Math.max(requestedLimit, 1), 200); return jdbc.query( "SELECT id, actor_user_id, event_type, target_type, target_id, ip_address, user_agent, details, created_at FROM auth_audit_log ORDER BY created_at DESC LIMIT ?", (resultSet, rowNumber) -> { Map event = new java.util.LinkedHashMap<>(); event.put("id", String.valueOf(resultSet.getLong("id"))); UUID actorUserId = resultSet.getObject("actor_user_id", UUID.class); if (actorUserId != null) event.put("actorUserId", actorUserId); event.put("eventType", resultSet.getString("event_type")); String targetType = resultSet.getString("target_type"); String targetId = resultSet.getString("target_id"); String ipAddress = resultSet.getString("ip_address"); if (targetType != null) event.put("targetType", targetType); if (targetId != null) event.put("targetId", targetId); if (ipAddress != null) event.put("ipAddress", ipAddress); event.put("details", readJson(resultSet.getString("details"))); event.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class)); return event; }, limit ); } public void audit(String eventType, UUID actorUserId, RequestMeta meta, Map details) { jdbc.update( "INSERT INTO auth_audit_log (actor_user_id, event_type, ip_address, user_agent, details) VALUES (?, ?, CAST(? AS inet), ?, CAST(? AS jsonb))", actorUserId, eventType, blankToNull(meta.ipAddress()), blankToNull(meta.userAgent()), writeJson(details) ); } private UserRow requireUserRow(String token) { if (token == null || token.isBlank()) { throw new ApiException("UNAUTHENTICATED", "请先登录", 401); } List users = jdbc.query( "SELECT u.* FROM auth_sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ? AND s.revoked_at IS NULL AND s.expires_at > now() AND u.status = 'active'", this::mapUser, hashSecret(token) ); if (users.isEmpty()) { throw new ApiException("UNAUTHENTICATED", "请先登录", 401); } return users.getFirst(); } private String createSession(UUID userId, RequestMeta meta) { String token = randomToken(32); OffsetDateTime createdAt = now(); jdbc.update( "INSERT INTO auth_sessions (id, token_hash, user_id, expires_at, created_at, last_seen_at, user_agent, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS inet))", UUID.randomUUID(), hashSecret(token), userId, createdAt.plusHours(sessionTtlHours), createdAt, createdAt, blankToNull(meta.userAgent()), blankToNull(meta.ipAddress()) ); return token; } private UserRow findUserByAccount(String account) { try { return jdbc.queryForObject("SELECT * FROM users WHERE account = ?", this::mapUser, account); } catch (EmptyResultDataAccessException exception) { return null; } } private UserRow findUserById(UUID id) { return jdbc.queryForObject("SELECT * FROM users WHERE id = ?", this::mapUser, id); } private UserRow mapUser(ResultSet resultSet, int rowNumber) throws SQLException { return new UserRow( resultSet.getObject("id", UUID.class), resultSet.getString("account"), resultSet.getString("account_kind"), resultSet.getString("password_hash"), resultSet.getString("display_name"), resultSet.getString("role"), resultSet.getString("status"), resultSet.getObject("created_at", OffsetDateTime.class), resultSet.getObject("last_login_at", OffsetDateTime.class) ); } private UserView toView(UserRow user, OffsetDateTime lastLoginOverride) { return new UserView( user.id(), user.account(), user.accountKind(), user.displayName(), user.role(), user.status(), user.createdAt(), lastLoginOverride == null ? user.lastLoginAt() : lastLoginOverride ); } private Map invitationView( UUID id, String prefix, String label, int maxUses, int usedCount, OffsetDateTime expiresAt, OffsetDateTime disabledAt, UUID createdBy, OffsetDateTime createdAt, String code ) { Map 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); if (expiresAt != null) result.put("expiresAt", expiresAt); if (disabledAt != null) result.put("disabledAt", disabledAt); result.put("createdBy", createdBy); result.put("createdAt", createdAt); return result; } private String decryptInvitationCode(String ciphertext) { if (ciphertext == null || ciphertext.isBlank() || secretCipher == null) return null; return secretCipher.decrypt(ciphertext); } private Map readJson(String value) { try { return objectMapper.readValue(value, new TypeReference<>() {}); } catch (JsonProcessingException exception) { return Map.of(); } } private String writeJson(Map value) { try { return objectMapper.writeValueAsString(value); } catch (JsonProcessingException exception) { throw new ApiException("JSON_ENCODING_FAILED", "无法记录审计信息", 500); } } private void validatePublicAccount(String account) { if (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches()) { throw new ApiException("INVALID_ACCOUNT", "请输入有效的邮箱或手机号"); } } private String normalizeAccount(String account) { String normalized = account == null ? "" : account.trim().toLowerCase(); return normalized.contains("@") ? normalized : normalized.replaceAll("[\\s-]", ""); } private String accountKind(String account) { if (account.contains("@")) return "email"; return PHONE.matcher(account).matches() ? "phone" : "username"; } private String defaultDisplayName(String account) { int separator = account.indexOf('@'); return separator > 0 ? account.substring(0, separator) : "MOYI 用户"; } private String randomToken(int byteCount) { byte[] bytes = new byte[byteCount]; new java.security.SecureRandom().nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } public static String hashSecret(String value) { try { return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); } } private OffsetDateTime now() { return OffsetDateTime.now(ZoneOffset.UTC); } private OffsetDateTime toOffsetDateTime(Object value) { return value instanceof OffsetDateTime dateTime ? dateTime : null; } private String blankToNull(String value) { return value == null || value.isBlank() ? null : value; } }