feat(admin): 顶部账号区支持修改自己的密码并失效旧会话

所有后台账号可在左上角修改本人密码:校验原密码、新密码至少 12 位,
成功后该账号所有既有会话立即失效需重新登录。会话校验新增密码哈希比对。
后端 615 项、前端 7 项测试全部通过。
This commit is contained in:
my_local_kimi_dev2
2026-11-19 10:48:51 +08:00
parent 2aa99abddd
commit 6dad85d6e4
6 changed files with 228 additions and 0 deletions
@@ -8,6 +8,7 @@ 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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
@@ -43,6 +44,7 @@ public class AdminAuthController {
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, admin.getId());
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_NAME,
admin.getName() == null ? admin.getAccount() : admin.getName());
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_PASSWORD_HASH, admin.getPasswordHash());
String csrf = randomHex(24);
session.setAttribute(AdminSessionFilter.CSRF_SESSION_KEY, csrf);
return new SessionView(admin.getId(), admin.getAccount(),
@@ -66,10 +68,30 @@ public class AdminAuthController {
session.invalidate();
}
@PutMapping("/password")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void changePassword(@RequestBody PasswordChangeRequest body, HttpSession session) {
if (body == null || body.oldPassword() == null || body.oldPassword().isBlank()
|| body.oldPassword().length() > 1024) throw badRequest("原密码不能为空且最多 1024 位");
if (body.newPassword() == null || body.newPassword().length() < 12
|| body.newPassword().length() > 1024) throw badRequest("新密码长度须为 12 至 1024 位");
Long adminId = (Long) session.getAttribute(AdminSessionFilter.ADMIN_SESSION_ID);
AdminUser admin = mapper.selectById(adminId);
if (!hasher.matches(body.oldPassword(), admin.getPasswordHash())) throw badRequest("原密码不正确");
admin.setPasswordHash(hasher.hash(body.newPassword()));
admin.setModifyId(adminId);
mapper.updateById(admin);
session.invalidate();
}
private static ResponseStatusException unauthorized() {
return new ResponseStatusException(HttpStatus.UNAUTHORIZED, "账号或密码错误");
}
private static ResponseStatusException badRequest(String message) {
return new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
}
static String randomHex(int bytes) {
byte[] value = new byte[bytes];
RANDOM.nextBytes(value);
@@ -79,5 +101,6 @@ public class AdminAuthController {
}
public record LoginRequest(String account, String password) {}
public record PasswordChangeRequest(String oldPassword, String newPassword) {}
public record SessionView(Long id, String account, String name, String csrfToken) {}
}
@@ -18,6 +18,7 @@ public class AdminSessionFilter extends OncePerRequestFilter {
static final String ADMIN_SESSION_ID = "adminUserId";
static final String ADMIN_SESSION_NAME = "adminName";
static final String ADMIN_SESSION_PASSWORD_HASH = "adminPasswordHash";
static final String CSRF_SESSION_KEY = "adminCsrf";
private final AdminUserMapper adminUserMapper;
@@ -53,6 +54,12 @@ public class AdminSessionFilter extends OncePerRequestFilter {
error(response, 401, "账号已禁用或删除,请重新登录");
return;
}
Object passwordHash = session.getAttribute(ADMIN_SESSION_PASSWORD_HASH);
if (passwordHash == null || !passwordHash.equals(admin.getPasswordHash())) {
session.invalidate();
error(response, 401, "密码已修改,请重新登录");
return;
}
if (("/api/admin/accounts".equals(uri) || uri.startsWith("/api/admin/accounts/"))
&& !"admin".equals(admin.getAccount())) {
error(response, 403, "仅 admin 可管理后台账号");
@@ -0,0 +1,122 @@
package me.iiv.agent.admin;
import me.iiv.agent.entity.svc.AdminUser;
import me.iiv.agent.mapper.svc.AdminUserMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
@ExtendWith(MockitoExtension.class)
class AdminAuthControllerTest {
@Mock AdminUserMapper mapper;
@Mock AdminPasswordHasher hasher;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
mockMvc = standaloneSetup(new AdminAuthController(mapper, hasher)).build();
}
@Test
void changePasswordVerifiesOldPasswordHashesNewPasswordAndInvalidatesSession() throws Exception {
AdminUser admin = activeAdmin(7L, "operator", "old-hash");
when(mapper.selectById(7L)).thenReturn(admin);
when(hasher.matches("old-password", "old-hash")).thenReturn(true);
when(hasher.hash("new-strong-password")).thenReturn("new-hash");
MockHttpSession session = authenticatedSession(7L);
mockMvc.perform(put("/api/admin/auth/password").session(session)
.contentType("application/json")
.content("{\"oldPassword\":\"old-password\",\"newPassword\":\"new-strong-password\"}"))
.andExpect(status().isNoContent());
ArgumentCaptor<AdminUser> captor = ArgumentCaptor.forClass(AdminUser.class);
verify(mapper).updateById(captor.capture());
assertEquals("new-hash", captor.getValue().getPasswordHash());
assertEquals(7L, captor.getValue().getModifyId());
assertTrue(session.isInvalid());
}
@Test
void changePasswordRejectsWrongOldPasswordWithoutChangingSession() throws Exception {
AdminUser admin = activeAdmin(7L, "operator", "old-hash");
when(mapper.selectById(7L)).thenReturn(admin);
when(hasher.matches("wrong-password", "old-hash")).thenReturn(false);
MockHttpSession session = authenticatedSession(7L);
mockMvc.perform(put("/api/admin/auth/password").session(session)
.contentType("application/json")
.content("{\"oldPassword\":\"wrong-password\",\"newPassword\":\"new-strong-password\"}"))
.andExpect(status().isBadRequest());
verify(mapper, never()).updateById(any(AdminUser.class));
verify(hasher, never()).hash(any());
assertFalse(session.isInvalid());
}
@Test
void changePasswordRejectsShortNewPassword() throws Exception {
MockHttpSession session = authenticatedSession(7L);
mockMvc.perform(put("/api/admin/auth/password").session(session)
.contentType("application/json")
.content("{\"oldPassword\":\"old-password\",\"newPassword\":\"short\"}"))
.andExpect(status().isBadRequest());
verify(mapper, never()).updateById(any(AdminUser.class));
assertFalse(session.isInvalid());
}
@Test
void loginStoresPasswordHashForLaterSessionInvalidation() throws Exception {
AdminUser admin = activeAdmin(7L, "operator", "current-hash");
when(mapper.selectOne(any())).thenReturn(admin);
when(hasher.matches("old-password", "current-hash")).thenReturn(true);
MvcResult result = mockMvc.perform(post("/api/admin/auth/login")
.contentType("application/json")
.content("{\"account\":\"operator\",\"password\":\"old-password\"}"))
.andExpect(status().isOk())
.andReturn();
assertEquals("current-hash", result.getRequest().getSession(false)
.getAttribute(AdminSessionFilter.ADMIN_SESSION_PASSWORD_HASH));
}
private static MockHttpSession authenticatedSession(Long adminId) {
MockHttpSession session = new MockHttpSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, adminId);
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_PASSWORD_HASH, "old-hash");
return session;
}
private static AdminUser activeAdmin(Long id, String account, String passwordHash) {
AdminUser admin = new AdminUser();
admin.setId(id);
admin.setAccount(account);
admin.setPasswordHash(passwordHash);
admin.setStatus((byte) 1);
admin.setSoftDelete((byte) 0);
return admin;
}
}
@@ -12,6 +12,7 @@ import org.springframework.mock.web.MockHttpSession;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -26,6 +27,7 @@ class AdminSessionFilterTest {
AdminUser admin = new AdminUser();
admin.setId(1L);
admin.setAccount("admin");
admin.setPasswordHash("current-hash");
admin.setStatus((byte) 1);
admin.setSoftDelete((byte) 0);
lenient().when(mapper.selectById(1L)).thenReturn(admin);
@@ -72,11 +74,13 @@ class AdminSessionFilterTest {
AdminUser operator = new AdminUser();
operator.setId(2L);
operator.setAccount("operator");
operator.setPasswordHash("current-hash");
operator.setStatus((byte) 1);
operator.setSoftDelete((byte) 0);
when(mapper.selectById(2L)).thenReturn(operator);
MockHttpSession session = new MockHttpSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, 2L);
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_PASSWORD_HASH, "current-hash");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/accounts");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
@@ -135,9 +139,28 @@ class AdminSessionFilterTest {
assertNull(chain.getRequest());
}
@Test
void passwordChangeInvalidatesOtherExistingSessions() throws Exception {
AdminUser admin = mapper.selectById(1L);
admin.setPasswordHash("new-hash");
MockHttpSession session = authenticatedSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_PASSWORD_HASH, "old-hash");
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/admin/tools");
request.setSession(session);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain chain = new MockFilterChain();
filter.doFilter(request, response, chain);
assertEquals(401, response.getStatus());
assertTrue(session.isInvalid());
assertNull(chain.getRequest());
}
private static MockHttpSession authenticatedSession() {
MockHttpSession session = new MockHttpSession();
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_ID, 1L);
session.setAttribute(AdminSessionFilter.ADMIN_SESSION_PASSWORD_HASH, "current-hash");
return session;
}
}