Files
webup-cloud/backend/src/main/java/run/webup/platform/AdminController.java
T
WebUp Cloud 2f93fb023a
Verify control plane / verify (push) Canceled after 0s
Verify control plane / verify (pull_request) Canceled after 0s
Add administrator-controlled IP project entry redirects
2026-11-08 12:25:01 +08:00

215 lines
7.9 KiB
Java

package run.webup.platform;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.util.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/admin")
public class AdminController {
final IdentityService users;
public AdminController(IdentityService users) {
this.users = users;
}
void audit(UUID actor, String action, String target, String details, String ip) {
users
.db()
.update(
"INSERT INTO admin_operation_logs(id,actor_id,action,target,ip,details) VALUES"
+ " (?,?,?,?,?,?)",
UUID.randomUUID(),
actor,
action,
target,
ip,
details);
}
@GetMapping("/users")
@PreAuthorize("hasAuthority('users:read')")
public Map<String, Object> list(
@RequestParam(defaultValue = "") String search,
@RequestParam(defaultValue = "0") @Min(0) int page) {
if (search.length() > 254 || page < 0 || page > 100000)
throw new ApiError.Failure(400, "筛选参数超出范围");
String pattern = "%" + search.toLowerCase(Locale.ROOT) + "%";
return Map.of(
"items",
users
.db()
.queryForList(
"SELECT id,email,display_name,status,created_at FROM users WHERE LOWER(email) LIKE"
+ " ? OR LOWER(display_name) LIKE ? ORDER BY created_at DESC LIMIT 20 OFFSET ?",
pattern,
pattern,
page * 20),
"total",
users
.db()
.queryForObject(
"SELECT COUNT(*) FROM users WHERE LOWER(email) LIKE ? OR LOWER(display_name) LIKE"
+ " ?",
Long.class,
pattern,
pattern),
"page",
page);
}
public record Status(
@Pattern(regexp = "ACTIVE|DISABLED") @NotNull String status,
@NotBlank @Size(max = 500) String reason) {}
@PutMapping("/users/{id}/status")
@PreAuthorize("hasAuthority('users:write')")
@Transactional
public Map<String, String> status(
@AuthenticationPrincipal SecurityConfig.Identity actor,
@PathVariable UUID id,
@Valid @RequestBody Status v,
HttpServletRequest req) {
if (id.equals(actor.id())) throw new ApiError.Failure(400, "不能停用自己的账户");
var before = users.db().queryForList("SELECT status FROM users WHERE id=? FOR UPDATE", id);
if (before.isEmpty()) throw new ApiError.Failure(404, "用户不存在");
if (users
.db()
.queryForObject(
"SELECT COUNT(*) FROM user_roles WHERE user_id=? AND role_code='SUPER_ADMIN'",
Integer.class,
id)
> 0) throw new ApiError.Failure(400, "超级管理员账户不能通过此接口停用");
users
.db()
.update("UPDATE users SET status=?,updated_at=CURRENT_TIMESTAMP WHERE id=?", v.status, id);
if ("DISABLED".equals(v.status))
users
.db()
.update("UPDATE user_sessions SET revoked_at=CURRENT_TIMESTAMP WHERE user_id=?", id);
audit(
actor.id(),
"USER_STATUS",
id.toString(),
before.getFirst().get("status") + " → " + v.status + "; " + v.reason,
AuthController.ip(req));
return Map.of("message", "账户状态已更新");
}
@DeleteMapping("/users/{id}/sessions")
@PreAuthorize("hasAuthority('users:write')")
@Transactional
public Map<String, String> forceLogout(
@AuthenticationPrincipal SecurityConfig.Identity actor,
@PathVariable UUID id,
HttpServletRequest req) {
users.db().update("UPDATE user_sessions SET revoked_at=CURRENT_TIMESTAMP WHERE user_id=?", id);
audit(actor.id(), "FORCE_LOGOUT", id.toString(), "撤销全部会话", AuthController.ip(req));
return Map.of("message", "全部会话已撤销");
}
@GetMapping("/audit")
@PreAuthorize("hasAuthority('audit:read')")
public List<Map<String, Object>> audit() {
return users
.db()
.queryForList(
"SELECT a.id,u.email AS actor,a.action,a.target,a.ip,a.details,a.created_at FROM"
+ " admin_operation_logs a JOIN users u ON u.id=a.actor_id ORDER BY a.created_at"
+ " DESC LIMIT 100");
}
@GetMapping("/settings")
@PreAuthorize("hasAuthority('settings:write')")
public Map<String, String> settings() {
return readSettings();
}
Map<String, String> readSettings() {
Map<String, String> result = new LinkedHashMap<>();
users
.db()
.query(
"SELECT setting_key,setting_value FROM system_settings ORDER BY setting_key",
rs -> {
result.put(rs.getString(1), rs.getString(2));
});
return result;
}
@PutMapping("/settings")
@PreAuthorize("hasAuthority('settings:write')")
@Transactional
public Map<String, String> save(
@AuthenticationPrincipal SecurityConfig.Identity actor,
@RequestBody Map<String, String> values,
HttpServletRequest req) {
var allowed =
Map.ofEntries(
Map.entry("siteName", 80),
Map.entry("englishName", 80),
Map.entry("siteDescription", 200),
Map.entry("tagline", 120),
Map.entry("heroHeadline", 160),
Map.entry("logoUrl", 1000),
Map.entry("faviconUrl", 1000),
Map.entry("mainDomain", 253),
Map.entry("deploymentDomain", 253),
Map.entry("domainDeliveryTarget", 253),
Map.entry("ipEntryOrigin", 100),
Map.entry("domainTemplate", 300),
Map.entry("filing", 100),
Map.entry("footer", 500),
Map.entry("registrationEnabled", 5),
Map.entry("announcement", 2000),
Map.entry("hostedFooterEnabled", 5),
Map.entry("hostedFooterText", 200),
Map.entry("hostedFooterLink", 1000));
var before = readSettings();
for (var e : values.entrySet()) {
if (!allowed.containsKey(e.getKey())
|| e.getValue() == null
|| e.getValue().length() > allowed.get(e.getKey()))
throw new ApiError.Failure(400, "设置项或长度不合法");
if (e.getKey().equals("hostedFooterLink")
&& !e.getValue().isEmpty()
&& !e.getValue().matches("https://[^\\s]+"))
throw new ApiError.Failure(400, "服务标识链接必须为 HTTPS 地址");
if (e.getKey().equals("siteName") && e.getValue().isBlank())
throw new ApiError.Failure(400, "平台名称不能为空");
if (Set.of("mainDomain", "deploymentDomain", "domainDeliveryTarget").contains(e.getKey())
&& !e.getValue().isBlank()) DomainNames.hostname(e.getValue());
if (Set.of("registrationEnabled", "hostedFooterEnabled").contains(e.getKey())
&& !Set.of("true", "false").contains(e.getValue()))
throw new ApiError.Failure(400, "注册开关无效");
if (Set.of("logoUrl", "faviconUrl").contains(e.getKey())
&& !e.getValue().isEmpty()
&& !e.getValue().matches("https://[^\\s]+|/brand/[A-Za-z0-9_.-]+"))
throw new ApiError.Failure(400, "Logo 需要 HTTPS 地址");
String value =
e.getKey().equals("ipEntryOrigin")
? IpEntryService.validateOrigin(e.getValue())
: e.getValue();
users
.db()
.update(
"UPDATE system_settings SET setting_value=?,updated_at=CURRENT_TIMESTAMP WHERE"
+ " setting_key=?",
value,
e.getKey());
audit(
actor.id(),
"SETTING_UPDATE",
e.getKey(),
"旧值: " + before.get(e.getKey()) + "; 新值: " + value,
AuthController.ip(req));
}
return readSettings();
}
}