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

@@ -72,7 +72,7 @@ Full design with approaches and the user's approved calls: `docs/superpowers/spe
- Logout records `LOGOUT` for the token's user.
6. **Client IP and user agent:**
- The portal's login and logout routes send `X-Client-IP` (the first entry of the incoming `x-forwarded-for`, else empty) and `User-Agent` to mobile-api.
- The portal's login and logout routes already send `X-Client-Ip` (the last `x-forwarded-for` hop, the one the ingress adds, else `x-real-ip`) and `X-Client-User-Agent` (the browser's user agent) to mobile-api, through `app/lib/server/clientContext.ts`, which was ported from babyboo.
- mobile-api reads them from the request for the record only.
- They are never used for any decision, since a client can forge them.
@@ -70,7 +70,7 @@ Design: `design.md`. All tasks run serially: each builds on the one before.
- Scope: `solvway-mobile-api/src/**` (`AdminAuthController`, `AdminAuthenticationService`, request record, tests)
- Verify: `mvn -T 1C -B -q -pl solvway-mobile-api -am verify`
- [ ] 3.3 `AdminLoginSecurityController` and service (design decision 8).
- [x] 3.3 `AdminLoginSecurityController` and service (design decision 8).
- **Tests first:**
- class-level `@AdminModule("BO_LOGIN_SECURITY")`;
- each endpoint maps its parameters;
@@ -95,6 +95,11 @@ public class RestApiSystemServiceConstants {
//LoginSecurity (admin sign-in lock check and history)
public static final String API_REST_LOGIN_SECURITY_IS_LOCKED = "/loginSecurity/isLocked/{username}";
public static final String API_REST_LOGIN_SECURITY_RECORD = "/loginSecurity/record";
public static final String API_REST_LOGIN_SECURITY_AUDIT = "/loginSecurity/audit";
public static final String API_REST_LOGIN_SECURITY_LOCKED = "/loginSecurity/locked";
public static final String API_REST_LOGIN_SECURITY_UNLOCK = "/loginSecurity/unlock";
public static final String API_REST_LOGIN_SECURITY_CONFIG = "/loginSecurity/config";
public static final String API_REST_LOGIN_SECURITY_PASSWORD_RULES = "/loginSecurity/passwordRules";
//Message
public static final String API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE = "/message/findByCodeAndLocale/{code}/{locale}";
@@ -0,0 +1,77 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.mobile.api.service.AdminLoginSecurityService;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
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.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.RestController;
import java.util.List;
import java.util.Map;
/** Login security screen: sign-in history, locked accounts, lockout settings, password rules. Must stay under {@code controller..} for AppAccessAspect. */
@RestController
@RequestMapping("/api/admin/login-security")
@RequiredArgsConstructor
@AdminModule("BO_LOGIN_SECURITY")
public class AdminLoginSecurityController {
private final AdminLoginSecurityService loginSecurity;
@AppAuth
@GetMapping("/audit")
public ResponseEntity<Map<String, Object>> audit(
@RequestParam(required = false) String username,
@RequestParam(required = false) String event,
@RequestParam(required = false) String from,
@RequestParam(required = false) String to,
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size) {
return ResponseEntity.ok(loginSecurity.audit(username, event, from, to, page, size));
}
@AppAuth
@GetMapping("/locked")
public ResponseEntity<List<Map<String, Object>>> locked() {
return ResponseEntity.ok(loginSecurity.locked());
}
@AppAuth
@PostMapping("/locked/{username}/unlock")
public ResponseEntity<Void> unlock(@PathVariable String username) {
loginSecurity.unlock(username);
return ResponseEntity.noContent().build();
}
@AppAuth
@GetMapping("/config")
public ResponseEntity<Map<String, Object>> config() {
return ResponseEntity.ok(loginSecurity.config());
}
@AppAuth
@PutMapping("/config")
public ResponseEntity<Map<String, Object>> saveConfig(@RequestBody Map<String, Object> config) {
return ResponseEntity.ok(loginSecurity.saveConfig(config));
}
@AppAuth
@GetMapping("/password-rules")
public ResponseEntity<List<Map<String, Object>>> passwordRules() {
return ResponseEntity.ok(loginSecurity.passwordRules());
}
@AppAuth
@PutMapping("/password-rules")
public ResponseEntity<List<Map<String, Object>>> savePasswordRules(@RequestBody List<Map<String, Object>> rules) {
return ResponseEntity.ok(loginSecurity.savePasswordRules(rules));
}
}
@@ -0,0 +1,108 @@
package com.solvway.mobile.api.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
/** Passes the Login security screen's calls to services-system, turning its 400s into coded admin errors. */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminLoginSecurityService {
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
private static final ParameterizedTypeReference<List<Map<String, Object>>> LIST = new ParameterizedTypeReference<>() {};
private static final ObjectMapper JSON = new ObjectMapper();
private final RestTemplateCustomUtil restTemplateUtil;
private final AdminAuthenticationService adminAuthenticationService;
public Map<String, Object> audit(String username, String event, String from, String to, int page, int size) {
Map<String, Object> body = new LinkedHashMap<>();
if (StringUtils.hasText(username)) body.put("username", username.trim());
if (StringUtils.hasText(event)) body.put("event", event.trim());
if (StringUtils.hasText(from)) body.put("from", from.trim());
if (StringUtils.hasText(to)) body.put("to", to.trim());
body.put("page", page);
body.put("size", size);
return post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_AUDIT, MAP, body);
}
public List<Map<String, Object>> locked() {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_LOCKED), LIST).getBody();
}
public void unlock(String username) {
String by = callerName();
post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_UNLOCK, MAP, Map.of("username", username, "by", by));
log.info("login lock for {} cleared by {}", username, by);
}
public Map<String, Object> config() {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG), MAP).getBody();
}
public Map<String, Object> saveConfig(Map<String, Object> config) {
Map<String, Object> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_CONFIG, MAP, config);
log.info("lockout settings changed by {}", callerName());
return saved;
}
public List<Map<String, Object>> passwordRules() {
return restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES), LIST).getBody();
}
public List<Map<String, Object>> savePasswordRules(List<Map<String, Object>> rules) {
List<Map<String, Object>> saved = post(RestApiSystemServiceConstants.API_REST_LOGIN_SECURITY_PASSWORD_RULES, LIST, rules);
log.info("password rules changed by {}", callerName());
return saved;
}
private <T> T post(String api, ParameterizedTypeReference<T> type, Object body) {
return upstream(() -> restTemplateUtil.postForEntity(url(api), type, body).getBody());
}
private static <T> T upstream(Supplier<T> call) {
try {
return call.get();
} catch (HttpClientErrorException.BadRequest e) {
throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, reason(e), "INVALID_SETTING");
}
}
private static String reason(HttpClientErrorException e) {
try {
JsonNode message = JSON.readTree(e.getResponseBodyAsString()).get("message");
if (message != null && message.isTextual() && StringUtils.hasText(message.asText())) return message.asText();
} catch (Exception ignored) {
// empty or unparsable body: fall through to the generic reason
}
return "Invalid request";
}
private String callerName() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
return caller.getUsername();
}
private String url(String api) {
return restTemplateUtil.getURLforApiService(api);
}
}
@@ -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"));
}
}