feat: admin API for login history, locked accounts, unlock and settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-30 14:01:04 +08:00
1 parent 6c6734baa3
commit 5ce684168a
7 files changed
+423 -2

No files matched your search

@@ -0,0 +1,94 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.mobile.api.service.AdminLoginSecurityService;
import com.solvway.mobile.api.useraccess.AdminModule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(MockitoExtension.class)
class AdminLoginSecurityControllerTest {
@Mock private AdminLoginSecurityService security;
@InjectMocks private AdminLoginSecurityController controller;
private MockMvc mvc;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
void guardedByLoginSecurityModule() {
assertThat(AdminLoginSecurityController.class.getAnnotation(AdminModule.class).value()).containsExactly("BO_LOGIN_SECURITY");
}
@Test
void audit_passesFiltersAndPaging() throws Exception {
when(security.audit("sales1", "LOCKED", "2026-11-01", "2026-11-30", 1, 5))
.thenReturn(Map.of("content", List.of(Map.of("id", 7)), "totalElements", 6));
mvc.perform(get("/api/admin/login-security/audit").param("username", "sales1").param("event", "LOCKED")
.param("from", "2026-11-01").param("to", "2026-11-30").param("page", "1").param("size", "5"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content[0].id").value(7));
}
@Test
void audit_defaultsToFirstPageOfTwenty() throws Exception {
when(security.audit(null, null, null, null, 0, 20)).thenReturn(Map.of("content", List.of()));
mvc.perform(get("/api/admin/login-security/audit")).andExpect(status().isOk());
verify(security).audit(null, null, null, null, 0, 20);
}
@Test
void locked_returnsList() throws Exception {
when(security.locked()).thenReturn(List.of(Map.of("username", "sales1", "failures", 5)));
mvc.perform(get("/api/admin/login-security/locked")).andExpect(status().isOk()).andExpect(jsonPath("$[0].username").value("sales1"));
}
@Test
void unlock_returns204() throws Exception {
mvc.perform(post("/api/admin/login-security/locked/sales1/unlock")).andExpect(status().isNoContent());
verify(security).unlock("sales1");
}
@Test
void config_getAndPut() throws Exception {
when(security.config()).thenReturn(Map.of("maxAttempts", 5));
mvc.perform(get("/api/admin/login-security/config")).andExpect(status().isOk()).andExpect(jsonPath("$.maxAttempts").value(5));
Map<String, Object> body = Map.of("enabled", true, "maxAttempts", 3, "period", 15, "unit", "MINUTES");
when(security.saveConfig(body)).thenReturn(body);
mvc.perform(put("/api/admin/login-security/config").contentType(MediaType.APPLICATION_JSON)
.content("{\"enabled\":true,\"maxAttempts\":3,\"period\":15,\"unit\":\"MINUTES\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.maxAttempts").value(3));
}
@Test
void passwordRules_getAndPut() throws Exception {
when(security.passwordRules()).thenReturn(List.of(Map.of("id", 1)));
mvc.perform(get("/api/admin/login-security/password-rules")).andExpect(status().isOk()).andExpect(jsonPath("$[0].id").value(1));
List<Map<String, Object>> body = List.of(Map.of("id", 1, "status", "Y", "value", "8"));
when(security.savePasswordRules(body)).thenReturn(body);
mvc.perform(put("/api/admin/login-security/password-rules").contentType(MediaType.APPLICATION_JSON)
.content("[{\"id\":1,\"status\":\"Y\",\"value\":\"8\"}]"))
.andExpect(status().isOk()).andExpect(jsonPath("$[0].value").value("8"));
}
}
@@ -0,0 +1,137 @@
package com.solvway.mobile.api.service;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.MockedStatic;
import org.slf4j.LoggerFactory;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@SuppressWarnings({"unchecked", "rawtypes"})
class AdminLoginSecurityServiceTest {
private static final String AUDIT = "/loginSecurity/audit";
private static final String UNLOCK = "/loginSecurity/unlock";
private static final String CONFIG = "/loginSecurity/config";
private static final String RULES = "/loginSecurity/passwordRules";
private RestTemplateCustomUtil rest;
private AdminLoginSecurityService service;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
rest = mock(RestTemplateCustomUtil.class);
AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
service = new AdminLoginSecurityService(rest, auth);
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
User caller = new User();
caller.setUsername("boss");
when(auth.loadUserByToken("tok")).thenReturn(caller);
}
@AfterEach
void close() { http.close(); }
private static HttpClientErrorException badRequest(String body) {
return HttpClientErrorException.create(HttpStatus.BAD_REQUEST, "Bad Request", new HttpHeaders(), body.getBytes(StandardCharsets.UTF_8), null);
}
private Object postedBody(String url) {
ArgumentCaptor<Object> body = ArgumentCaptor.forClass(Object.class);
verify(rest).postForEntity(eq(url), any(ParameterizedTypeReference.class), body.capture());
return body.getValue();
}
private List<String> captureLogs(Runnable action) {
Logger logger = (Logger) LoggerFactory.getLogger(AdminLoginSecurityService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
action.run();
} finally {
logger.detachAppender(appender);
}
return appender.list.stream().map(ILoggingEvent::getFormattedMessage).toList();
}
@Test
void audit_forwardsOnlyGivenFiltersWithDefaultPaging() {
when(rest.postForEntity(eq(AUDIT), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(Map.of("content", List.of())));
service.audit("sales1", null, " ", "2026-11-30", 0, 20);
Map<String, Object> sent = (Map<String, Object>) postedBody(AUDIT);
assertThat(sent).containsOnlyKeys("username", "to", "page", "size");
assertThat(sent).containsEntry("username", "sales1").containsEntry("page", 0).containsEntry("size", 20);
}
@Test
void unlock_sendsCallerAsBy_andLogs() {
when(rest.postForEntity(eq(UNLOCK), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok().build());
List<String> logs = captureLogs(() -> service.unlock("sales1"));
assertThat((Map<String, Object>) postedBody(UNLOCK)).containsEntry("username", "sales1").containsEntry("by", "boss");
assertThat(logs).containsExactly("login lock for sales1 cleared by boss");
}
@Test
void saveConfig_returnsBody_andLogsCaller() {
Map<String, Object> cfg = Map.of("enabled", true, "maxAttempts", 3, "period", 15, "unit", "MINUTES");
when(rest.postForEntity(eq(CONFIG), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(cfg));
List<String> logs = captureLogs(() -> assertThat(service.saveConfig(cfg)).isEqualTo(cfg));
assertThat(logs).containsExactly("lockout settings changed by boss");
}
@Test
void savePasswordRules_returnsBody_andLogsCaller() {
List<Map<String, Object>> rules = List.of(Map.of("id", 1, "status", "Y", "value", "8"));
when(rest.postForEntity(eq(RULES), any(ParameterizedTypeReference.class), any())).thenReturn(ResponseEntity.ok(rules));
List<String> logs = captureLogs(() -> assertThat(service.savePasswordRules(rules)).isEqualTo(rules));
assertThat(logs).containsExactly("password rules changed by boss");
}
@Test
void upstreamBadRequest_becomesInvalidSettingWithUpstreamMessage() {
when(rest.postForEntity(eq(CONFIG), any(ParameterizedTypeReference.class), any()))
.thenThrow(badRequest("{\"message\":\"maxAttempts must be at least 1\"}"));
assertThatThrownBy(() -> service.saveConfig(Map.of("maxAttempts", 0)))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> {
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getCode()).isEqualTo("INVALID_SETTING");
assertThat(e.getReason()).isEqualTo("maxAttempts must be at least 1");
});
}
@Test
void upstreamBadRequestWithoutBody_fallsBackToGenericReason() {
when(rest.postForEntity(eq(AUDIT), any(ParameterizedTypeReference.class), any())).thenThrow(badRequest(""));
assertThatThrownBy(() -> service.audit(null, null, "nope", null, 0, 20))
.isInstanceOfSatisfying(CodedResponseStatusException.class, e -> assertThat(e.getReason()).isEqualTo("Invalid request"));
}
}