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
@@ -16,7 +16,7 @@ Design: `design.md`. All tasks run serially, ordered so that sign-in keeps worki
|
||||
|
||||
## 2. Backend services
|
||||
|
||||
- [ ] 2.1 services-system: companies, users and login security (decisions 1, 2, 3, 5 and 9).
|
||||
- [x] 2.1 services-system: companies, users and login security (decisions 1, 2, 3, 5 and 9).
|
||||
- Tests first:
|
||||
- company list, create, edit; duplicate code (ignoring case) refused; code format validated;
|
||||
- rename-code rewrites only that company's admin usernames, in one transaction;
|
||||
|
||||
@@ -89,6 +89,8 @@ public class User implements Serializable{
|
||||
private String aclHtml;
|
||||
private String uuid;
|
||||
private Long companyId;
|
||||
private String companyCode;
|
||||
private String companyStatus;
|
||||
public User() {
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.solvway.core.model;
|
||||
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class UserCompanyTest {
|
||||
|
||||
private final PubSubUtil util = new PubSubUtil();
|
||||
|
||||
@Test
|
||||
void companyCodeAndStatusRoundTripThroughJson() {
|
||||
User u = new User();
|
||||
u.setCompanyId(2L);
|
||||
u.setCompanyCode("cv");
|
||||
u.setCompanyStatus("A");
|
||||
|
||||
String json = util.convertToString(u);
|
||||
assertThat(json).contains("\"companyCode\":\"cv\"").contains("\"companyStatus\":\"A\"");
|
||||
|
||||
User back = util.convertToOriginalObject(json.getBytes(StandardCharsets.UTF_8), User.class);
|
||||
assertThat(back.getCompanyCode()).isEqualTo("cv");
|
||||
assertThat(back.getCompanyStatus()).isEqualTo("A");
|
||||
assertThat(back.getCompanyId()).isEqualTo(2L);
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.solvway.services.system.controller;
|
||||
|
||||
import com.solvway.services.system.model.Company;
|
||||
import com.solvway.services.system.service.CompanyService;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/company")
|
||||
public class CompanyController {
|
||||
|
||||
private final CompanyService service;
|
||||
|
||||
public CompanyController(CompanyService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping("/findAll")
|
||||
public List<Company> findAll() {
|
||||
return service.findAll();
|
||||
}
|
||||
|
||||
@GetMapping("/findById/{id}")
|
||||
public Company findById(@PathVariable Long id) {
|
||||
return service.findById(id);
|
||||
}
|
||||
|
||||
@GetMapping("/findByCode/{code}")
|
||||
public Company findByCode(@PathVariable String code) {
|
||||
return service.findByCode(code);
|
||||
}
|
||||
|
||||
@PostMapping("/save")
|
||||
public Company save(@RequestBody Company c) {
|
||||
return service.save(c);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/code")
|
||||
public Company renameCode(@PathVariable Long id, @RequestBody Map<String, String> body) {
|
||||
return service.renameCode(id, body.get("code"));
|
||||
}
|
||||
|
||||
@ExceptionHandler({IllegalArgumentException.class, HttpMessageNotReadableException.class})
|
||||
public ResponseEntity<Map<String, String>> badRequest(RuntimeException e) {
|
||||
return ResponseEntity.badRequest().body(Map.of("message", String.valueOf(e.getMessage())));
|
||||
}
|
||||
}
|
||||
+9
-6
@@ -18,8 +18,8 @@ import java.util.Map;
|
||||
public class LoginSecurityController {
|
||||
|
||||
record RecordBody(String username, String event, String ip, String userAgent, String message) {}
|
||||
record AuditBody(String username, String event, String from, String to, Integer page, Integer size) {}
|
||||
record UnlockBody(String username, String by) {}
|
||||
record AuditBody(String username, String event, String from, String to, Integer page, Integer size, Long companyId) {}
|
||||
record UnlockBody(String username, String by, Long companyId) {}
|
||||
|
||||
private final LoginSecurityService service;
|
||||
|
||||
@@ -41,18 +41,21 @@ public class LoginSecurityController {
|
||||
@PostMapping("/audit")
|
||||
public Map<String, Object> audit(@RequestBody AuditBody b) {
|
||||
body(b);
|
||||
return service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size());
|
||||
return b.companyId() == null
|
||||
? service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size())
|
||||
: service.audit(b.username(), b.event(), date(b.from()), date(b.to()), b.page(), b.size(), b.companyId());
|
||||
}
|
||||
|
||||
@GetMapping("/locked")
|
||||
public List<Locked> locked() {
|
||||
return service.lockedUsers();
|
||||
public List<Locked> locked(@RequestParam(required = false) Long companyId) {
|
||||
return companyId == null ? service.lockedUsers() : service.lockedUsers(companyId);
|
||||
}
|
||||
|
||||
@PostMapping("/unlock")
|
||||
public void unlock(@RequestBody UnlockBody b) {
|
||||
body(b);
|
||||
service.unlock(b.username(), b.by());
|
||||
if (b.companyId() == null) service.unlock(b.username(), b.by());
|
||||
else service.unlock(b.username(), b.by(), b.companyId());
|
||||
}
|
||||
|
||||
@GetMapping("/config")
|
||||
|
||||
+24
@@ -239,6 +239,16 @@ public class UserController {
|
||||
return user;
|
||||
}
|
||||
|
||||
@RequestMapping("/findByEmailAndCompanyId/{email}")
|
||||
public User findByEmailAndCompanyId(@PathVariable("email") String email, @org.springframework.web.bind.annotation.RequestParam(value = "companyId", required = false) Long companyId) {
|
||||
return userService.findByEmailAndCompanyId(email, companyId);
|
||||
}
|
||||
|
||||
@RequestMapping("/findByEmailAndCompanyIdAndIdNot/{email}/{id}")
|
||||
public User findByEmailAndCompanyIdAndIdNot(@PathVariable("email") String email, @PathVariable("id") Long id, @org.springframework.web.bind.annotation.RequestParam(value = "companyId", required = false) Long companyId) {
|
||||
return userService.findByEmailAndCompanyIdAndIdNot(email, companyId, id);
|
||||
}
|
||||
|
||||
@RequestMapping("/findByUsernameAndIdNot/{username}/{id}")
|
||||
public User findByUsernameAndIdNot(@PathVariable("username") String username, @PathVariable("id") Long id) {
|
||||
User user = userService.findByUsernameAndIdNot(username, id);
|
||||
@@ -298,6 +308,20 @@ public class UserController {
|
||||
|
||||
@RequestMapping("/save")
|
||||
public User save(@RequestBody User user) {
|
||||
// Guard the EFFECTIVE company and type: an edit that omits them keeps the stored values.
|
||||
User stored = user.getId() == null ? null : userService.findById(user.getId()).orElse(null);
|
||||
Long companyId = user.getCompanyId() != null || stored == null ? user.getCompanyId() : stored.getCompanyId();
|
||||
UserType type = user.getType() != null || stored == null ? user.getType() : stored.getType();
|
||||
if (type == UserType.A) {
|
||||
List<Role> roles = user.getRoles() != null || stored == null ? user.getRoles() : stored.getRoles();
|
||||
boolean superAdmin = roles != null && roles.stream().anyMatch(r -> Long.valueOf(1L).equals(r.getId()));
|
||||
if (companyId != null && superAdmin) {
|
||||
throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.BAD_REQUEST, "A user with a company cannot be a super admin");
|
||||
}
|
||||
if (companyId == null && !superAdmin) {
|
||||
throw new org.springframework.web.server.ResponseStatusException(org.springframework.http.HttpStatus.BAD_REQUEST, "An admin without a company must be a super admin");
|
||||
}
|
||||
}
|
||||
try {
|
||||
if(user.getId()!=null) {
|
||||
User persistedUser = findByIdWithPassword(user.getId());
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.solvway.services.system.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Entity
|
||||
@Table(name = "company")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Company {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String name;
|
||||
|
||||
private String code;
|
||||
|
||||
/** A active, I inactive. */
|
||||
private String status;
|
||||
}
|
||||
@@ -131,6 +131,12 @@ public class User {
|
||||
|
||||
private Long companyId;
|
||||
|
||||
@org.hibernate.annotations.Formula("(select c.code from company c where c.id = company_id)")
|
||||
private String companyCode;
|
||||
|
||||
@org.hibernate.annotations.Formula("(select c.status from company c where c.id = company_id)")
|
||||
private String companyStatus;
|
||||
|
||||
|
||||
@Transient
|
||||
private List<String> linkedAccounts;
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.solvway.services.system.repo;
|
||||
|
||||
import com.solvway.services.system.model.Company;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface CompanyRepository extends JpaRepository<Company, Long> {
|
||||
|
||||
List<Company> findAllByOrderByNameAsc();
|
||||
|
||||
Optional<Company> findByCodeIgnoreCase(String code);
|
||||
}
|
||||
+12
@@ -23,6 +23,18 @@ public interface LoginAuditRepository extends JpaRepository<LoginAudit, Long> {
|
||||
@Query("SELECT DISTINCT a.username FROM LoginAudit a WHERE a.event = 'LOGIN_FAIL' AND a.datetime > :since")
|
||||
List<String> findUsernamesWithFailuresAfter(@Param("since") LocalDateTime since);
|
||||
|
||||
@Query("SELECT DISTINCT a.username FROM LoginAudit a WHERE a.event = 'LOGIN_FAIL' AND a.datetime > :since AND a.companyId = :companyId")
|
||||
List<String> findUsernamesWithFailuresAfterInCompany(@Param("since") LocalDateTime since, @Param("companyId") Long companyId);
|
||||
|
||||
@Query("SELECT a FROM LoginAudit a WHERE (:pattern IS NULL OR a.username LIKE :pattern) "
|
||||
+ "AND (:event IS NULL OR a.event = :event) "
|
||||
+ "AND (:from IS NULL OR a.datetime >= :from) "
|
||||
+ "AND (:toExclusive IS NULL OR a.datetime < :toExclusive) "
|
||||
+ "AND a.companyId = :companyId")
|
||||
Page<LoginAudit> searchInCompany(@Param("pattern") String pattern, @Param("event") String event,
|
||||
@Param("from") LocalDateTime from, @Param("toExclusive") LocalDateTime toExclusive,
|
||||
@Param("companyId") Long companyId, Pageable pageable);
|
||||
|
||||
/** Null arguments are ignored; {@code pattern} is a LIKE pattern, {@code toExclusive} an exclusive upper bound. */
|
||||
@Query("SELECT a FROM LoginAudit a WHERE (:pattern IS NULL OR a.username LIKE :pattern) "
|
||||
+ "AND (:event IS NULL OR a.event = :event) "
|
||||
|
||||
+10
@@ -24,6 +24,16 @@ public interface UserRepository extends JpaRepository<User, Long>, JpaRepository
|
||||
|
||||
User findByEmailAndIdNot(String email, Long id);
|
||||
|
||||
User findByEmailAndCompanyIdAndType(String email, Long companyId, com.solvway.core.enums.UserEnum.UserType type);
|
||||
|
||||
User findByEmailAndCompanyIdIsNullAndType(String email, com.solvway.core.enums.UserEnum.UserType type);
|
||||
|
||||
User findByEmailAndCompanyIdAndTypeAndIdNot(String email, Long companyId, com.solvway.core.enums.UserEnum.UserType type, Long id);
|
||||
|
||||
User findByEmailAndCompanyIdIsNullAndTypeAndIdNot(String email, com.solvway.core.enums.UserEnum.UserType type, Long id);
|
||||
|
||||
java.util.List<User> findByCompanyIdAndType(Long companyId, com.solvway.core.enums.UserEnum.UserType type);
|
||||
|
||||
User findByUsernameAndIdNot(String username, Long id);
|
||||
|
||||
Page<User> findByUsernameContainingOrderByIdAsc(String username, Pageable pageable);
|
||||
|
||||
+4
@@ -73,6 +73,10 @@ public class UserRepositoryImpl implements JpaRepositoryCustom<User>{
|
||||
predicates.add(cb.equal(root.get(k), UserType.valueOf(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get(k), UserType.valueOf(value)));
|
||||
}
|
||||
case "companyId" -> {
|
||||
predicates.add(cb.equal(root.get("companyId"), Long.valueOf(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get("companyId"), Long.valueOf(value)));
|
||||
}
|
||||
case "userGroupId" -> {
|
||||
predicates.add(cb.equal(root.get("userGroup").get("id"), Long.valueOf(value)));
|
||||
predicatesCount.add(cb.equal(rootCount.get("userGroup").get("id"), Long.valueOf(value)));
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
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.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Service
|
||||
public class CompanyService {
|
||||
|
||||
private static final int USERNAME_MAX = 255; // user.username column length
|
||||
private static final Pattern CODE = Pattern.compile("^[a-z0-9-]{2,20}$");
|
||||
|
||||
private final CompanyRepository companies;
|
||||
private final UserRepository users;
|
||||
|
||||
public CompanyService(CompanyRepository companies, UserRepository users) {
|
||||
this.companies = companies;
|
||||
this.users = users;
|
||||
}
|
||||
|
||||
public List<Company> findAll() {
|
||||
return companies.findAllByOrderByNameAsc();
|
||||
}
|
||||
|
||||
public Company findById(Long id) {
|
||||
return companies.findById(id).orElse(null);
|
||||
}
|
||||
|
||||
public Company findByCode(String code) {
|
||||
return companies.findByCodeIgnoreCase(code).orElse(null);
|
||||
}
|
||||
|
||||
/** Create (id null) or edit name and status; the code of an existing company changes only through renameCode. */
|
||||
@Transactional
|
||||
public Company save(Company in) {
|
||||
String name = in.getName() == null ? "" : in.getName().trim();
|
||||
if (name.isEmpty()) throw new IllegalArgumentException("Name is required");
|
||||
String status = in.getStatus() == null ? "A" : in.getStatus();
|
||||
if (!status.equals("A") && !status.equals("I")) throw new IllegalArgumentException("Status must be A or I");
|
||||
if (in.getId() == null) {
|
||||
Company c = new Company();
|
||||
c.setName(name);
|
||||
c.setStatus(status);
|
||||
c.setCode(freeCode(in.getCode(), null));
|
||||
return saveUnique(c);
|
||||
}
|
||||
Company c = companies.findById(in.getId()).orElseThrow(() -> notFound());
|
||||
c.setName(name);
|
||||
c.setStatus(status);
|
||||
return saveUnique(c);
|
||||
}
|
||||
|
||||
/** Changes the code and the login name (local@code) of every admin of the company, atomically. */
|
||||
@Transactional
|
||||
public Company renameCode(Long id, String code) {
|
||||
String newCode = validCode(code);
|
||||
Company c = companies.findById(id).orElseThrow(() -> notFound());
|
||||
c.setCode(freeCode(newCode, id));
|
||||
List<User> admins = users.findByCompanyIdAndType(id, UserType.A);
|
||||
for (User u : admins) {
|
||||
String name = u.getUsername();
|
||||
String renamed = name.substring(0, name.lastIndexOf('@') < 0 ? name.length() : name.lastIndexOf('@')) + "@" + newCode;
|
||||
if (renamed.length() > USERNAME_MAX) throw new IllegalArgumentException("Login name too long for " + name + " with the new code");
|
||||
u.setUsername(renamed);
|
||||
}
|
||||
saveUnique(c);
|
||||
users.saveAll(admins);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** Flushes so a unique-key race on code surfaces here as 409, not at commit. */
|
||||
private Company saveUnique(Company c) {
|
||||
try {
|
||||
Company saved = companies.save(c);
|
||||
companies.flush();
|
||||
return saved;
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "Code is already taken");
|
||||
}
|
||||
}
|
||||
|
||||
private String freeCode(String code, Long ownId) {
|
||||
String v = validCode(code);
|
||||
companies.findByCodeIgnoreCase(v).filter(o -> !o.getId().equals(ownId))
|
||||
.ifPresent(o -> { throw new ResponseStatusException(HttpStatus.CONFLICT, "Code is already taken"); });
|
||||
return v;
|
||||
}
|
||||
|
||||
private static String validCode(String code) {
|
||||
String v = code == null ? "" : code.trim().toLowerCase();
|
||||
if (!CODE.matcher(v).matches()) throw new IllegalArgumentException("Code must be 2 to 20 characters: a-z, 0-9 or -");
|
||||
return v;
|
||||
}
|
||||
|
||||
private static ResponseStatusException notFound() {
|
||||
return new ResponseStatusException(HttpStatus.NOT_FOUND, "Company not found");
|
||||
}
|
||||
}
|
||||
+32
-6
@@ -9,7 +9,9 @@ import com.solvway.services.system.repo.UserRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Clock;
|
||||
@@ -78,10 +80,17 @@ public class LoginSecurityService {
|
||||
}
|
||||
|
||||
public List<Locked> lockedUsers() {
|
||||
return lockedUsers(null);
|
||||
}
|
||||
|
||||
/** companyId null means every row, including those without a company. */
|
||||
public List<Locked> lockedUsers(Long companyId) {
|
||||
Config c = config();
|
||||
if (!c.enabled() || !c.valid()) return List.of();
|
||||
LocalDateTime now = LocalDateTime.now(clock);
|
||||
return audits.findUsernamesWithFailuresAfter(now.minus(c.length())).stream()
|
||||
List<String> names = companyId == null ? audits.findUsernamesWithFailuresAfter(now.minus(c.length()))
|
||||
: audits.findUsernamesWithFailuresAfterInCompany(now.minus(c.length()), companyId);
|
||||
return names.stream()
|
||||
.map(u -> evaluate(u, c, now)).filter(l -> l != null).toList();
|
||||
}
|
||||
|
||||
@@ -94,16 +103,33 @@ public class LoginSecurityService {
|
||||
write(username, "UNLOCK_RESET", null, null, cut("unlocked by " + by, 255));
|
||||
}
|
||||
|
||||
public void unlock(String username, String by, Long companyId) {
|
||||
String name = username == null ? "" : username.trim();
|
||||
if (name.isEmpty()) throw new IllegalArgumentException("username is required");
|
||||
User u = companyId == null ? null : users.findByUsername(name);
|
||||
if (companyId != null && (u == null || !companyId.equals(u.getCompanyId()))) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found");
|
||||
}
|
||||
unlock(name, by);
|
||||
}
|
||||
|
||||
public Map<String, Object> audit(String username, String event, LocalDate from, LocalDate to, Integer page, Integer size) {
|
||||
return audit(username, event, from, to, page, size, null);
|
||||
}
|
||||
|
||||
/** companyId null means every row, including those without a company. */
|
||||
public Map<String, Object> audit(String username, String event, LocalDate from, LocalDate to, Integer page, Integer size, Long companyId) {
|
||||
int p = page == null || page < 0 ? 0 : page;
|
||||
int s = size == null || size < 1 ? 20 : Math.min(size, 100);
|
||||
String name = username == null ? "" : username.trim();
|
||||
// ponytail: % and _ in the username filter are not escaped (admin-only filter); escape in the query if it matters
|
||||
Page<LoginAudit> r = audits.search(name.isEmpty() ? null : "%" + name + "%",
|
||||
event == null || event.isBlank() ? null : event,
|
||||
from == null ? null : from.atStartOfDay(),
|
||||
to == null ? null : to.plusDays(1).atStartOfDay(),
|
||||
PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "datetime", "id")));
|
||||
String pattern = name.isEmpty() ? null : "%" + name + "%";
|
||||
String ev = event == null || event.isBlank() ? null : event;
|
||||
LocalDateTime f = from == null ? null : from.atStartOfDay();
|
||||
LocalDateTime t = to == null ? null : to.plusDays(1).atStartOfDay();
|
||||
PageRequest pr = PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "datetime", "id"));
|
||||
Page<LoginAudit> r = companyId == null ? audits.search(pattern, ev, f, t, pr)
|
||||
: audits.searchInCompany(pattern, ev, f, t, companyId, pr);
|
||||
return Map.of("content", r.getContent(), "totalElements", r.getTotalElements(), "number", p, "size", s);
|
||||
}
|
||||
|
||||
|
||||
+10
@@ -52,6 +52,16 @@ public class UserService {
|
||||
return userRepository.findByEmailAndIdNot(email, id);
|
||||
}
|
||||
|
||||
public User findByEmailAndCompanyId(String email, Long companyId) {
|
||||
return companyId == null ? userRepository.findByEmailAndCompanyIdIsNullAndType(email, UserType.A)
|
||||
: userRepository.findByEmailAndCompanyIdAndType(email, companyId, UserType.A);
|
||||
}
|
||||
|
||||
public User findByEmailAndCompanyIdAndIdNot(String email, Long companyId, Long id) {
|
||||
return companyId == null ? userRepository.findByEmailAndCompanyIdIsNullAndTypeAndIdNot(email, UserType.A, id)
|
||||
: userRepository.findByEmailAndCompanyIdAndTypeAndIdNot(email, companyId, UserType.A, id);
|
||||
}
|
||||
|
||||
public User findByUsernameAndIdNot(String username, Long id){
|
||||
return userRepository.findByUsernameAndIdNot(username, id);
|
||||
}
|
||||
|
||||
+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