feat(admin): implement P4 management console
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package me.iiv.agent.admin;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import me.iiv.agent.entity.svc.AdminUser;
|
||||
import me.iiv.agent.mapper.svc.AdminUserMapper;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/auth")
|
||||
public class AdminAuthController {
|
||||
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private final AdminUserMapper mapper;
|
||||
private final AdminPasswordHasher hasher;
|
||||
|
||||
public AdminAuthController(AdminUserMapper mapper, AdminPasswordHasher hasher) {
|
||||
this.mapper = mapper;
|
||||
this.hasher = hasher;
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public SessionView login(@RequestBody LoginRequest body, HttpServletRequest request) {
|
||||
if (body == null || body.account() == null || body.password() == null
|
||||
|| body.account().length() > 64 || body.password().length() > 1024) throw unauthorized();
|
||||
AdminUser admin = mapper.selectOne(new LambdaQueryWrapper<AdminUser>()
|
||||
.eq(AdminUser::getAccount, body.account().trim())
|
||||
.eq(AdminUser::getStatus, 1).eq(AdminUser::getSoftDelete, 0));
|
||||
if (admin == null || !hasher.matches(body.password(), admin.getPasswordHash())) throw unauthorized();
|
||||
HttpSession old = request.getSession(false);
|
||||
if (old != null) old.invalidate();
|
||||
HttpSession session = request.getSession(true);
|
||||
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, admin.getId());
|
||||
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_NAME,
|
||||
admin.getName() == null ? admin.getAccount() : admin.getName());
|
||||
String csrf = randomHex(24);
|
||||
session.setAttribute(AdminSessionFilter.CSRF_SESSION_KEY, csrf);
|
||||
return new SessionView(admin.getId(), admin.getAccount(),
|
||||
(String) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_NAME), csrf);
|
||||
}
|
||||
|
||||
@GetMapping("/me")
|
||||
public SessionView me(HttpSession session) {
|
||||
Long id = (Long) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_ID);
|
||||
AdminUser admin = mapper.selectById(id);
|
||||
if (admin == null || admin.getStatus() == null || admin.getStatus() != 1
|
||||
|| admin.getSoftDelete() == null || admin.getSoftDelete() != 0) throw unauthorized();
|
||||
return new SessionView(id, admin.getAccount(),
|
||||
(String) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_NAME),
|
||||
(String) session.getAttribute(AdminSessionFilter.CSRF_SESSION_KEY));
|
||||
}
|
||||
|
||||
@PostMapping("/logout")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void logout(HttpSession session) {
|
||||
session.invalidate();
|
||||
}
|
||||
|
||||
private static ResponseStatusException unauthorized() {
|
||||
return new ResponseStatusException(HttpStatus.UNAUTHORIZED, "账号或密码错误");
|
||||
}
|
||||
|
||||
static String randomHex(int bytes) {
|
||||
byte[] value = new byte[bytes];
|
||||
RANDOM.nextBytes(value);
|
||||
StringBuilder result = new StringBuilder(bytes * 2);
|
||||
for (byte b : value) result.append(String.format("%02x", b));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public record LoginRequest(String account, String password) {}
|
||||
public record SessionView(Long id, String account, String name, String csrfToken) {}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package me.iiv.agent.admin;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import me.iiv.agent.entity.svc.AdminUser;
|
||||
import me.iiv.agent.mapper.svc.AdminUserMapper;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class AdminBootstrap implements ApplicationRunner {
|
||||
|
||||
private final AdminUserMapper mapper;
|
||||
private final AdminPasswordHasher hasher;
|
||||
private final String account;
|
||||
private final String password;
|
||||
private final String name;
|
||||
|
||||
public AdminBootstrap(AdminUserMapper mapper, AdminPasswordHasher hasher,
|
||||
@Value("${app.admin.bootstrap.account:}") String account,
|
||||
@Value("${app.admin.bootstrap.password:}") String password,
|
||||
@Value("${app.admin.bootstrap.name:系统管理员}") String name) {
|
||||
this.mapper = mapper;
|
||||
this.hasher = hasher;
|
||||
this.account = account;
|
||||
this.password = password;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
if (account.isBlank() || password.isBlank()) return;
|
||||
if (account.length() > 64 || password.length() < 12) {
|
||||
throw new IllegalStateException("管理员账号最多 64 字,初始密码至少 12 字");
|
||||
}
|
||||
Long count = mapper.selectCount(new LambdaQueryWrapper<AdminUser>().eq(AdminUser::getSoftDelete, 0));
|
||||
if (count != 0) return;
|
||||
AdminUser admin = new AdminUser();
|
||||
admin.setAccount(account.trim());
|
||||
admin.setPasswordHash(hasher.hash(password));
|
||||
admin.setName(name);
|
||||
admin.setStatus((byte) 1);
|
||||
admin.setSoftDelete((byte) 0);
|
||||
mapper.insert(admin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package me.iiv.agent.admin;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import me.iiv.agent.entity.m0.Agent;
|
||||
import me.iiv.agent.entity.m0.Authority;
|
||||
import me.iiv.agent.entity.m0.User;
|
||||
import me.iiv.agent.entity.svc.AgentApiKey;
|
||||
import me.iiv.agent.entity.svc.AgentScope;
|
||||
import me.iiv.agent.entity.svc.AuditLog;
|
||||
import me.iiv.agent.entity.svc.ScopeTool;
|
||||
import me.iiv.agent.entity.svc.TokenScope;
|
||||
import me.iiv.agent.entity.svc.Tool;
|
||||
import me.iiv.agent.mapper.m0.AgentMapper;
|
||||
import me.iiv.agent.mapper.m0.AuthorityMapper;
|
||||
import me.iiv.agent.mapper.m0.UserMapper;
|
||||
import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
|
||||
import me.iiv.agent.mapper.svc.AgentScopeMapper;
|
||||
import me.iiv.agent.mapper.svc.AuditLogMapper;
|
||||
import me.iiv.agent.mapper.svc.ScopeToolMapper;
|
||||
import me.iiv.agent.mapper.svc.ToolMapper;
|
||||
import me.iiv.agent.mapper.svc.TokenScopeMapper;
|
||||
import me.iiv.agent.permission.PermissionService;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PatchMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
public class AdminConsoleController {
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final AuthorityMapper authorityMapper;
|
||||
private final AgentMapper agentMapper;
|
||||
private final AgentApiKeyMapper tokenMapper;
|
||||
private final AgentScopeMapper scopeMapper;
|
||||
private final ToolMapper toolMapper;
|
||||
private final ScopeToolMapper scopeToolMapper;
|
||||
private final TokenScopeMapper tokenScopeMapper;
|
||||
private final AuditLogMapper auditMapper;
|
||||
private final PermissionService permissionService;
|
||||
private final AdminTokenService tokenService;
|
||||
|
||||
public AdminConsoleController(UserMapper userMapper, AuthorityMapper authorityMapper, AgentMapper agentMapper,
|
||||
AgentApiKeyMapper tokenMapper, AgentScopeMapper scopeMapper, ToolMapper toolMapper,
|
||||
ScopeToolMapper scopeToolMapper, AuditLogMapper auditMapper,
|
||||
TokenScopeMapper tokenScopeMapper, PermissionService permissionService,
|
||||
AdminTokenService tokenService) {
|
||||
this.userMapper = userMapper;
|
||||
this.authorityMapper = authorityMapper;
|
||||
this.agentMapper = agentMapper;
|
||||
this.tokenMapper = tokenMapper;
|
||||
this.scopeMapper = scopeMapper;
|
||||
this.toolMapper = toolMapper;
|
||||
this.scopeToolMapper = scopeToolMapper;
|
||||
this.tokenScopeMapper = tokenScopeMapper;
|
||||
this.auditMapper = auditMapper;
|
||||
this.permissionService = permissionService;
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
@GetMapping("/users")
|
||||
public List<UserView> users(@RequestParam(defaultValue = "") String keyword) {
|
||||
if (keyword.length() > 100) bad("搜索关键词最多 100 字");
|
||||
LambdaQueryWrapper<User> query = new LambdaQueryWrapper<User>().eq(User::getSoftDelete, 0);
|
||||
if (!keyword.isBlank()) query.and(w -> w.like(User::getName, keyword.trim())
|
||||
.or().like(User::getMobile, keyword.trim()));
|
||||
List<User> users = userMapper.selectList(query.orderByDesc(User::getId).last("LIMIT 100"));
|
||||
Set<Long> ids = users.stream().map(User::getId).collect(Collectors.toSet());
|
||||
Map<Long, Long> counts = ids.isEmpty() ? Map.of() : tokenMapper.selectList(
|
||||
new LambdaQueryWrapper<AgentApiKey>().in(AgentApiKey::getUserId, ids)
|
||||
.eq(AgentApiKey::getSoftDelete, 0))
|
||||
.stream().collect(Collectors.groupingBy(AgentApiKey::getUserId, Collectors.counting()));
|
||||
return users.stream().map(user -> new UserView(user.getId(), user.getName(), maskMobile(user.getMobile()),
|
||||
counts.getOrDefault(user.getId(), 0L))).toList();
|
||||
}
|
||||
|
||||
@GetMapping("/users/{id}/permission")
|
||||
public PermissionView permission(@PathVariable Long id) {
|
||||
User user = userMapper.selectById(id);
|
||||
if (user == null || Integer.valueOf(1).equals(user.getSoftDelete())) bad("人员不存在");
|
||||
Authority authority = user.getAuthorityId() == null ? null : authorityMapper.selectById(user.getAuthorityId());
|
||||
Agent agent = user.getAgentId() == null ? null : agentMapper.selectById(user.getAgentId());
|
||||
String range;
|
||||
try {
|
||||
List<Long> ids = permissionService.visibleAgentIds(user);
|
||||
range = ids == null ? "全部数据" : "自己、直属下级及代管代理(" + ids.size() + " 家)";
|
||||
} catch (IllegalStateException e) {
|
||||
range = "权限配置异常:" + e.getMessage();
|
||||
}
|
||||
return new PermissionView(authority == null ? "未配置" : authority.getName(),
|
||||
authority == null ? null : authority.getIsagent(), agent == null ? "未关联" : agent.getName(),
|
||||
user.getEnterpriseType(), range);
|
||||
}
|
||||
|
||||
@GetMapping("/users/{id}/tokens")
|
||||
public List<AdminTokenService.TokenView> tokens(@PathVariable Long id) {
|
||||
return tokenService.list(id);
|
||||
}
|
||||
|
||||
@PostMapping("/users/{id}/tokens")
|
||||
public AdminTokenService.IssuedToken issue(@PathVariable Long id, @RequestBody TokenRequest body,
|
||||
HttpSession session) {
|
||||
if (body == null) bad("请求内容不能为空");
|
||||
return tokenService.issue(id, body.memo(), body.scopeIds(), body.expireTime(), adminId(session));
|
||||
}
|
||||
|
||||
@PutMapping("/tokens/{id}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void updateToken(@PathVariable Long id, @RequestBody TokenRequest body, HttpSession session) {
|
||||
if (body == null) bad("请求内容不能为空");
|
||||
tokenService.update(id, body.memo(), body.scopeIds(), body.expireTime(), adminId(session));
|
||||
}
|
||||
|
||||
@PatchMapping("/tokens/{id}/status")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void tokenStatus(@PathVariable Long id, @RequestBody StatusRequest body, HttpSession session) {
|
||||
if (body == null) bad("请求内容不能为空");
|
||||
tokenService.status(id, body.status(), adminId(session));
|
||||
}
|
||||
|
||||
@DeleteMapping("/tokens/{id}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void deleteToken(@PathVariable Long id, HttpSession session) {
|
||||
tokenService.delete(id, adminId(session));
|
||||
}
|
||||
|
||||
@GetMapping("/tools")
|
||||
public List<ToolView> tools(@RequestParam(defaultValue = "") String category,
|
||||
@RequestParam(defaultValue = "") String kind,
|
||||
@RequestParam(defaultValue = "") String keyword) {
|
||||
LambdaQueryWrapper<Tool> query = new LambdaQueryWrapper<Tool>().eq(Tool::getSoftDelete, 0);
|
||||
if (!category.isBlank()) query.eq(Tool::getCategory, category);
|
||||
if (!kind.isBlank()) query.eq(Tool::getKind, kind);
|
||||
if (!keyword.isBlank()) query.and(w -> w.like(Tool::getName, keyword.trim())
|
||||
.or().like(Tool::getDescription, keyword.trim()));
|
||||
List<Tool> tools = toolMapper.selectList(query.orderByAsc(Tool::getCategory, Tool::getName));
|
||||
Map<Long, AgentScope> scopes = scopeMapper.selectList(new LambdaQueryWrapper<AgentScope>()
|
||||
.eq(AgentScope::getSoftDelete, 0)).stream()
|
||||
.collect(Collectors.toMap(AgentScope::getId, Function.identity()));
|
||||
Map<Long, List<String>> scopeNames = scopeToolMapper.selectList(new LambdaQueryWrapper<ScopeTool>()
|
||||
.eq(ScopeTool::getSoftDelete, 0)).stream()
|
||||
.filter(r -> scopes.containsKey(r.getScopeId()))
|
||||
.collect(Collectors.groupingBy(ScopeTool::getToolId,
|
||||
Collectors.mapping(r -> scopes.get(r.getScopeId()).getName(), Collectors.toList())));
|
||||
return tools.stream().map(tool -> new ToolView(tool.getId(), tool.getName(), tool.getCategory(),
|
||||
tool.getDescription(), tool.getKind(), tool.getStatus(), tool.getModifyTime(),
|
||||
scopeNames.getOrDefault(tool.getId(), List.of()))).toList();
|
||||
}
|
||||
|
||||
@PatchMapping("/tools/{id}/status")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void toolStatus(@PathVariable Long id, @RequestBody StatusRequest body, HttpSession session) {
|
||||
if (body == null) bad("请求内容不能为空");
|
||||
validateStatus(body.status());
|
||||
Tool tool = toolMapper.selectById(id);
|
||||
if (tool == null || !Byte.valueOf((byte) 0).equals(tool.getSoftDelete())) bad("工具不存在");
|
||||
tool.setStatus(body.status());
|
||||
tool.setModifyId(adminId(session));
|
||||
toolMapper.updateById(tool);
|
||||
}
|
||||
|
||||
@GetMapping("/scopes")
|
||||
public List<ScopeView> scopes() {
|
||||
List<AgentScope> scopes = scopeMapper.selectList(new LambdaQueryWrapper<AgentScope>()
|
||||
.eq(AgentScope::getSoftDelete, 0).orderByDesc(AgentScope::getId));
|
||||
Map<Long, Long> counts = scopeToolMapper.selectList(new LambdaQueryWrapper<ScopeTool>()
|
||||
.eq(ScopeTool::getSoftDelete, 0)).stream()
|
||||
.collect(Collectors.groupingBy(ScopeTool::getScopeId, Collectors.counting()));
|
||||
return scopes.stream().map(scope -> new ScopeView(scope.getId(), scope.getName(), scope.getCode(),
|
||||
scope.getMemo(), scope.getStatus(), scope.getModifyTime(), counts.getOrDefault(scope.getId(), 0L))).toList();
|
||||
}
|
||||
|
||||
@PostMapping("/scopes")
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public ScopeView createScope(@RequestBody ScopeRequest body, HttpSession session) {
|
||||
validateScope(body, null);
|
||||
AgentScope scope = new AgentScope();
|
||||
apply(scope, body, adminId(session));
|
||||
scope.setCreateId(adminId(session));
|
||||
scope.setStatus((byte) 1);
|
||||
scope.setSoftDelete((byte) 0);
|
||||
scopeMapper.insert(scope);
|
||||
return new ScopeView(scope.getId(), scope.getName(), scope.getCode(), scope.getMemo(),
|
||||
scope.getStatus(), scope.getModifyTime(), 0);
|
||||
}
|
||||
|
||||
@PutMapping("/scopes/{id}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void updateScope(@PathVariable Long id, @RequestBody ScopeRequest body, HttpSession session) {
|
||||
AgentScope scope = activeScope(id);
|
||||
validateScope(body, id);
|
||||
apply(scope, body, adminId(session));
|
||||
scopeMapper.updateById(scope);
|
||||
}
|
||||
|
||||
@PatchMapping("/scopes/{id}/status")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
public void scopeStatus(@PathVariable Long id, @RequestBody StatusRequest body, HttpSession session) {
|
||||
if (body == null) bad("请求内容不能为空");
|
||||
validateStatus(body.status());
|
||||
AgentScope scope = activeScope(id);
|
||||
scope.setStatus(body.status());
|
||||
scope.setModifyId(adminId(session));
|
||||
scopeMapper.updateById(scope);
|
||||
}
|
||||
|
||||
@DeleteMapping("/scopes/{id}")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public void deleteScope(@PathVariable Long id, HttpSession session) {
|
||||
AgentScope scope = activeScope(id);
|
||||
Long tokenCount = tokenScopeMapper.selectCount(new LambdaQueryWrapper<TokenScope>()
|
||||
.eq(TokenScope::getScopeId, id).eq(TokenScope::getSoftDelete, 0));
|
||||
if (tokenCount != null && tokenCount > 0) {
|
||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "该作用域仍被 Token 使用,请先调整 Token");
|
||||
}
|
||||
scope.setStatus((byte) 0);
|
||||
scope.setSoftDelete((byte) 1);
|
||||
scope.setModifyId(adminId(session));
|
||||
scopeMapper.updateById(scope);
|
||||
for (ScopeTool relation : scopeToolMapper.selectList(new LambdaQueryWrapper<ScopeTool>()
|
||||
.eq(ScopeTool::getScopeId, id).eq(ScopeTool::getSoftDelete, 0))) {
|
||||
relation.setSoftDelete((byte) 1);
|
||||
relation.setModifyId(adminId(session));
|
||||
scopeToolMapper.updateById(relation);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/scopes/{id}/tools")
|
||||
public List<Long> scopeTools(@PathVariable Long id) {
|
||||
activeScope(id);
|
||||
return scopeToolMapper.selectList(new LambdaQueryWrapper<ScopeTool>()
|
||||
.eq(ScopeTool::getScopeId, id).eq(ScopeTool::getSoftDelete, 0))
|
||||
.stream().map(ScopeTool::getToolId).toList();
|
||||
}
|
||||
|
||||
@PutMapping("/scopes/{id}/tools")
|
||||
@ResponseStatus(HttpStatus.NO_CONTENT)
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public void updateScopeTools(@PathVariable Long id, @RequestBody ToolIdsRequest body, HttpSession session) {
|
||||
activeScope(id);
|
||||
if (body == null) bad("请求内容不能为空");
|
||||
List<Long> toolIds = body.toolIds() == null ? List.of() : body.toolIds().stream().distinct().toList();
|
||||
if (!toolIds.isEmpty() && toolMapper.selectList(new LambdaQueryWrapper<Tool>()
|
||||
.in(Tool::getId, toolIds).eq(Tool::getSoftDelete, 0)).size() != toolIds.size()) bad("工具不存在");
|
||||
Long adminId = adminId(session);
|
||||
List<ScopeTool> old = scopeToolMapper.selectList(new LambdaQueryWrapper<ScopeTool>().eq(ScopeTool::getScopeId, id));
|
||||
for (ScopeTool relation : old) {
|
||||
relation.setSoftDelete((byte) 1);
|
||||
relation.setModifyId(adminId);
|
||||
scopeToolMapper.updateById(relation);
|
||||
}
|
||||
for (Long toolId : toolIds) {
|
||||
ScopeTool relation = old.stream().filter(r -> Objects.equals(r.getToolId(), toolId)).findFirst().orElse(null);
|
||||
if (relation == null) {
|
||||
relation = new ScopeTool();
|
||||
relation.setScopeId(id);
|
||||
relation.setToolId(toolId);
|
||||
relation.setCreateId(adminId);
|
||||
}
|
||||
relation.setSoftDelete((byte) 0);
|
||||
relation.setModifyId(adminId);
|
||||
if (relation.getId() == null) scopeToolMapper.insert(relation); else scopeToolMapper.updateById(relation);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/audit")
|
||||
public List<AuditView> audit(@RequestParam(defaultValue = "") String person,
|
||||
@RequestParam(defaultValue = "") String tokenPrefix,
|
||||
@RequestParam(defaultValue = "") String tool,
|
||||
@RequestParam(defaultValue = "") String result,
|
||||
@RequestParam(defaultValue = "") String client,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to) {
|
||||
LambdaQueryWrapper<AuditLog> query = new LambdaQueryWrapper<AuditLog>().eq(AuditLog::getSoftDelete, 0);
|
||||
if (person.length() > 100 || tokenPrefix.length() > 16 || tool.length() > 128) bad("审计筛选条件过长");
|
||||
if (!person.isBlank()) {
|
||||
List<Long> ids = userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getSoftDelete, 0)
|
||||
.and(w -> w.like(User::getName, person.trim()).or().like(User::getMobile, person.trim()))
|
||||
.select(User::getId).last("LIMIT 1000"))
|
||||
.stream().map(User::getId).toList();
|
||||
if (ids.isEmpty()) return List.of();
|
||||
query.in(AuditLog::getUserId, ids);
|
||||
}
|
||||
if (!tokenPrefix.isBlank()) {
|
||||
List<Long> ids = tokenMapper.selectList(new LambdaQueryWrapper<AgentApiKey>()
|
||||
.likeRight(AgentApiKey::getKeyPrefix, tokenPrefix.trim()).select(AgentApiKey::getId)
|
||||
.last("LIMIT 1000"))
|
||||
.stream().map(AgentApiKey::getId).toList();
|
||||
if (ids.isEmpty()) return List.of();
|
||||
query.in(AuditLog::getTokenId, ids);
|
||||
}
|
||||
if (!tool.isBlank()) query.like(AuditLog::getToolName, tool.trim());
|
||||
if (!result.isBlank()) query.eq(AuditLog::getResultStatus, result);
|
||||
if (!client.isBlank()) query.eq(AuditLog::getClientType, client);
|
||||
ZoneId zone = ZoneId.systemDefault();
|
||||
if (from != null) query.ge(AuditLog::getCreateTime, Date.from(from.atStartOfDay(zone).toInstant()));
|
||||
if (to != null) query.lt(AuditLog::getCreateTime, Date.from(to.plusDays(1).atStartOfDay(zone).toInstant()));
|
||||
List<AuditLog> logs = auditMapper.selectList(query.orderByDesc(AuditLog::getCreateTime).last("LIMIT 200"));
|
||||
Set<Long> userIds = logs.stream().map(AuditLog::getUserId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
Set<Long> tokenIds = logs.stream().map(AuditLog::getTokenId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
Map<Long, String> names = userIds.isEmpty() ? Map.of() : userMapper.selectBatchIds(userIds).stream()
|
||||
.collect(Collectors.toMap(User::getId, user -> user.getName() == null ? "未命名" : user.getName()));
|
||||
Map<Long, String> prefixes = tokenIds.isEmpty() ? Map.of() : tokenMapper.selectBatchIds(tokenIds).stream()
|
||||
.collect(Collectors.toMap(AgentApiKey::getId, AgentApiKey::getKeyPrefix));
|
||||
return logs.stream().map(log -> new AuditView(log.getId(), log.getCreateTime(), log.getUserId(),
|
||||
log.getUserId() == null ? "未知用户" : names.getOrDefault(log.getUserId(), "未知用户"),
|
||||
log.getTokenId() == null ? null : prefixes.get(log.getTokenId()), log.getToolName(),
|
||||
log.getParamsDigest(), log.getResultStatus(), log.getResultMessage(), log.getCostMs(),
|
||||
log.getClientIp(), log.getClientType())).toList();
|
||||
}
|
||||
|
||||
private void validateScope(ScopeRequest body, Long currentId) {
|
||||
if (body == null) bad("请求内容不能为空");
|
||||
if (body.name() == null || body.name().isBlank() || body.name().length() > 64) bad("作用域名称不能为空且最多 64 字");
|
||||
if (body.code() == null || !body.code().matches("[a-z][a-z0-9_-]{0,63}")) bad("作用域编码格式无效");
|
||||
if (body.memo() != null && body.memo().length() > 255) bad("作用域备注最多 255 字");
|
||||
AgentScope duplicate = scopeMapper.selectOne(new LambdaQueryWrapper<AgentScope>()
|
||||
.eq(AgentScope::getCode, body.code()).eq(AgentScope::getSoftDelete, 0)
|
||||
.ne(currentId != null, AgentScope::getId, currentId));
|
||||
if (duplicate != null) throw new ResponseStatusException(HttpStatus.CONFLICT, "作用域编码已存在");
|
||||
}
|
||||
|
||||
private static void apply(AgentScope scope, ScopeRequest body, Long adminId) {
|
||||
scope.setName(body.name().trim());
|
||||
scope.setCode(body.code().trim());
|
||||
scope.setMemo(body.memo() == null ? null : body.memo().trim());
|
||||
scope.setModifyId(adminId);
|
||||
}
|
||||
|
||||
private AgentScope activeScope(Long id) {
|
||||
AgentScope scope = scopeMapper.selectById(id);
|
||||
if (scope == null || !Byte.valueOf((byte) 0).equals(scope.getSoftDelete())) bad("作用域不存在");
|
||||
return scope;
|
||||
}
|
||||
|
||||
private static Long adminId(HttpSession session) {
|
||||
return (Long) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_ID);
|
||||
}
|
||||
|
||||
private static void validateStatus(byte status) {
|
||||
if (status != 0 && status != 1) bad("状态无效");
|
||||
}
|
||||
|
||||
private static void bad(String message) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
|
||||
}
|
||||
|
||||
private static String maskMobile(String mobile) {
|
||||
if (mobile == null || mobile.length() < 7) return mobile;
|
||||
return mobile.substring(0, 3) + "****" + mobile.substring(mobile.length() - 4);
|
||||
}
|
||||
|
||||
public record UserView(Long id, String name, String mobile, long tokenCount) {}
|
||||
public record PermissionView(String authorityName, Integer isAgent, String agentName,
|
||||
Integer enterpriseType, String visibleRange) {}
|
||||
public record TokenRequest(String memo, List<Long> scopeIds, Date expireTime) {}
|
||||
public record StatusRequest(byte status) {}
|
||||
public record ToolView(Long id, String name, String category, String description, String kind,
|
||||
Byte status, Date modifyTime, List<String> scopeNames) {}
|
||||
public record ScopeRequest(String name, String code, String memo) {}
|
||||
public record ScopeView(Long id, String name, String code, String memo, Byte status,
|
||||
Date modifyTime, long toolCount) {}
|
||||
public record ToolIdsRequest(List<Long> toolIds) {}
|
||||
public record AuditView(Long id, Date createTime, Long userId, String userName, String tokenPrefix,
|
||||
String toolName, String paramsDigest, String resultStatus, String resultMessage,
|
||||
Long costMs, String clientIp, String clientType) {}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package me.iiv.agent.admin;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.PBEKeySpec;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
@Component
|
||||
public class AdminPasswordHasher {
|
||||
|
||||
private static final int ITERATIONS = 210_000;
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
public String hash(String password) {
|
||||
byte[] salt = new byte[16];
|
||||
RANDOM.nextBytes(salt);
|
||||
return "pbkdf2$" + ITERATIONS + "$" + Base64.getEncoder().encodeToString(salt)
|
||||
+ "$" + Base64.getEncoder().encodeToString(derive(password, salt, ITERATIONS));
|
||||
}
|
||||
|
||||
public boolean matches(String password, String encoded) {
|
||||
if (password == null || encoded == null) return false;
|
||||
try {
|
||||
String[] parts = encoded.split("\\$", -1);
|
||||
if (parts.length != 4 || !"pbkdf2".equals(parts[0])) return false;
|
||||
int iterations = Integer.parseInt(parts[1]);
|
||||
if (iterations < 10_000 || iterations > 1_000_000) return false;
|
||||
byte[] salt = Base64.getDecoder().decode(parts[2]);
|
||||
byte[] expected = Base64.getDecoder().decode(parts[3]);
|
||||
return MessageDigest.isEqual(expected, derive(password, salt, iterations));
|
||||
} catch (RuntimeException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] derive(String password, byte[] salt, int iterations) {
|
||||
try {
|
||||
PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, 256);
|
||||
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("密码哈希失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package me.iiv.agent.admin;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import jakarta.servlet.http.HttpSession;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@Component
|
||||
public class AdminSessionFilter extends OncePerRequestFilter {
|
||||
|
||||
static final String ADMIN_SESSION_ID = "adminUserId";
|
||||
static final String ADMIN_SESSION_NAME = "adminName";
|
||||
static final String CSRF_SESSION_KEY = "adminCsrf";
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !request.getRequestURI().startsWith("/api/admin/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain chain) throws ServletException, IOException {
|
||||
String uri = request.getRequestURI();
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if ("/api/admin/auth/login".equals(uri)) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
HttpSession session = request.getSession(false);
|
||||
if (session == null || session.getAttribute(ADMIN_SESSION_ID) == null) {
|
||||
error(response, 401, "请先登录");
|
||||
return;
|
||||
}
|
||||
Object csrf = session.getAttribute(CSRF_SESSION_KEY);
|
||||
if (isMutation(request.getMethod())
|
||||
&& (csrf == null || !csrf.equals(request.getHeader("X-CSRF-Token")))) {
|
||||
error(response, 403, "请求校验失败,请刷新后重试");
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private static boolean isMutation(String method) {
|
||||
return "POST".equals(method) || "PUT".equals(method)
|
||||
|| "PATCH".equals(method) || "DELETE".equals(method);
|
||||
}
|
||||
|
||||
private static void error(HttpServletResponse response, int status, String message) throws IOException {
|
||||
response.setStatus(status);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
response.setContentType("application/json");
|
||||
response.getWriter().write("{\"message\":\"" + message + "\"}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package me.iiv.agent.admin;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import me.iiv.agent.entity.m0.User;
|
||||
import me.iiv.agent.entity.svc.AgentApiKey;
|
||||
import me.iiv.agent.entity.svc.AgentScope;
|
||||
import me.iiv.agent.entity.svc.TokenScope;
|
||||
import me.iiv.agent.mapper.m0.UserMapper;
|
||||
import me.iiv.agent.mapper.svc.AgentApiKeyMapper;
|
||||
import me.iiv.agent.mapper.svc.AgentScopeMapper;
|
||||
import me.iiv.agent.mapper.svc.TokenScopeMapper;
|
||||
import me.iiv.agent.security.AuthService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class AdminTokenService {
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final AgentApiKeyMapper tokenMapper;
|
||||
private final TokenScopeMapper relationMapper;
|
||||
private final AgentScopeMapper scopeMapper;
|
||||
|
||||
public AdminTokenService(UserMapper userMapper, AgentApiKeyMapper tokenMapper,
|
||||
TokenScopeMapper relationMapper, AgentScopeMapper scopeMapper) {
|
||||
this.userMapper = userMapper;
|
||||
this.tokenMapper = tokenMapper;
|
||||
this.relationMapper = relationMapper;
|
||||
this.scopeMapper = scopeMapper;
|
||||
}
|
||||
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public IssuedToken issue(Long userId, String memo, List<Long> scopeIds, Date expireTime, Long adminId) {
|
||||
User user = userMapper.selectById(userId);
|
||||
if (user == null || Integer.valueOf(1).equals(user.getSoftDelete())) bad("人员不存在");
|
||||
validateMemo(memo);
|
||||
validateScopes(scopeIds);
|
||||
String plaintext = "xqak_" + AdminAuthController.randomHex(24);
|
||||
AgentApiKey token = new AgentApiKey();
|
||||
token.setUserId(userId);
|
||||
token.setKeyPrefix(plaintext.substring(0, 13));
|
||||
token.setKeyHash(AuthService.sha256Hex(plaintext));
|
||||
token.setMemo(trim(memo, 255));
|
||||
token.setStatus((byte) 1);
|
||||
token.setExpireTime(expireTime);
|
||||
token.setCreateId(adminId);
|
||||
token.setModifyId(adminId);
|
||||
token.setSoftDelete((byte) 0);
|
||||
tokenMapper.insert(token);
|
||||
replaceScopes(token.getId(), scopeIds, adminId);
|
||||
return new IssuedToken(plaintext, view(token));
|
||||
}
|
||||
|
||||
@Transactional(transactionManager = "svcTransactionManager")
|
||||
public void update(Long tokenId, String memo, List<Long> scopeIds, Date expireTime, Long adminId) {
|
||||
AgentApiKey current = activeToken(tokenId);
|
||||
validateMemo(memo);
|
||||
validateScopes(scopeIds);
|
||||
current.setMemo(trim(memo, 255));
|
||||
current.setExpireTime(expireTime);
|
||||
current.setModifyId(adminId);
|
||||
tokenMapper.updateById(current);
|
||||
replaceScopes(tokenId, scopeIds, adminId);
|
||||
}
|
||||
|
||||
public void status(Long tokenId, byte status, Long adminId) {
|
||||
if (status != 0 && status != 1) bad("状态无效");
|
||||
AgentApiKey token = activeToken(tokenId);
|
||||
token.setStatus(status);
|
||||
token.setModifyId(adminId);
|
||||
tokenMapper.updateById(token);
|
||||
}
|
||||
|
||||
public void delete(Long tokenId, Long adminId) {
|
||||
AgentApiKey token = activeToken(tokenId);
|
||||
token.setStatus((byte) 0);
|
||||
token.setSoftDelete((byte) 1);
|
||||
token.setModifyId(adminId);
|
||||
tokenMapper.updateById(token);
|
||||
}
|
||||
|
||||
public List<TokenView> list(Long userId) {
|
||||
List<AgentApiKey> tokens = tokenMapper.selectList(new LambdaQueryWrapper<AgentApiKey>()
|
||||
.eq(AgentApiKey::getUserId, userId).eq(AgentApiKey::getSoftDelete, 0)
|
||||
.orderByDesc(AgentApiKey::getCreateTime));
|
||||
return tokens.stream().map(this::view).toList();
|
||||
}
|
||||
|
||||
private TokenView view(AgentApiKey token) {
|
||||
List<Long> scopeIds = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
|
||||
.eq(TokenScope::getTokenId, token.getId()).eq(TokenScope::getSoftDelete, 0))
|
||||
.stream().map(TokenScope::getScopeId).toList();
|
||||
List<String> scopeNames = scopeIds.isEmpty() ? List.of() : scopeMapper.selectList(
|
||||
new LambdaQueryWrapper<AgentScope>().in(AgentScope::getId, scopeIds))
|
||||
.stream().map(AgentScope::getName).toList();
|
||||
return new TokenView(token.getId(), token.getKeyPrefix(), token.getMemo(), token.getStatus(),
|
||||
token.getExpireTime(), token.getLastUsedTime(), scopeIds, scopeNames);
|
||||
}
|
||||
|
||||
private void replaceScopes(Long tokenId, List<Long> scopeIds, Long adminId) {
|
||||
List<TokenScope> old = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
|
||||
.eq(TokenScope::getTokenId, tokenId));
|
||||
for (TokenScope relation : old) {
|
||||
relation.setSoftDelete((byte) 1);
|
||||
relation.setModifyId(adminId);
|
||||
relationMapper.updateById(relation);
|
||||
}
|
||||
for (Long scopeId : scopeIds) {
|
||||
TokenScope relation = old.stream().filter(r -> scopeId.equals(r.getScopeId())).findFirst().orElse(null);
|
||||
if (relation == null) {
|
||||
relation = new TokenScope();
|
||||
relation.setTokenId(tokenId);
|
||||
relation.setScopeId(scopeId);
|
||||
relation.setCreateId(adminId);
|
||||
}
|
||||
relation.setSoftDelete((byte) 0);
|
||||
relation.setModifyId(adminId);
|
||||
if (relation.getId() == null) relationMapper.insert(relation); else relationMapper.updateById(relation);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateScopes(List<Long> scopeIds) {
|
||||
if (scopeIds == null || scopeIds.isEmpty()) bad("至少选择一个作用域");
|
||||
if (scopeIds.stream().distinct().count() != scopeIds.size()) bad("作用域不能重复");
|
||||
long count = scopeMapper.selectList(new LambdaQueryWrapper<AgentScope>()
|
||||
.in(AgentScope::getId, scopeIds).eq(AgentScope::getStatus, 1)
|
||||
.eq(AgentScope::getSoftDelete, 0)).size();
|
||||
if (count != scopeIds.stream().distinct().count()) bad("作用域不存在或已停用");
|
||||
}
|
||||
|
||||
private static void validateMemo(String memo) {
|
||||
if (memo != null && memo.length() > 255) bad("用途备注最多 255 字");
|
||||
}
|
||||
|
||||
private AgentApiKey activeToken(Long id) {
|
||||
AgentApiKey token = tokenMapper.selectById(id);
|
||||
if (token == null || token.getSoftDelete() == null || token.getSoftDelete() != 0) bad("Token 不存在");
|
||||
return token;
|
||||
}
|
||||
|
||||
private static String trim(String value, int max) {
|
||||
if (value == null) return null;
|
||||
String result = value.trim();
|
||||
return result.length() <= max ? result : result.substring(0, max);
|
||||
}
|
||||
|
||||
private static void bad(String message) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
|
||||
}
|
||||
|
||||
public record TokenView(Long id, String keyPrefix, String memo, Byte status, Date expireTime,
|
||||
Date lastUsedTime, List<Long> scopeIds, List<String> scopeNames) {}
|
||||
public record IssuedToken(String plaintext, TokenView token) {}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.jdbc.DataSourceBuilder;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@@ -35,4 +37,9 @@ public class SvcDataSourceConfig {
|
||||
bean.setConfiguration(configuration);
|
||||
return bean.getObject();
|
||||
}
|
||||
|
||||
@Bean(name = "svcTransactionManager")
|
||||
public PlatformTransactionManager svcTransactionManager(@Qualifier("svcDataSource") DataSource dataSource) {
|
||||
return new DataSourceTransactionManager(dataSource);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public class AdminUser implements Serializable {
|
||||
private String account;
|
||||
|
||||
/**
|
||||
* 密码 SHA-256 hex
|
||||
* PBKDF2 加盐密码哈希
|
||||
*/
|
||||
private String passwordHash;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user