feat: migrate java control plane foundation

This commit is contained in:
wlx committed 2026-09-07 16:54:43 +08:00
1 parent 1615401185
commit 9da175c040
24 files changed
+1555 -12

No files matched your search

@@ -0,0 +1,407 @@
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 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.Map;
import java.util.UUID;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Value;
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;
public AuthService(
JdbcTemplate jdbc,
PasswordHasher passwordHasher,
ObjectMapper objectMapper,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours
) {
this.jdbc = jdbc;
this.passwordHasher = passwordHasher;
this.objectMapper = objectMapper;
this.sessionTtlHours = sessionTtlHours;
}
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.isBlank()) {
throw new ApiException("INVALID_ADMIN_CONFIG", "管理员初始配置无效", 500);
}
if (findUserByAccount(account) != null) {
return;
}
OffsetDateTime now = now();
jdbc.update(
"INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, '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) {
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);
}
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));
}
@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<Map<String, Object>> 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<String, Object> 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 (!"admin".equals(user.role())) {
throw new ApiException("FORBIDDEN", "需要管理员权限", 403);
}
return toView(user, null);
}
public void logout(String token, RequestMeta meta) {
if (token == null || token.isBlank()) {
return;
}
List<Map<String, Object>> 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<String, Object> 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<UserView> 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 Map<String, Object> 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, label, max_uses, used_count, expires_at, created_by, created_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)",
id, hashSecret(code), code.substring(0, Math.min(code.length(), 10)),
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)
);
}
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",
(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)
)
);
}
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<Map<String, Object>> 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<String, Object> 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<String, Object> 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<UserRow> 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<String, Object> invitationView(
UUID id, String prefix, String label, int maxUses, int usedCount, OffsetDateTime expiresAt,
OffsetDateTime disabledAt, UUID createdBy, OffsetDateTime createdAt
) {
Map<String, Object> result = new java.util.LinkedHashMap<>();
result.put("id", id);
result.put("codePrefix", prefix);
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 Map<String, Object> readJson(String value) {
try {
return objectMapper.readValue(value, new TypeReference<>() {});
} catch (JsonProcessingException exception) {
return Map.of();
}
}
private String writeJson(Map<String, Object> 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;
}
}