feat: companies API, company on user lookups, company filters for users and login security
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
840b5a3bae
commit
c9c0745955
23 files changed
+1181
-13
No files matched your search
+103
@@ -0,0 +1,103 @@
|
||||
package com.solvway.services.system.controller;
|
||||
|
||||
import com.solvway.services.system.model.Company;
|
||||
import com.solvway.services.system.service.CompanyService;
|
||||
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.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
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 CompanyControllerTest {
|
||||
|
||||
@Mock private CompanyService service;
|
||||
@InjectMocks private CompanyController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
private static Company company(Long id, String name, String code) {
|
||||
Company c = new Company();
|
||||
c.setId(id);
|
||||
c.setName(name);
|
||||
c.setCode(code);
|
||||
c.setStatus("A");
|
||||
return c;
|
||||
}
|
||||
|
||||
@Test
|
||||
void findAllReturnsCompanies() throws Exception {
|
||||
when(service.findAll()).thenReturn(List.of(company(2L, "CV", "cv"), company(1L, "INS", "ins")));
|
||||
|
||||
mvc.perform(get("/company/findAll")).andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].code").value("cv")).andExpect(jsonPath("$[1].status").value("A"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByIdAndCode() throws Exception {
|
||||
when(service.findById(1L)).thenReturn(company(1L, "INS", "ins"));
|
||||
when(service.findByCode("INS")).thenReturn(company(1L, "INS", "ins"));
|
||||
|
||||
mvc.perform(get("/company/findById/1")).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("INS"));
|
||||
mvc.perform(get("/company/findByCode/INS")).andExpect(status().isOk()).andExpect(jsonPath("$.id").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveReturnsSavedCompany() throws Exception {
|
||||
when(service.save(any(Company.class))).thenReturn(company(3L, "New", "new"));
|
||||
|
||||
mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"name\":\"New\",\"code\":\"NEW\",\"status\":\"A\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.id").value(3));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidCodeIs400WithMessage() throws Exception {
|
||||
when(service.save(any(Company.class))).thenThrow(new IllegalArgumentException("Code must be 2 to 20 characters"));
|
||||
|
||||
mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"X\",\"code\":\"a\"}"))
|
||||
.andExpect(status().isBadRequest()).andExpect(jsonPath("$.message").value("Code must be 2 to 20 characters"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateCodeIs409() throws Exception {
|
||||
when(service.save(any(Company.class))).thenThrow(new ResponseStatusException(HttpStatus.CONFLICT, "Code is already taken"));
|
||||
|
||||
mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON).content("{\"name\":\"X\",\"code\":\"ins\"}"))
|
||||
.andExpect(status().isConflict());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameCodePostsToService() throws Exception {
|
||||
when(service.renameCode(2L, "cvx")).thenReturn(company(2L, "CV", "cvx"));
|
||||
|
||||
mvc.perform(post("/company/2/code").contentType(MediaType.APPLICATION_JSON).content("{\"code\":\"cvx\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.code").value("cvx"));
|
||||
verify(service).renameCode(2L, "cvx");
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingBodyIs400() throws Exception {
|
||||
mvc.perform(post("/company/save").contentType(MediaType.APPLICATION_JSON).content("")).andExpect(status().isBadRequest());
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.solvway.services.system.controller;
|
||||
|
||||
import com.solvway.services.system.service.LoginSecurityService;
|
||||
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.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
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.status;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class LoginSecurityControllerCompanyTest {
|
||||
|
||||
@Mock private LoginSecurityService service;
|
||||
@InjectMocks private LoginSecurityController controller;
|
||||
private MockMvc mvc;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
mvc = MockMvcBuilders.standaloneSetup(controller).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditPassesCompanyId() throws Exception {
|
||||
when(service.audit(any(), any(), any(), any(), any(), any(), any())).thenReturn(Map.of());
|
||||
|
||||
mvc.perform(post("/loginSecurity/audit").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"bo\",\"from\":\"2025-06-01\",\"page\":1,\"size\":50,\"companyId\":2}"))
|
||||
.andExpect(status().isOk());
|
||||
|
||||
verify(service).audit("bo", null, LocalDate.of(2025, 6, 1), null, 1, 50, 2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedPassesCompanyIdQueryParam() throws Exception {
|
||||
when(service.lockedUsers(2L)).thenReturn(List.of());
|
||||
|
||||
mvc.perform(get("/loginSecurity/locked").param("companyId", "2")).andExpect(status().isOk());
|
||||
|
||||
verify(service).lockedUsers(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockPassesCompanyId() throws Exception {
|
||||
mvc.perform(post("/loginSecurity/unlock").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"a@cv\",\"by\":\"boss\",\"companyId\":2}")).andExpect(status().isOk());
|
||||
|
||||
verify(service).unlock("a@cv", "boss", 2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockOfAnotherCompanysUserIs404() throws Exception {
|
||||
doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "user not found")).when(service).unlock("a@ins", "boss", 2L);
|
||||
|
||||
mvc.perform(post("/loginSecurity/unlock").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"username\":\"a@ins\",\"by\":\"boss\",\"companyId\":2}")).andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.solvway.services.system.controller;
|
||||
|
||||
import com.solvway.core.enums.UserEnum.UserType;
|
||||
import com.solvway.services.system.model.Role;
|
||||
import com.solvway.services.system.model.User;
|
||||
import com.solvway.services.system.service.UserService;
|
||||
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.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
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.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class UserControllerCompanyGuardTest {
|
||||
|
||||
@Mock private UserService userService;
|
||||
@InjectMocks private UserController controller;
|
||||
|
||||
private static User user(UserType type, Long companyId, Long... roleIds) {
|
||||
User u = new User();
|
||||
u.setType(type);
|
||||
u.setCompanyId(companyId);
|
||||
List<Role> roles = new ArrayList<>();
|
||||
for (Long id : roleIds) {
|
||||
Role r = new Role();
|
||||
r.setId(id);
|
||||
roles.add(r);
|
||||
}
|
||||
u.setRoles(roles);
|
||||
return u;
|
||||
}
|
||||
|
||||
private void refused(User u, String message) {
|
||||
assertThatThrownBy(() -> controller.save(u)).isInstanceOfSatisfying(ResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode().value()).isEqualTo(400);
|
||||
assertThat(e.getReason()).contains(message);
|
||||
});
|
||||
verify(userService, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminWithCompanyCannotHoldSuperAdminRole() {
|
||||
refused(user(UserType.A, 2L, 1L, 5L), "super admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void companylessAdminMustHoldSuperAdminRole() {
|
||||
refused(user(UserType.A, null, 5L), "company");
|
||||
}
|
||||
|
||||
@Test
|
||||
void companylessAdminWithRoleOneIsSaved() {
|
||||
when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0));
|
||||
|
||||
assertThat(controller.save(user(UserType.A, null, 1L)).getCompanyId()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminWithCompanyAndOtherRoleIsSaved() {
|
||||
when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0));
|
||||
|
||||
assertThat(controller.save(user(UserType.A, 2L, 5L)).getCompanyId()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void membersAreUnaffected() {
|
||||
when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0));
|
||||
|
||||
assertThat(controller.save(user(UserType.M, null)).getType()).isEqualTo(UserType.M);
|
||||
assertThat(controller.save(user(UserType.M, 2L, 1L)).getCompanyId()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
private void stored(Long id, UserType type, Long companyId, Long... roleIds) {
|
||||
User s = user(type, companyId, roleIds);
|
||||
s.setId(id);
|
||||
when(userService.findById(id)).thenReturn(java.util.Optional.of(s));
|
||||
}
|
||||
|
||||
private static User edit(Long id, UserType type, Long companyId, Long... roleIds) {
|
||||
User u = user(type, companyId, roleIds);
|
||||
u.setId(id);
|
||||
return u;
|
||||
}
|
||||
|
||||
@Test
|
||||
void editOmittingCompanyKeepsStoredCompanyAndRefusesSuperAdminRole() {
|
||||
stored(7L, UserType.A, 2L, 5L);
|
||||
refused(edit(7L, null, null, 1L), "super admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void editOmittingCompanyOfStoredCompanyAdminWithOtherRoleIsSaved() {
|
||||
stored(7L, UserType.A, 2L, 5L);
|
||||
when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0));
|
||||
|
||||
assertThat(controller.save(edit(7L, null, null, 5L))).isNotNull();
|
||||
verify(userService).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void editOmittingTypeOfStoredAdminStillAppliesGuard() {
|
||||
stored(7L, UserType.A, null, 1L);
|
||||
refused(edit(7L, null, null, 5L), "company");
|
||||
}
|
||||
|
||||
@Test
|
||||
void editOmittingRolesKeepsStoredRoles() {
|
||||
stored(7L, UserType.A, null, 1L);
|
||||
when(userService.save(any(User.class))).thenAnswer(i -> i.getArgument(0));
|
||||
User u = edit(7L, UserType.A, null);
|
||||
u.setRoles(null);
|
||||
|
||||
assertThat(controller.save(u)).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailFindersPassTheCompany() {
|
||||
User other = new User();
|
||||
when(userService.findByEmailAndCompanyId("a@x.com", 2L)).thenReturn(other);
|
||||
when(userService.findByEmailAndCompanyIdAndIdNot("a@x.com", null, 9L)).thenReturn(other);
|
||||
|
||||
assertThat(controller.findByEmailAndCompanyId("a@x.com", 2L)).isSameAs(other);
|
||||
assertThat(controller.findByEmailAndCompanyIdAndIdNot("a@x.com", 9L, null)).isSameAs(other);
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.solvway.services.system.model;
|
||||
|
||||
import org.hibernate.annotations.Formula;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class UserCompanyMappingTest {
|
||||
|
||||
@Test
|
||||
void companyCodeAndStatusAreReadOnlyFormulasOverTheCompanyTable() throws Exception {
|
||||
for (String field : new String[]{"companyCode", "companyStatus"}) {
|
||||
Formula f = User.class.getDeclaredField(field).getAnnotation(Formula.class);
|
||||
assertThat(f).as(field).isNotNull();
|
||||
assertThat(f.value()).contains("from company c where c.id = company_id");
|
||||
}
|
||||
assertThat(User.class.getDeclaredField("companyCode").getAnnotation(Formula.class).value()).contains("c.code");
|
||||
assertThat(User.class.getDeclaredField("companyStatus").getAnnotation(Formula.class).value()).contains("c.status");
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.solvway.services.system.repo;
|
||||
|
||||
import com.solvway.services.system.model.User;
|
||||
import com.solvway.services.system.util.paging.PageableRest;
|
||||
import jakarta.persistence.EntityManager;
|
||||
import jakarta.persistence.TypedQuery;
|
||||
import jakarta.persistence.criteria.CriteriaBuilder;
|
||||
import jakarta.persistence.criteria.CriteriaQuery;
|
||||
import jakarta.persistence.criteria.Path;
|
||||
import jakarta.persistence.criteria.Root;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Answers;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
class UserRepositoryImplCompanyTest {
|
||||
|
||||
private final EntityManager em = mock(EntityManager.class);
|
||||
private final CriteriaBuilder cb = mock(CriteriaBuilder.class);
|
||||
private final Path companyPath = mock(Path.class);
|
||||
private UserRepositoryImpl repo;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
CriteriaQuery<User> cq = mock(CriteriaQuery.class, Answers.RETURNS_SELF);
|
||||
CriteriaQuery<Long> count = mock(CriteriaQuery.class, Answers.RETURNS_SELF);
|
||||
Root<User> root = mock(Root.class);
|
||||
Root<User> rootCount = mock(Root.class);
|
||||
TypedQuery q = mock(TypedQuery.class, Answers.RETURNS_SELF);
|
||||
TypedQuery<Long> qc = mock(TypedQuery.class);
|
||||
when(qc.getSingleResult()).thenReturn(0L);
|
||||
when(em.getCriteriaBuilder()).thenReturn(cb);
|
||||
when(cb.createQuery(User.class)).thenReturn(cq);
|
||||
when(cb.createQuery(Long.class)).thenReturn(count);
|
||||
when(cq.from(User.class)).thenReturn(root);
|
||||
when(count.from(User.class)).thenReturn(rootCount);
|
||||
when(root.get("companyId")).thenReturn(companyPath);
|
||||
when(rootCount.get("companyId")).thenReturn(companyPath);
|
||||
when(em.createQuery(cq)).thenReturn(q);
|
||||
when(em.createQuery(count)).thenReturn(qc);
|
||||
repo = new UserRepositoryImpl();
|
||||
repo.em = em;
|
||||
}
|
||||
|
||||
private static PageableRest page() {
|
||||
PageableRest p = new PageableRest();
|
||||
p.setNumber(0);
|
||||
p.setSize(10);
|
||||
PageableRest.SortRest sort = new PageableRest.SortRest();
|
||||
sort.setDirection("ASC");
|
||||
sort.setProperty("name");
|
||||
p.setSorts(new java.util.ArrayList<>(java.util.List.of(sort)));
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
void companyIdFiltersListAndCount() {
|
||||
HashMap<String, String> property = new HashMap<>();
|
||||
property.put("companyId", "2");
|
||||
|
||||
repo.findByPropertyAndPageable(property, page());
|
||||
|
||||
verify(cb, times(2)).equal(companyPath, 2L); // data query and count query
|
||||
}
|
||||
|
||||
@Test
|
||||
void withoutCompanyIdNothingIsFiltered() {
|
||||
repo.findByPropertyAndPageable(new HashMap<>(), page());
|
||||
|
||||
verify(cb, never()).equal(any(), any(Object.class));
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package com.solvway.services.system.service;
|
||||
|
||||
import com.solvway.core.enums.UserEnum.UserType;
|
||||
import com.solvway.services.system.model.Company;
|
||||
import com.solvway.services.system.model.User;
|
||||
import com.solvway.services.system.repo.CompanyRepository;
|
||||
import com.solvway.services.system.repo.UserRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
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.doThrow;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class CompanyServiceTest {
|
||||
|
||||
@Mock private CompanyRepository companies;
|
||||
@Mock private UserRepository users;
|
||||
private CompanyService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new CompanyService(companies, users);
|
||||
when(companies.save(any(Company.class))).thenAnswer(i -> i.getArgument(0));
|
||||
}
|
||||
|
||||
private static Company company(Long id, String name, String code, String status) {
|
||||
Company c = new Company();
|
||||
c.setId(id);
|
||||
c.setName(name);
|
||||
c.setCode(code);
|
||||
c.setStatus(status);
|
||||
return c;
|
||||
}
|
||||
|
||||
private static User admin(Long id, String username) {
|
||||
User u = new User();
|
||||
u.setId(id);
|
||||
u.setUsername(username);
|
||||
u.setType(UserType.A);
|
||||
return u;
|
||||
}
|
||||
|
||||
@Test
|
||||
void listsAllOrderedByName() {
|
||||
List<Company> all = List.of(company(2L, "CV", "cv", "A"), company(1L, "INS", "ins", "A"));
|
||||
when(companies.findAllByOrderByNameAsc()).thenReturn(all);
|
||||
|
||||
assertThat(service.findAll()).isSameAs(all);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createLowercasesCodeAndDefaultsToActive() {
|
||||
Company saved = service.save(company(null, " CV ", " CV-2 ", null));
|
||||
|
||||
assertThat(saved.getName()).isEqualTo("CV");
|
||||
assertThat(saved.getCode()).isEqualTo("cv-2");
|
||||
assertThat(saved.getStatus()).isEqualTo("A");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateCodeIgnoringCaseIsRefused() {
|
||||
when(companies.findByCodeIgnoreCase("ins")).thenReturn(Optional.of(company(1L, "INS", "ins", "A")));
|
||||
|
||||
assertThatThrownBy(() -> service.save(company(null, "Other", "INS", "A")))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(409));
|
||||
verify(companies, never()).save(any());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "a", "UPPER_case", "has space", "under_score", "abcdefghijklmnopqrstu"})
|
||||
void badCodeFormatIsRefused(String code) {
|
||||
assertThatThrownBy(() -> service.save(company(null, "X", code, "A"))).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(companies, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameIsRequiredAndStatusMustBeAOrI() {
|
||||
assertThatThrownBy(() -> service.save(company(null, " ", "ok", "A"))).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThatThrownBy(() -> service.save(company(null, "X", "ok", "Z"))).isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void editChangesNameAndStatusButNotCode() {
|
||||
Company existing = company(2L, "CV", "cv", "A");
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(existing));
|
||||
|
||||
Company saved = service.save(company(2L, "CV Ltd", "other", "I"));
|
||||
|
||||
assertThat(saved.getName()).isEqualTo("CV Ltd");
|
||||
assertThat(saved.getStatus()).isEqualTo("I");
|
||||
assertThat(saved.getCode()).isEqualTo("cv");
|
||||
}
|
||||
|
||||
@Test
|
||||
void editOfUnknownCompanyIs404() {
|
||||
when(companies.findById(9L)).thenReturn(Optional.empty());
|
||||
|
||||
assertThatThrownBy(() -> service.save(company(9L, "X", "xx", "A")))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404));
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameCodeRewritesOnlyThatCompanysAdminUsernames() throws Exception {
|
||||
Company cv = company(2L, "CV", "cv", "A");
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(cv));
|
||||
User a = admin(10L, "sales@cv");
|
||||
User b = admin(11L, "odd@name@cv"); // last '@' splits local from code
|
||||
when(users.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(a, b));
|
||||
|
||||
Company renamed = service.renameCode(2L, "CVX");
|
||||
|
||||
assertThat(renamed.getCode()).isEqualTo("cvx");
|
||||
assertThat(a.getUsername()).isEqualTo("sales@cvx");
|
||||
assertThat(b.getUsername()).isEqualTo("odd@name@cvx");
|
||||
verify(users).findByCompanyIdAndType(2L, UserType.A); // only that company, only admins
|
||||
verify(users).saveAll(List.of(a, b));
|
||||
// one transaction: company update and username rewrite share one @Transactional method
|
||||
assertThat(CompanyService.class.getMethod("renameCode", Long.class, String.class)
|
||||
.isAnnotationPresent(Transactional.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameToTakenCodeIsRefusedAndRewritesNothing() {
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(company(2L, "CV", "cv", "A")));
|
||||
when(companies.findByCodeIgnoreCase("ins")).thenReturn(Optional.of(company(1L, "INS", "ins", "A")));
|
||||
|
||||
assertThatThrownBy(() -> service.renameCode(2L, "INS")).isInstanceOf(ResponseStatusException.class);
|
||||
verify(users, never()).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRaceOnUniqueCodeIs409() {
|
||||
when(companies.save(any(Company.class))).thenThrow(new DataIntegrityViolationException("uk_company_code"));
|
||||
|
||||
assertThatThrownBy(() -> service.save(company(null, "New", "new", "A")))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> {
|
||||
assertThat(e.getStatusCode().value()).isEqualTo(409);
|
||||
assertThat(e.getReason()).isEqualTo("Code is already taken");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameRaceOnUniqueCodeIs409() {
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(company(2L, "CV", "cv", "A")));
|
||||
doThrow(new DataIntegrityViolationException("uk_company_code")).when(companies).flush();
|
||||
|
||||
assertThatThrownBy(() -> service.renameCode(2L, "cvx"))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(409));
|
||||
verify(users, never()).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameThatOverflowsUsernameColumnIsRefusedBeforeAnyWrite() {
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(company(2L, "CV", "cv", "A")));
|
||||
User longName = admin(10L, "x".repeat(252) + "@cv"); // 255 now, 256 after rename to cvx
|
||||
when(users.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of(longName));
|
||||
|
||||
assertThatThrownBy(() -> service.renameCode(2L, "cvx")).isInstanceOf(IllegalArgumentException.class);
|
||||
assertThat(longName.getUsername()).endsWith("@cv");
|
||||
verify(companies, never()).save(any());
|
||||
verify(users, never()).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameToBadCodeIsRefused() {
|
||||
assertThatThrownBy(() -> service.renameCode(2L, "Bad Code")).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(users, never()).saveAll(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renameToOwnCodeIgnoringCaseIsAllowed() {
|
||||
Company cv = company(2L, "CV", "cv", "A");
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(cv));
|
||||
when(companies.findByCodeIgnoreCase("cv")).thenReturn(Optional.of(cv));
|
||||
when(users.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of());
|
||||
|
||||
assertThat(service.renameCode(2L, "CV").getCode()).isEqualTo("cv");
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByCodeIgnoresCase() {
|
||||
Company ins = company(1L, "INS", "ins", "A");
|
||||
when(companies.findByCodeIgnoreCase("INS")).thenReturn(Optional.of(ins));
|
||||
|
||||
assertThat(service.findByCode("INS")).isSameAs(ins);
|
||||
}
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package com.solvway.services.system.service;
|
||||
|
||||
import com.solvway.services.system.model.LoginAudit;
|
||||
import com.solvway.services.system.model.PasswordRuleProperty;
|
||||
import com.solvway.services.system.model.User;
|
||||
import com.solvway.services.system.repo.LoginAuditRepository;
|
||||
import com.solvway.services.system.repo.PasswordRuleRepository;
|
||||
import com.solvway.services.system.repo.UserRepository;
|
||||
import com.solvway.services.system.service.LoginSecurityService.Locked;
|
||||
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.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
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.anyList;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class LoginSecurityServiceCompanyTest {
|
||||
|
||||
private static final LocalDateTime NOW = LocalDateTime.of(2025, 6, 15, 12, 0);
|
||||
|
||||
@Mock private LoginAuditRepository audits;
|
||||
@Mock private UserRepository users;
|
||||
@Mock private PasswordRuleRepository properties;
|
||||
private LoginSecurityService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new LoginSecurityService(audits, users, properties);
|
||||
service.clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
private static PasswordRuleProperty prop(String param, String type, String status, String value) {
|
||||
PasswordRuleProperty p = new PasswordRuleProperty();
|
||||
p.setParam(param);
|
||||
p.setType(type);
|
||||
p.setStatus(status);
|
||||
p.setValue(value);
|
||||
return p;
|
||||
}
|
||||
|
||||
private void lockoutOn() { // 3 failures in 10 minutes
|
||||
when(properties.findByType("ADMIN_LOGIN_BLOCK")).thenReturn(List.of(
|
||||
prop("ADMIN_LOGIN_BLOCK_PERIOD", "ADMIN_LOGIN_BLOCK", "Y", "10"),
|
||||
prop("ADMIN_LOGIN_MAX_ATTEMPT", "ADMIN_LOGIN_BLOCK", "Y", "3")));
|
||||
when(properties.findByType("ADMIN_LOGIN_BLOCK_TIME_UNIT")).thenReturn(List.of(
|
||||
prop("ADMIN_LOGIN_BLOCK_TIME_UNIT", "ADMIN_LOGIN_BLOCK_TIME_UNIT", "Y", "M")));
|
||||
}
|
||||
|
||||
private static LoginAudit fail(LocalDateTime at) {
|
||||
LoginAudit a = new LoginAudit();
|
||||
a.setEvent("LOGIN_FAIL");
|
||||
a.setDatetime(at);
|
||||
return a;
|
||||
}
|
||||
|
||||
private void threeFailures(String username) {
|
||||
when(audits.findFirstByUsernameAndEventInOrderByDatetimeDescIdDesc(eq(username), anyList())).thenReturn(Optional.empty());
|
||||
when(audits.findByUsernameAndEventAndDatetimeAfterOrderByDatetimeAscIdAsc(eq(username), eq("LOGIN_FAIL"), any()))
|
||||
.thenReturn(List.of(fail(NOW.minusMinutes(3)), fail(NOW.minusMinutes(2)), fail(NOW.minusMinutes(1))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedUsersOfACompanyUseOnlyThatCompanysFailures() {
|
||||
lockoutOn();
|
||||
threeFailures("a@cv");
|
||||
when(audits.findUsernamesWithFailuresAfterInCompany(NOW.minusMinutes(10), 2L)).thenReturn(List.of("a@cv"));
|
||||
|
||||
assertThat(service.lockedUsers(2L)).extracting(Locked::username).containsExactly("a@cv");
|
||||
verify(audits, never()).findUsernamesWithFailuresAfter(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockedUsersWithoutCompanyIncludeEveryRowEvenNullCompany() {
|
||||
lockoutOn();
|
||||
threeFailures("admin");
|
||||
when(audits.findUsernamesWithFailuresAfter(NOW.minusMinutes(10))).thenReturn(List.of("admin"));
|
||||
|
||||
assertThat(service.lockedUsers(null)).extracting(Locked::username).containsExactly("admin");
|
||||
verify(audits, never()).findUsernamesWithFailuresAfterInCompany(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditOfACompanyFiltersByCompanyId() {
|
||||
when(audits.searchInCompany(any(), any(), any(), any(), eq(2L), any(Pageable.class))).thenReturn(new PageImpl<>(List.of(fail(NOW))));
|
||||
|
||||
assertThat(service.audit("bo", "LOGIN_FAIL", null, null, 0, 20, 2L)).containsEntry("totalElements", 1L);
|
||||
verify(audits).searchInCompany(eq("%bo%"), eq("LOGIN_FAIL"), eq(null), eq(null), eq(2L), any(Pageable.class));
|
||||
verify(audits, never()).search(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditWithoutCompanyIsTheUnfilteredSearch() {
|
||||
when(audits.search(any(), any(), any(), any(), any())).thenReturn(Page.empty());
|
||||
|
||||
service.audit(null, null, null, null, null, null, null);
|
||||
|
||||
verify(audits).search(eq(null), eq(null), eq(null), eq(null), any(Pageable.class));
|
||||
verify(audits, never()).searchInCompany(any(), any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockOfAnotherCompanysUsernameIs404AndWritesNothing() {
|
||||
User u = new User();
|
||||
u.setCompanyId(1L);
|
||||
when(users.findByUsername("a@ins")).thenReturn(u);
|
||||
|
||||
assertThatThrownBy(() -> service.unlock("a@ins", "boss", 2L))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(404));
|
||||
verify(audits, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockOfUnknownUsernameWithCompanyIs404() {
|
||||
assertThatThrownBy(() -> service.unlock("ghost@cv", "boss", 2L)).isInstanceOf(ResponseStatusException.class);
|
||||
verify(audits, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unlockOfOwnCompanysUsernameWritesResetRowWithThatCompany() {
|
||||
User u = new User();
|
||||
u.setCompanyId(2L);
|
||||
when(users.findByUsername("a@cv")).thenReturn(u);
|
||||
|
||||
service.unlock(" a@cv ", "boss", 2L);
|
||||
|
||||
ArgumentCaptor<LoginAudit> c = ArgumentCaptor.forClass(LoginAudit.class);
|
||||
verify(audits).save(c.capture());
|
||||
assertThat(c.getValue().getUsername()).isEqualTo("a@cv");
|
||||
assertThat(c.getValue().getEvent()).isEqualTo("UNLOCK_RESET");
|
||||
assertThat(c.getValue().getCompanyId()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void auditRowsTakeTheCompanyOfTheUserFoundByTheFullLoginName() {
|
||||
User u = new User();
|
||||
u.setCompanyId(2L);
|
||||
when(users.findByUsername("a@cv")).thenReturn(u);
|
||||
|
||||
service.record("a@cv", "LOGIN_FAIL", null, null, null);
|
||||
|
||||
verify(users).findByUsername("a@cv");
|
||||
ArgumentCaptor<LoginAudit> c = ArgumentCaptor.forClass(LoginAudit.class);
|
||||
verify(audits).save(c.capture());
|
||||
assertThat(c.getValue().getCompanyId()).isEqualTo(2L);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.solvway.services.system.service;
|
||||
|
||||
import com.solvway.core.enums.UserEnum.UserType;
|
||||
import com.solvway.services.system.model.User;
|
||||
import com.solvway.services.system.repo.UserRepository;
|
||||
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 static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoMoreInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserServiceCompanyTest {
|
||||
|
||||
@Mock private UserRepository repo;
|
||||
@InjectMocks private UserService service;
|
||||
|
||||
@Test
|
||||
void emailIsCheckedWithinTheGivenCompany() {
|
||||
User other = new User();
|
||||
when(repo.findByEmailAndCompanyIdAndType("a@x.com", 2L, UserType.A)).thenReturn(other);
|
||||
|
||||
assertThat(service.findByEmailAndCompanyId("a@x.com", 2L)).isSameAs(other);
|
||||
verify(repo).findByEmailAndCompanyIdAndType("a@x.com", 2L, UserType.A);
|
||||
verifyNoMoreInteractions(repo);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullCompanyComparesAmongCompanylessUsers() {
|
||||
User other = new User();
|
||||
when(repo.findByEmailAndCompanyIdIsNullAndType("a@x.com", UserType.A)).thenReturn(other);
|
||||
|
||||
assertThat(service.findByEmailAndCompanyId("a@x.com", null)).isSameAs(other);
|
||||
}
|
||||
|
||||
@Test
|
||||
void emailAndIdNotWithinCompany() {
|
||||
User other = new User();
|
||||
when(repo.findByEmailAndCompanyIdAndTypeAndIdNot("a@x.com", 2L, UserType.A, 9L)).thenReturn(other);
|
||||
when(repo.findByEmailAndCompanyIdIsNullAndTypeAndIdNot("a@x.com", UserType.A, 9L)).thenReturn(null);
|
||||
|
||||
assertThat(service.findByEmailAndCompanyIdAndIdNot("a@x.com", 2L, 9L)).isSameAs(other);
|
||||
assertThat(service.findByEmailAndCompanyIdAndIdNot("a@x.com", null, 9L)).isNull();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user