fix admin invitations api url and account settings

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

No files matched your search

@@ -16,6 +16,7 @@ import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@@ -59,6 +60,7 @@ public class AuthController {
public record RoleRequest(String role) {}
public record CreateUserRequest(String account, String password, String displayName) {}
public record AccountSettingsRequest(String displayName, String currentPassword, String newPassword) {}
@PostMapping("/admin/users")
public ResponseEntity<Map<String,Object>> createUser(@RequestBody CreateUserRequest input, HttpServletRequest request) {
@@ -102,6 +104,13 @@ public class AuthController {
return Map.of("user", authService.requireUser(sessionToken(request)));
}
@PatchMapping("/auth/account")
public Map<String, Object> updateAccount(@RequestBody AccountSettingsRequest input, HttpServletRequest request) {
return Map.of("user", authService.updateAccount(
sessionToken(request), input.displayName(), input.currentPassword(), input.newPassword(), meta(request)
));
}
@GetMapping("/admin/users")
public Map<String, Object> users(HttpServletRequest request) {
return Map.of("users", authService.listUsers(sessionToken(request)));
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.security.SecretCipher;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -18,6 +19,7 @@ import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@@ -31,17 +33,31 @@ public class AuthService {
private final PasswordHasher passwordHasher;
private final ObjectMapper objectMapper;
private final int sessionTtlHours;
private final SecretCipher secretCipher;
/** Kept for isolated unit tests that do not exercise encrypted invitation display. */
public AuthService(
JdbcTemplate jdbc,
PasswordHasher passwordHasher,
ObjectMapper objectMapper,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours
) {
this(jdbc, passwordHasher, objectMapper, sessionTtlHours, null);
}
@Autowired
public AuthService(
JdbcTemplate jdbc,
PasswordHasher passwordHasher,
ObjectMapper objectMapper,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
SecretCipher secretCipher
) {
this.jdbc = jdbc;
this.passwordHasher = passwordHasher;
this.objectMapper = objectMapper;
this.sessionTtlHours = sessionTtlHours;
this.secretCipher = secretCipher;
}
public record UserView(
@@ -209,6 +225,37 @@ public class AuthService {
return toView(findUserById(userId), null);
}
@Transactional
public UserView updateAccount(
String token,
String displayNameInput,
String currentPassword,
String newPassword,
RequestMeta meta
) {
UserRow user = requireUserRow(token);
String displayName = displayNameInput == null ? user.displayName() : displayNameInput.trim();
if (displayName.isBlank() || displayName.length() > 80) {
throw new ApiException("INVALID_NAME", "显示名称不能为空且最多 80 字符", 400);
}
boolean changingPassword = newPassword != null && !newPassword.isBlank();
if (changingPassword) {
if (currentPassword == null || currentPassword.isBlank() || !passwordHasher.matches(currentPassword, user.passwordHash())) {
throw new ApiException("INVALID_CURRENT_PASSWORD", "当前密码错误", 403);
}
if (newPassword.length() > 256 || (!"super_admin".equals(user.role()) && newPassword.length() < 8)) {
throw new ApiException("WEAK_PASSWORD", "普通用户新密码长度为 8 至 256 位", 400);
}
}
if (changingPassword) {
jdbc.update("UPDATE users SET display_name = ?, password_hash = ?, updated_at = ? WHERE id = ?", displayName, passwordHasher.hash(newPassword), now(), user.id());
} else {
jdbc.update("UPDATE users SET display_name = ?, updated_at = ? WHERE id = ?", displayName, now(), user.id());
}
audit("user.account_updated", user.id(), meta, Map.of("passwordChanged", changingPassword));
return toView(findUserById(user.id()), null);
}
private boolean isAdminRole(String role) {
return "admin".equals(role) || "super_admin".equals(role);
}
@@ -267,8 +314,9 @@ public class AuthService {
OffsetDateTime createdAt = now();
int allowedUses = maxUses == null ? 1 : Math.max(1, maxUses);
jdbc.update(
"INSERT INTO invitation_codes (id, code_hash, code_prefix, label, max_uses, used_count, expires_at, created_by, created_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)",
"INSERT INTO invitation_codes (id, code_hash, code_prefix, code_ciphertext, label, max_uses, used_count, expires_at, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?)",
id, hashSecret(code), code.substring(0, Math.min(code.length(), 10)),
secretCipher == null ? null : secretCipher.encrypt(code),
label == null || label.isBlank() ? "内测邀请码" : label.trim(), allowedUses, expiresAt, admin.id(), createdAt
);
audit("invitation.created", admin.id(), meta, Map.of("invitationId", id));
@@ -276,19 +324,20 @@ public class AuthService {
"code", code,
"invitation", invitationView(id, code.substring(0, Math.min(code.length(), 10)),
label == null || label.isBlank() ? "内测邀请码" : label.trim(), allowedUses, 0,
expiresAt, null, admin.id(), createdAt)
expiresAt, null, admin.id(), createdAt, code)
);
}
public List<Map<String, Object>> listInvitations(String token) {
requireAdmin(token);
return jdbc.query(
"SELECT id, code_prefix, label, max_uses, used_count, expires_at, disabled_at, created_by, created_at FROM invitation_codes ORDER BY created_at DESC",
"SELECT id, code_prefix, code_ciphertext, label, max_uses, used_count, expires_at, disabled_at, created_by, created_at FROM invitation_codes ORDER BY created_at DESC",
(resultSet, rowNumber) -> invitationView(
resultSet.getObject("id", UUID.class), resultSet.getString("code_prefix"), resultSet.getString("label"),
resultSet.getInt("max_uses"), resultSet.getInt("used_count"),
resultSet.getObject("expires_at", OffsetDateTime.class), resultSet.getObject("disabled_at", OffsetDateTime.class),
resultSet.getObject("created_by", UUID.class), resultSet.getObject("created_at", OffsetDateTime.class)
resultSet.getObject("created_by", UUID.class), resultSet.getObject("created_at", OffsetDateTime.class),
decryptInvitationCode(resultSet.getString("code_ciphertext"))
)
);
}
@@ -398,11 +447,12 @@ public class AuthService {
private Map<String, Object> invitationView(
UUID id, String prefix, String label, int maxUses, int usedCount, OffsetDateTime expiresAt,
OffsetDateTime disabledAt, UUID createdBy, OffsetDateTime createdAt
OffsetDateTime disabledAt, UUID createdBy, OffsetDateTime createdAt, String code
) {
Map<String, Object> result = new java.util.LinkedHashMap<>();
result.put("id", id);
result.put("codePrefix", prefix);
if (code != null && !code.isBlank()) result.put("code", code);
result.put("label", label);
result.put("maxUses", maxUses);
result.put("usedCount", usedCount);
@@ -413,6 +463,11 @@ public class AuthService {
return result;
}
private String decryptInvitationCode(String ciphertext) {
if (ciphertext == null || ciphertext.isBlank() || secretCipher == null) return null;
return secretCipher.decrypt(ciphertext);
}
private Map<String, Object> readJson(String value) {
try {
return objectMapper.readValue(value, new TypeReference<>() {});