592 lines
28 KiB
Java
592 lines
28 KiB
Java
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;
|
|
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
|
import org.springframework.transaction.support.TransactionTemplate;
|
|
|
|
@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;
|
|
private final LoginAttemptLimiter loginAttempts;
|
|
private final TransactionTemplate loginTransactions;
|
|
// Valid PBKDF2 shape for comparable unknown-account work; this is not a usable user credential.
|
|
private static final String UNKNOWN_PASSWORD_HASH = "pbkdf2$210000$AAECAwQFBgcICQoLDA0ODw$_ZW4zVJDiheXQ51WuP_SSr_f8xjYJXBHvjkzLlPtFHo";
|
|
@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;
|
|
this.loginAttempts = new LoginAttemptLimiter(jdbc);
|
|
this.loginTransactions = jdbc.getDataSource() == null ? null : new TransactionTemplate(new DataSourceTransactionManager(jdbc.getDataSource()));
|
|
}
|
|
|
|
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()) {
|
|
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<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;
|
|
}
|
|
OffsetDateTime now = now();
|
|
PasswordPolicy.validate(password);
|
|
if (java.util.Set.of("admin123", "generate_admin_password", "replace-with-a-strong-initial-password").contains(password.strip().toLowerCase(Locale.ROOT))) {
|
|
throw new ApiException("INVALID_ADMIN_CONFIG", "首次启动必须配置非默认、非示例占位的管理员密码", 500);
|
|
}
|
|
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) {
|
|
String account = normalizeAccount(accountInput);
|
|
if (account.length() > 320 || password == null || password.length() > 4096) throw new ApiException("INVALID_CREDENTIALS", "账号或密码错误", 401);
|
|
loginAttempts.check(account, meta == null ? null : meta.ipAddress());
|
|
// Acquire the row lock only AFTER the independently committed limiter. Do not hold a pool
|
|
// connection while asking REQUIRES_NEW for another connection under concurrent login load.
|
|
if (loginTransactions == null) throw new IllegalStateException("Login requires a transactional data source");
|
|
LoginOutcome outcome = loginTransactions.execute(status -> authenticateLocked(account, password, otp, meta));
|
|
if (outcome.error() != null) throw outcome.error();
|
|
return outcome.result();
|
|
}
|
|
|
|
private record LoginOutcome(AuthResult result, ApiException error) {}
|
|
|
|
private LoginOutcome authenticateLocked(String account, String password, String otp, RequestMeta meta) {
|
|
UserRow user = findUserByAccountLocked(account);
|
|
boolean matches = passwordHasher.matches(password, user == null ? UNKNOWN_PASSWORD_HASH : user.passwordHash());
|
|
if (user == null || !matches) {
|
|
throw new ApiException("INVALID_CREDENTIALS", "账号或密码错误", 401);
|
|
}
|
|
if (!"active".equals(user.status())) {
|
|
throw new ApiException("ACCOUNT_DISABLED", "账号已停用", 403);
|
|
}
|
|
if(totp!=null) {
|
|
try { totp.verifyLogin(user.id(),otp); }
|
|
catch (ApiException exception) { return new LoginOutcome(null, exception); } // Persist MFA failure/replay counters.
|
|
}
|
|
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 LoginOutcome(new AuthResult(createSession(user.id(), meta), toView(user, loginAt)), null);
|
|
}
|
|
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);
|
|
PasswordPolicy.validate(password);
|
|
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();
|
|
if (name.length() > 80) throw new ApiException("INVALID_NAME", "显示名称最多 80 字符", 400);
|
|
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<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);
|
|
}
|
|
|
|
@Transactional
|
|
public UserView updateAccount(
|
|
String token,
|
|
String displayNameInput,
|
|
String currentPassword,
|
|
String newPassword,
|
|
RequestMeta meta
|
|
) {
|
|
UserRow authenticated = requireUserRow(token);
|
|
jdbc.queryForList("SELECT id FROM users WHERE id=? FOR UPDATE", authenticated.id());
|
|
UserRow user = requireUserRow(token); // Recheck after any concurrent password change revoked this session.
|
|
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;
|
|
if (changingPassword) {
|
|
if (currentPassword == null || currentPassword.isBlank() || !passwordHasher.matches(currentPassword, user.passwordHash())) {
|
|
throw new ApiException("INVALID_CURRENT_PASSWORD", "当前密码错误", 403);
|
|
}
|
|
PasswordPolicy.validate(newPassword);
|
|
}
|
|
if (changingPassword) {
|
|
jdbc.update("UPDATE users SET display_name = ?, password_hash = ?, updated_at = ? WHERE id = ?", displayName, passwordHasher.hash(newPassword), now(), user.id());
|
|
jdbc.update("UPDATE auth_sessions SET revoked_at=? WHERE user_id=? AND revoked_at IS NULL", 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 = findUserByAccountLocked(account);
|
|
if (user == null || !"active".equals(user.status())) {
|
|
throw new ApiException("ACCOUNT_NOT_FOUND", "账号不存在或已停用", 404);
|
|
}
|
|
PasswordPolicy.validate(newPassword);
|
|
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<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 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 位字母数字下划线用户名");
|
|
PasswordPolicy.validate(password);
|
|
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<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, 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<Map<String, Object>> 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<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 findUserByAccountLocked(String account) {
|
|
try { return jdbc.queryForObject("SELECT * FROM users WHERE account=? FOR UPDATE", 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, 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);
|
|
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<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 (account.length() > 254 || (!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(Locale.ROOT);
|
|
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;
|
|
}
|
|
}
|