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

@@ -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"));
}
}