feat: company sign-in, company scope and super-admin Companies API

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 19:42:40 +08:00
1 parent 91a0f339a5
commit 69d3ebc58c
16 files changed
+702 -12

No files matched your search

@@ -92,6 +92,12 @@ public class RestApiSystemServiceConstants {
public static final String API_REST_GENERIC_POST_FIND_BY_UUID = "/system/genericPost/findByUuid/{uuid}";
public static final String API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE = "/system/genericPost/content/findByPostUuidAndLocale/{uuid}/{locale}";
//Company
public static final String API_REST_COMPANY_FIND_ALL = "/company/findAll";
public static final String API_REST_COMPANY_FIND_BY_ID = "/company/findById/{id}";
public static final String API_REST_COMPANY_SAVE = "/company/save";
public static final String API_REST_COMPANY_RENAME_CODE = "/company/{id}/code";
//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";
@@ -7,12 +7,14 @@ import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.dto.admin.AdminChangePasswordRequest;
import com.solvway.mobile.api.dto.admin.AdminFirstLoginRequest;
import com.solvway.mobile.api.dto.admin.AdminForgotPasswordRequest;
import com.solvway.mobile.api.dto.admin.AdminLoginRequest;
import com.solvway.mobile.api.dto.admin.AdminLoginResponse;
import com.solvway.mobile.api.dto.admin.AdminMeResponse;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.model.AuthRequest;
import com.solvway.mobile.api.service.AdminAuthenticationService;
import com.solvway.mobile.api.service.AuthenticationService;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.useraccess.AdminModule;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -43,12 +45,15 @@ public class AdminAuthController {
@AppAuth(skipValidate = true)
@PostMapping("/auth/login")
public ResponseEntity<?> login(@RequestBody AuthRequest request) {
public ResponseEntity<?> login(@RequestBody AdminLoginRequest in) {
// Blank fields never reach services-auth: it fails differently for known and unknown usernames.
if (!StringUtils.hasText(request.getUsername()) || !StringUtils.hasText(request.getPassword())) {
String username = loginName(in.company(), in.username());
if (username == null || !StringUtils.hasText(in.password())) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(BAD_LOGIN);
}
String username = request.getUsername().trim();
AuthRequest request = new AuthRequest();
request.setUsername(username);
request.setPassword(in.password());
if (adminAuthenticationService.isLocked(username)) {
adminAuthenticationService.record(username, "LOGIN_LOCKED", null);
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ACCOUNT_LOCKED);
@@ -64,6 +69,11 @@ public class AdminAuthController {
authenticationService.logoutToken(token);
u = null;
}
if (u != null && u.getCompanyId() != null && !AdminCompanyScope.isSuper(u) && !"A".equals(u.getCompanyStatus())) {
// an inactive company cannot sign in; same revoke as a disabled admin
authenticationService.logoutToken(token);
u = null;
}
} catch (RestClientException ex) {
u = null; // any upstream failure is a refused login; never echo why
token = null;
@@ -74,7 +84,8 @@ public class AdminAuthController {
}
adminAuthenticationService.record(username, "LOGIN_SUCCESS", null);
return ResponseEntity.ok(new AdminLoginResponse(token, u.getName(), u.getRoles(), u.getAclMenu(),
GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false"));
GeneralEnum.LoginStatus.N.equals(u.getLogin()) ? "true" : "false",
u.getCompanyId(), u.getCompanyCode(), AdminCompanyScope.isSuper(u)));
}
@AdminModule(value = AdminModule.ANY_ADMIN, allowPendingReset = true)
@@ -143,8 +154,9 @@ public class AdminAuthController {
@PostMapping("/auth/forgot-password")
public ResponseEntity<Map<String, String>> forgotPassword(@RequestBody AdminForgotPasswordRequest request) {
try {
if (StringUtils.hasText(request.username()) && StringUtils.hasText(request.email())) {
adminAuthenticationService.resetAdminPassword(request.username().trim(), request.email().trim());
String username = loginName(request.company(), request.username());
if (username != null && StringUtils.hasText(request.email())) {
adminAuthenticationService.resetAdminPassword(username, request.email().trim());
}
} catch (Exception e) {
log.warn("Admin forgot-password failed downstream: {}", e.getClass().getSimpleName());
@@ -186,6 +198,16 @@ public class AdminAuthController {
if (u == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(new AdminMeResponse(u.getId(), u.getUsername(), u.getName(), u.getRoles(), u.getAclMenu()));
return ResponseEntity.ok(new AdminMeResponse(u.getId(), u.getUsername(), u.getName(), u.getRoles(), u.getAclMenu(),
u.getCompanyId(), u.getCompanyCode(), AdminCompanyScope.isSuper(u)));
}
/** Stored login name: {@code username@company}, or the plain username for a blank company (super admin). Null when unusable. */
private static String loginName(String company, String username) {
if (!StringUtils.hasText(username) || username.contains("@")) {
return null;
}
String code = company == null ? "" : company.trim().toLowerCase();
return code.isEmpty() ? username.trim() : username.trim() + "@" + code;
}
}
@@ -0,0 +1,73 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.service.AdminAuthenticationService;
import com.solvway.mobile.api.service.AdminCompanyService;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/** Companies screen, super admin only. No @AdminModule on purpose: AppAccessAspect then lets only role 1 through, and requireSuper rejects company staff holding it. Must stay under {@code controller..}. */
@RestController
@RequestMapping("/api/admin/companies")
@RequiredArgsConstructor
public class AdminCompanyController {
private final AdminCompanyService companies;
private final AdminAuthenticationService adminAuthenticationService;
private final AdminCompanyScope scope;
@AppAuth
@GetMapping
public ResponseEntity<List<Map<String, Object>>> list() {
requireSuper();
return ResponseEntity.ok(companies.list());
}
@AppAuth
@GetMapping("/{id}")
public ResponseEntity<Map<String, Object>> get(@PathVariable Long id) {
requireSuper();
return ResponseEntity.ok(companies.get(id));
}
@AppAuth
@PostMapping
public ResponseEntity<Map<String, Object>> save(@RequestBody Map<String, Object> body) {
requireSuper();
return ResponseEntity.ok(companies.save(body));
}
@AppAuth
@PostMapping("/{id}/code")
public ResponseEntity<Map<String, Object>> renameCode(@PathVariable Long id, @RequestBody Map<String, String> body) {
requireSuper();
return ResponseEntity.ok(companies.renameCode(id, body.get("code")));
}
/** Portal body is just {"message"}; the exception still reaches AppAccessAspect first, so the audit has the real status. */
@ExceptionHandler(CodedResponseStatusException.class)
public ResponseEntity<Map<String, String>> upstream(CodedResponseStatusException e) {
return ResponseEntity.status(e.getStatusCode()).body(Map.of("message", String.valueOf(e.getReason())));
}
private void requireSuper() {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw new CodedResponseStatusException(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
scope.requireSuper(caller);
}
}
@@ -1,5 +1,5 @@
package com.solvway.mobile.api.dto.admin;
/** Body of {@code POST /api/admin/auth/forgot-password}. */
public record AdminForgotPasswordRequest(String username, String email) {
/** Body of {@code POST /api/admin/auth/forgot-password}. A blank company means a super admin. */
public record AdminForgotPasswordRequest(String company, String username, String email) {
}
@@ -0,0 +1,5 @@
package com.solvway.mobile.api.dto.admin;
/** Body of {@code POST /api/admin/auth/login}. A blank company means a super admin. */
public record AdminLoginRequest(String company, String username, String password) {
}
@@ -1,10 +1,12 @@
package com.solvway.mobile.api.dto.admin;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.solvway.core.model.Module;
import com.solvway.core.model.Role;
import java.util.List;
/** Body of {@code POST /api/admin/auth/login}. Declares no password field on purpose: the upstream user carries hashes. */
public record AdminLoginResponse(String token, String name, List<Role> roles, Module aclMenu, String resetPasswordRequired) {
public record AdminLoginResponse(String token, String name, List<Role> roles, Module aclMenu, String resetPasswordRequired,
Long companyId, String companyCode, @JsonProperty("isSuper") boolean isSuper) {
}
@@ -1,10 +1,12 @@
package com.solvway.mobile.api.dto.admin;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.solvway.core.model.Module;
import com.solvway.core.model.Role;
import java.util.List;
/** Body of {@code GET /api/admin/me}. No token or password fields. */
public record AdminMeResponse(Long id, String username, String name, List<Role> roles, Module aclMenu) {
public record AdminMeResponse(Long id, String username, String name, List<Role> roles, Module aclMenu,
Long companyId, String companyCode, @JsonProperty("isSuper") boolean isSuper) {
}
@@ -5,6 +5,7 @@ import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
import com.solvway.mobile.api.dto.admin.AdminModuleGrant;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import com.solvway.mobile.api.useraccess.AuditChanges;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import lombok.RequiredArgsConstructor;
@@ -45,7 +46,7 @@ public class AdminAclService {
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
if (caller == null) throw error(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
boolean isSuper = caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID);
boolean isSuper = AdminCompanyScope.isSuper(caller);
if (!isSuper && caller.getRoles() != null && caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() != ROLE_ADMIN_ID && r.getId().equals(roleId))) {
throw error(HttpStatus.FORBIDDEN, "You cannot change the access of a role you hold", "OWN_ROLE");
}
@@ -0,0 +1,74 @@
package com.solvway.mobile.api.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 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.List;
import java.util.Map;
import java.util.function.Supplier;
/** Passes the Companies screen's calls to services-system, turning its 400/409/404 into coded admin errors. */
@Service
@RequiredArgsConstructor
public class AdminCompanyService {
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;
public List<Map<String, Object>> list() {
return call(() -> restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_ALL), LIST).getBody());
}
public Map<String, Object> get(Long id) {
return call(() -> restTemplateUtil.getForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_FIND_BY_ID).replace("{id}", String.valueOf(id)), MAP).getBody());
}
public Map<String, Object> save(Map<String, Object> company) {
return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_SAVE), MAP, company).getBody());
}
public Map<String, Object> renameCode(Long id, String code) {
if (!StringUtils.hasText(code)) throw new CodedResponseStatusException(HttpStatus.BAD_REQUEST, "Code is required", "INVALID_COMPANY");
return call(() -> restTemplateUtil.postForEntity(url(RestApiSystemServiceConstants.API_REST_COMPANY_RENAME_CODE).replace("{id}", String.valueOf(id)), MAP,
Map.of("code", code)).getBody());
}
private static <T> T call(Supplier<T> call) {
try {
return call.get();
} catch (HttpClientErrorException e) {
HttpStatus status = HttpStatus.resolve(e.getStatusCode().value());
if (status == HttpStatus.BAD_REQUEST) throw new CodedResponseStatusException(status, reason(e, "Invalid request"), "INVALID_COMPANY");
if (status == HttpStatus.CONFLICT) throw new CodedResponseStatusException(status, reason(e, "Code is already taken"), "COMPANY_CODE_TAKEN");
if (status == HttpStatus.NOT_FOUND) throw new CodedResponseStatusException(status, reason(e, "Company not found"), "COMPANY_NOT_FOUND");
throw e;
}
}
private static String reason(HttpClientErrorException e, String fallback) {
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: use the fallback
}
return fallback;
}
private String url(String api) {
return restTemplateUtil.getURLforApiService(api);
}
}
@@ -0,0 +1,40 @@
package com.solvway.mobile.api.useraccess;
import com.solvway.core.model.User;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/** Which company an admin request may see or write. Every admin handler that reads or writes company data routes through here. */
@Component
public class AdminCompanyScope {
private static final long SUPER_ADMIN_ROLE_ID = 1L;
/** Super admin = no company and the super-admin role. A company user holding role 1 is still staff. */
public static boolean isSuper(User caller) {
return caller.getCompanyId() == null && caller.getRoles() != null
&& caller.getRoles().stream().anyMatch(r -> r.getId() != null && r.getId() == SUPER_ADMIN_ROLE_ID);
}
/** Staff: their own company, whatever was requested. Super: the requested company, null = all companies. */
public Long scope(User caller, Long requestedCompanyId) {
return isSuper(caller) ? requestedCompanyId : caller.getCompanyId();
}
/** Writes need a concrete company: staff get their own, a super admin must choose one. */
public Long requireCompanyForCreate(User caller, Long requestedCompanyId) {
Long company = scope(caller, requestedCompanyId);
if (company == null) throw coded(HttpStatus.BAD_REQUEST, "Choose a company.", "COMPANY_REQUIRED");
return company;
}
public void requireSuper(User caller) {
if (!isSuper(caller)) throw coded(HttpStatus.FORBIDDEN, "Super admin only", "SUPER_ADMIN_REQUIRED");
}
private static CodedResponseStatusException coded(HttpStatus status, String reason, String code) {
CodedResponseStatusException ex = new CodedResponseStatusException(status, reason, code);
ex.getBody().setProperty("message", reason); // the portal reads {"message"}
return ex;
}
}
@@ -23,6 +23,10 @@ public class AdminSessionGuard {
if (!user.isEnabled()) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Account disabled");
}
// Same reason as a dead session, so the response does not reveal an inactive company. Super admin has no company.
if (user.getCompanyId() != null && !"A".equals(user.getCompanyStatus())) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token");
}
if (user.getLogin() == LoginStatus.N && !allowPendingReset) {
throw new CodedResponseStatusException(HttpStatus.FORBIDDEN, "Password change required", "PASSWORD_RESET_REQUIRED");
}
@@ -0,0 +1,163 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.model.Role;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.model.AuthRequest;
import com.solvway.mobile.api.service.AdminAuthenticationService;
import com.solvway.mobile.api.service.AuthenticationService;
import org.junit.jupiter.api.AfterEach;
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.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mockStatic;
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.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(MockitoExtension.class)
class AdminAuthControllerCompanyTest {
@Mock private AdminAuthenticationService auth;
@Mock private AuthenticationService authenticationService;
@InjectMocks private AdminAuthController controller;
private MockMvc mvc;
private MockedStatic<HttpReqRespUtils> http;
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(controller).build();
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
}
@AfterEach
void close() { http.close(); }
private static User user(Long companyId, String code, String status, long roleId) {
User u = new User();
u.setId(9L);
u.setUsername(code == null ? "root" : "john@" + code);
u.setName("John");
u.setEnabled(true);
u.setLogin(GeneralEnum.LoginStatus.Y);
u.setCompanyId(companyId);
u.setCompanyCode(code);
u.setCompanyStatus(status);
Role r = new Role("R");
r.setId(roleId);
u.setRoles(List.of(r));
return u;
}
private ResultActions login(String body) throws Exception {
return mvc.perform(post("/api/admin/auth/login").contentType(MediaType.APPLICATION_JSON).content(body));
}
@Test
void login_buildsLoginNameFromCompanyAndUsername() throws Exception {
when(auth.getToken(any())).thenReturn("tok");
when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "A", 4));
login("{\"company\":\" INS \",\"username\":\"john\",\"password\":\"pw\"}").andExpect(status().isOk());
ArgumentCaptor<AuthRequest> sent = ArgumentCaptor.forClass(AuthRequest.class);
verify(auth).getToken(sent.capture());
assertThat(sent.getValue().getUsername()).isEqualTo("john@ins");
verify(auth).isLocked("john@ins");
verify(auth).record("john@ins", "LOGIN_SUCCESS", null);
}
@Test
void login_blankOrAbsentCompany_isSuperAdminPlainUsername() throws Exception {
when(auth.getToken(any())).thenReturn("tok");
when(auth.loadUserByToken("tok")).thenReturn(user(null, null, null, 1));
login("{\"company\":\"\",\"username\":\"root\",\"password\":\"pw\"}").andExpect(status().isOk());
login("{\"username\":\"root\",\"password\":\"pw\"}").andExpect(status().isOk());
ArgumentCaptor<AuthRequest> sent = ArgumentCaptor.forClass(AuthRequest.class);
verify(auth, org.mockito.Mockito.times(2)).getToken(sent.capture());
assertThat(sent.getAllValues()).allMatch(r -> r.getUsername().equals("root"));
}
@Test
void login_atSignInUsername_isBadLoginWithoutDownstreamCall() throws Exception {
login("{\"company\":\"ins\",\"username\":\"john@cv\",\"password\":\"pw\"}")
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.message").value("Invalid username or password"));
verify(auth, never()).getToken(any());
verify(auth, never()).isLocked(anyString());
}
@Test
void login_wrongCompanyOrUnknownUser_isBadLogin() throws Exception {
when(auth.getToken(any())).thenReturn(null);
login("{\"company\":\"nope\",\"username\":\"john\",\"password\":\"pw\"}").andExpect(status().isUnauthorized());
verify(auth).record("john@nope", "LOGIN_FAIL", null);
}
@Test
void login_inactiveCompany_isBadLoginAndRecordedAndTokenRevoked() throws Exception {
when(auth.getToken(any())).thenReturn("tok");
when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "I", 4));
login("{\"company\":\"ins\",\"username\":\"john\",\"password\":\"pw\"}")
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.message").value("Invalid username or password"));
verify(auth).record("john@ins", "LOGIN_FAIL", null);
verify(authenticationService).logoutToken("tok");
}
@Test
void login_response_carriesCompanyFieldsAndIsSuperKey() throws Exception {
when(auth.getToken(any())).thenReturn("tok");
when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "A", 4));
login("{\"company\":\"ins\",\"username\":\"john\",\"password\":\"pw\"}")
.andExpect(jsonPath("$.companyId").value(5)).andExpect(jsonPath("$.companyCode").value("ins"))
.andExpect(jsonPath("$.isSuper").value(false));
when(auth.loadUserByToken("tok")).thenReturn(user(null, null, null, 1));
login("{\"username\":\"root\",\"password\":\"pw\"}")
.andExpect(jsonPath("$.companyId").doesNotExist()).andExpect(jsonPath("$.isSuper").value(true));
}
@Test
void me_carriesCompanyFieldsAndIsSuperKey() throws Exception {
when(auth.loadUserByToken("tok")).thenReturn(user(5L, "ins", "A", 4));
mvc.perform(get("/api/admin/me")).andExpect(jsonPath("$.companyId").value(5))
.andExpect(jsonPath("$.companyCode").value("ins")).andExpect(jsonPath("$.isSuper").value(false))
.andExpect(jsonPath("$.username").value("john@ins"));
}
@Test
void forgotPassword_buildsLoginName_andIgnoresAtSign() throws Exception {
mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON)
.content("{\"company\":\"INS\",\"username\":\"john\",\"email\":\"j@x.com\"}"))
.andExpect(status().isOk()).andExpect(jsonPath("$.result").value("true"));
verify(auth).resetAdminPassword("john@ins", "j@x.com");
mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON)
.content("{\"company\":\"ins\",\"username\":\"a@b\",\"email\":\"j@x.com\"}")).andExpect(status().isOk());
verify(auth, never()).resetAdminPassword(org.mockito.ArgumentMatchers.eq("a@b@ins"), anyString());
}
}
@@ -0,0 +1,120 @@
package com.solvway.mobile.api.controller.admin;
import com.solvway.core.annotation.AppAuth;
import com.solvway.core.model.Role;
import com.solvway.core.model.User;
import com.solvway.core.utils.HttpReqRespUtils;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.service.AdminAuthenticationService;
import com.solvway.mobile.api.service.AdminCompanyService;
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verifyNoInteractions;
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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ExtendWith(MockitoExtension.class)
class AdminCompanyControllerTest {
@Mock private AdminCompanyService companies;
@Mock private AdminAuthenticationService auth;
private MockMvc mvc;
private MockedStatic<HttpReqRespUtils> http;
private static final String BODY = "{\"name\":\"Ins\",\"code\":\"ins\",\"status\":\"A\"}";
@BeforeEach
void setUp() {
mvc = MockMvcBuilders.standaloneSetup(new AdminCompanyController(companies, auth, new AdminCompanyScope())).build();
http = mockStatic(HttpReqRespUtils.class);
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
}
@AfterEach
void close() { http.close(); }
private void caller(Long companyId, long roleId) {
User u = new User();
u.setCompanyId(companyId);
Role r = new Role("R");
r.setId(roleId);
u.setRoles(List.of(r));
when(auth.loadUserByToken("tok")).thenReturn(u);
}
private static CodedResponseStatusException coded(HttpStatus s, String reason) {
return new CodedResponseStatusException(s, reason, "X");
}
@Test
void everyHandlerIsAuthenticated() {
for (Method m : AdminCompanyController.class.getDeclaredMethods()) {
if (m.isSynthetic() || !java.lang.reflect.Modifier.isPublic(m.getModifiers())) continue;
if (m.getName().equals("upstream")) continue;
assertThat(m.isAnnotationPresent(AppAuth.class)).as(m.getName()).isTrue();
}
}
@Test
void companyStaff_get403_onEveryHandler_andNothingIsCalled() throws Exception {
caller(5L, 1);
mvc.perform(get("/api/admin/companies")).andExpect(status().isForbidden());
mvc.perform(get("/api/admin/companies/1")).andExpect(status().isForbidden());
mvc.perform(post("/api/admin/companies").contentType(MediaType.APPLICATION_JSON).content(BODY)).andExpect(status().isForbidden());
mvc.perform(post("/api/admin/companies/1/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"x1\"}"))
.andExpect(status().isForbidden());
verifyNoInteractions(companies);
}
@Test
void superAdmin_listsGetsAndSaves() throws Exception {
caller(null, 1);
when(companies.list()).thenReturn(List.of(Map.of("id", 1, "name", "Ins", "code", "ins", "status", "A")));
when(companies.get(1L)).thenReturn(Map.of("id", 1, "code", "ins"));
when(companies.save(any())).thenReturn(Map.of("id", 2, "code", "cv"));
when(companies.renameCode(1L, "new1")).thenReturn(Map.of("id", 1, "code", "new1"));
mvc.perform(get("/api/admin/companies")).andExpect(status().isOk()).andExpect(jsonPath("$[0].code").value("ins"));
mvc.perform(get("/api/admin/companies/1")).andExpect(jsonPath("$.code").value("ins"));
mvc.perform(post("/api/admin/companies").contentType(MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isOk()).andExpect(jsonPath("$.code").value("cv"));
mvc.perform(post("/api/admin/companies/1/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"new1\"}"))
.andExpect(jsonPath("$.code").value("new1"));
}
@Test
void upstream400_409_404_areMappedWithMessage() throws Exception {
caller(null, 1);
when(companies.save(any())).thenThrow(coded(HttpStatus.BAD_REQUEST, "Name is required"));
mvc.perform(post("/api/admin/companies").contentType(MediaType.APPLICATION_JSON).content(BODY))
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("Name is required"));
when(companies.renameCode(1L, "taken")).thenThrow(coded(HttpStatus.CONFLICT, "Code is already taken"));
mvc.perform(post("/api/admin/companies/1/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"taken\"}"))
.andExpect(status().isConflict()).andExpect(jsonPath("$.message").value("Code is already taken"));
when(companies.get(9L)).thenThrow(coded(HttpStatus.NOT_FOUND, "Company not found"));
mvc.perform(get("/api/admin/companies/9")).andExpect(status().isNotFound())
.andExpect(jsonPath("$.message").value("Company not found"));
}
}
@@ -0,0 +1,59 @@
package com.solvway.mobile.api.service;
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
import org.junit.jupiter.api.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpClientErrorException;
import java.nio.charset.StandardCharsets;
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.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
class AdminCompanyServiceTest {
private final RestTemplateCustomUtil rest = mock(RestTemplateCustomUtil.class);
private final AdminCompanyService service = new AdminCompanyService(rest);
private static HttpClientErrorException upstream(HttpStatus s, String body) {
return HttpClientErrorException.create(s, s.name(), null, body.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
private void assertCoded(Runnable call, HttpStatus status, String message) {
assertThatThrownBy(call::run).isInstanceOf(CodedResponseStatusException.class).satisfies(ex -> {
CodedResponseStatusException c = (CodedResponseStatusException) ex;
assertThat(c.getStatusCode()).isEqualTo(status);
assertThat(c.getReason()).isEqualTo(message);
});
}
@Test
void upstream400_409_404_becomeCodedExceptions() {
when(rest.getURLforApiService(any())).thenAnswer(i -> i.getArgument(0));
when(rest.postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()))
.thenThrow(upstream(HttpStatus.BAD_REQUEST, "{\"message\":\"Name is required\"}"));
assertCoded(() -> service.save(Map.of("name", "")), HttpStatus.BAD_REQUEST, "Name is required");
when(rest.postForEntity(any(String.class), any(ParameterizedTypeReference.class), any()))
.thenThrow(upstream(HttpStatus.CONFLICT, ""));
assertCoded(() -> service.renameCode(1L, "taken"), HttpStatus.CONFLICT, "Code is already taken");
when(rest.getForEntity(any(String.class), any(ParameterizedTypeReference.class))).thenThrow(upstream(HttpStatus.NOT_FOUND, ""));
assertCoded(() -> service.get(9L), HttpStatus.NOT_FOUND, "Company not found");
}
@Test
void blankOrMissingCode_is400_beforeAnyDownstreamCall() {
assertCoded(() -> service.renameCode(1L, null), HttpStatus.BAD_REQUEST, "Code is required");
assertCoded(() -> service.renameCode(1L, " "), HttpStatus.BAD_REQUEST, "Code is required");
verifyNoMoreInteractions(rest);
}
}
@@ -0,0 +1,69 @@
package com.solvway.mobile.api.useraccess;
import com.solvway.core.model.Role;
import com.solvway.core.model.User;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
class AdminCompanyScopeTest {
private final AdminCompanyScope scope = new AdminCompanyScope();
private static User user(Long companyId, long... roleIds) {
User u = new User();
u.setCompanyId(companyId);
u.setRoles(java.util.Arrays.stream(roleIds).mapToObj(id -> {
Role r = new Role("R" + id);
r.setId(id);
return r;
}).toList());
return u;
}
private static void assertStatus(Runnable call, HttpStatus expected) {
assertThatThrownBy(call::run).isInstanceOf(ResponseStatusException.class)
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(expected));
}
@Test
void isSuper_needsNoCompanyAndRoleOne() {
assertThat(AdminCompanyScope.isSuper(user(null, 1))).isTrue();
assertThat(AdminCompanyScope.isSuper(user(5L, 1))).isFalse();
assertThat(AdminCompanyScope.isSuper(user(null, 2, 4))).isFalse();
assertThat(AdminCompanyScope.isSuper(user(null))).isFalse();
}
@Test
void scope_staffIgnoresRequest_superGetsRequestedOrNull() {
assertThat(scope.scope(user(5L, 4), 9L)).isEqualTo(5L);
assertThat(scope.scope(user(5L, 4), null)).isEqualTo(5L);
assertThat(scope.scope(user(null, 1), 9L)).isEqualTo(9L);
assertThat(scope.scope(user(null, 1), null)).isNull();
}
@Test
void requireCompanyForCreate_staffOwn_superRequestedOr400() {
assertThat(scope.requireCompanyForCreate(user(5L, 4), 9L)).isEqualTo(5L);
assertThat(scope.requireCompanyForCreate(user(null, 1), 9L)).isEqualTo(9L);
assertThatThrownBy(() -> scope.requireCompanyForCreate(user(null, 1), null))
.isInstanceOf(ResponseStatusException.class)
.satisfies(ex -> {
ResponseStatusException e = (ResponseStatusException) ex;
assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
assertThat(e.getBody().getProperties()).containsEntry("message", "Choose a company.");
});
}
@Test
void requireSuper_forbidsStaff() {
scope.requireSuper(user(null, 1));
assertStatus(() -> scope.requireSuper(user(5L, 1)), HttpStatus.FORBIDDEN);
assertStatus(() -> scope.requireSuper(user(null, 4)), HttpStatus.FORBIDDEN);
}
}
@@ -0,0 +1,50 @@
package com.solvway.mobile.api.useraccess;
import com.solvway.core.enums.GeneralEnum.LoginStatus;
import com.solvway.core.model.Role;
import com.solvway.core.model.User;
import com.solvway.mobile.api.service.AdminAuthenticationService;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AdminSessionGuardCompanyTest {
private final AdminAuthenticationService auth = mock(AdminAuthenticationService.class);
private final AdminSessionGuard guard = new AdminSessionGuard(auth);
private static User user(Long companyId, String status, Long roleId) {
User u = new User();
u.setEnabled(true);
u.setLogin(LoginStatus.Y);
u.setCompanyId(companyId);
u.setCompanyStatus(status);
Role r = new Role("R");
r.setId(roleId);
u.setRoles(java.util.List.of(r));
return u;
}
@Test
void inactiveCompany_endsStaffSession() {
when(auth.loadUserByToken("tok")).thenReturn(user(5L, "I", 4L));
assertThatThrownBy(() -> guard.check("tok", false)).isInstanceOf(ResponseStatusException.class)
.satisfies(ex -> {
assertThat(((ResponseStatusException) ex).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
assertThat(((ResponseStatusException) ex).getReason()).isEqualTo("Invalid Token"); // same as a dead session
});
}
@Test
void activeCompany_andSuperAdmin_pass() {
when(auth.loadUserByToken("tok")).thenReturn(user(5L, "A", 4L));
assertThat(guard.check("tok", false)).isNotNull();
when(auth.loadUserByToken("sup")).thenReturn(user(null, null, 1L));
assertThat(guard.check("sup", false)).isNotNull();
}
}