diff --git a/src/main/java/org/example/team6backend/incident/controller/IncidentController.java b/src/main/java/org/example/team6backend/incident/controller/IncidentController.java index 0bea6be..fc92229 100644 --- a/src/main/java/org/example/team6backend/incident/controller/IncidentController.java +++ b/src/main/java/org/example/team6backend/incident/controller/IncidentController.java @@ -43,6 +43,20 @@ public class IncidentController { private final UserMapper userMapper; private final NotificationService notificationService; + private AppUser getUser(CustomUserDetails userDetails) { + if (userDetails == null) { + Authentication auth = SecurityContextHolder.getContext().getAuthentication(); + if (auth != null && auth.getPrincipal() instanceof CustomUserDetails cd) { + if (cd.getUser() == null) { + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid user details"); + } + return cd.getUser(); + } + throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authentication required"); + } + return userDetails.getUser(); + } + @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseStatus(HttpStatus.CREATED) @PreAuthorize("hasAnyRole('RESIDENT', 'ADMIN')") @@ -50,10 +64,10 @@ public ResponseEntity createIncidentWithFiles(@RequestParam("s @RequestParam(value = "description", required = false) String description, @RequestParam("incidentCategory") IncidentCategory incidentCategory, @RequestParam(value = "files", required = false) List files, - @AuthenticationPrincipal CustomUserDetails customUserDetails) { + @AuthenticationPrincipal CustomUserDetails userDetails) { log.info("POST /api/incidents - Creating new incident with {} files", files != null ? files.size() : 0); - AppUser user = customUserDetails.getUser(); + AppUser user = getUser(userDetails); IncidentRequest incidentRequest = new IncidentRequest(); incidentRequest.setSubject(subject); @@ -68,10 +82,10 @@ public ResponseEntity createIncidentWithFiles(@RequestParam("s @ResponseStatus(HttpStatus.CREATED) @PreAuthorize("hasAnyRole('RESIDENT', 'ADMIN')") public ResponseEntity createIncident(@RequestBody @Valid IncidentRequest incidentRequest, - @AuthenticationPrincipal CustomUserDetails customUserDetails) { + @AuthenticationPrincipal CustomUserDetails userDetails) { log.info("POST /api/incidents (JSON) - Creating new incident"); - AppUser user = customUserDetails.getUser(); + AppUser user = getUser(userDetails); Incident saved = incidentService.createIncident(incidentRequest, null, user); return ResponseEntity.status(HttpStatus.CREATED).body(IncidentResponse.fromEntityBasic(saved)); } @@ -81,7 +95,7 @@ public ResponseEntity createIncident(@RequestBody @Valid Incid public ResponseEntity> getMyIncidents(@AuthenticationPrincipal CustomUserDetails userDetails, Pageable pageable) { log.info("GET /api/incidents/my - Fetching my incidents"); - AppUser user = userDetails.getUser(); + AppUser user = getUser(userDetails); return ResponseEntity .ok(incidentService.findByCreatedBy(user, pageable).map(IncidentResponse::fromEntityBasic)); } @@ -91,7 +105,7 @@ public ResponseEntity> getMyIncidents(@AuthenticationPrin public ResponseEntity> getAssignedIncidents( @AuthenticationPrincipal CustomUserDetails userDetails, Pageable pageable) { log.info("GET /api/incidents/assigned - Fetching assigned incidents"); - AppUser user = userDetails.getUser(); + AppUser user = getUser(userDetails); return ResponseEntity .ok(incidentService.findByAssignedTo(user, pageable).map(IncidentResponse::fromEntityBasic)); } @@ -106,35 +120,33 @@ public ResponseEntity> getAllIncidents(Pageable pageable) @PreAuthorize("hasAnyRole('RESIDENT', 'HANDLER', 'ADMIN')") @GetMapping("/{id}") public ResponseEntity getIncidentById(@PathVariable Long id) { - log.info("GET /api/incidents/{} - Fetching incident", id); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); - - if (auth == null || !(auth.getPrincipal() instanceof CustomUserDetails userDetails)) { + if (auth == null || !(auth.getPrincipal() instanceof CustomUserDetails cd)) { throw new ResponseStatusException(HttpStatus.UNAUTHORIZED); } - - AppUser currentUser = userDetails.getUser(); + AppUser currentUser = cd.getUser(); + log.info("GET /api/incidents/{} - Fetching incident", id); notificationService.markNotificationAsReadForIncident(currentUser.getId(), id); - return ResponseEntity.ok(IncidentResponse.fromEntityWithDocuments(incidentService.getById(id, currentUser))); } @PreAuthorize("hasRole('ADMIN')") @PatchMapping("/{incidentId}/assign") public ResponseEntity assignIncident(@PathVariable Long incidentId, - @Valid @RequestBody AssignIncidentRequest request, @AuthenticationPrincipal CustomUserDetails adminUser) { + @Valid @RequestBody AssignIncidentRequest request, @AuthenticationPrincipal CustomUserDetails userDetails) { log.info("PATCH /api/incidents/{}/assign - Assigning to handler {}", incidentId, request.handlerId()); - Incident updatedIncident = incidentService.assignIncidentToHandler(incidentId, request.handlerId(), - adminUser.getUser()); + AppUser user = getUser(userDetails); + Incident updatedIncident = incidentService.assignIncidentToHandler(incidentId, request.handlerId(), user); return ResponseEntity.ok(IncidentResponse.fromEntityBasic(updatedIncident)); } @PreAuthorize("hasRole('ADMIN')") @PatchMapping("/{incidentId}/unassign") public ResponseEntity unassignIncident(@PathVariable Long incidentId, - @AuthenticationPrincipal CustomUserDetails adminUser) { + @AuthenticationPrincipal CustomUserDetails userDetails) { log.info("PATCH /api/incidents/{}/unassign - Unassigning incident", incidentId); - Incident updatedIncident = incidentService.unassignIncident(incidentId, adminUser.getUser()); + AppUser user = getUser(userDetails); + Incident updatedIncident = incidentService.unassignIncident(incidentId, user); return ResponseEntity.ok(IncidentResponse.fromEntityBasic(updatedIncident)); } @@ -160,10 +172,10 @@ public ResponseEntity resolveIncident(@PathVariable Long incid @PatchMapping("/{incidentId}/status") public ResponseEntity updateStatus(@PathVariable Long incidentId, @Valid @RequestBody UpdateIncidentStatusRequest request, - @AuthenticationPrincipal CustomUserDetails adminUser) { + @AuthenticationPrincipal CustomUserDetails userDetails) { log.info("PATCH /api/incidents/{}/status - Updating status to {}", incidentId, request.status()); - Incident updatedIncident = incidentService.updateIncidentStatus(incidentId, request.status(), - adminUser.getUser()); + AppUser user = getUser(userDetails); + Incident updatedIncident = incidentService.updateIncidentStatus(incidentId, request.status(), user); return ResponseEntity.ok(IncidentResponse.fromEntity(updatedIncident)); } diff --git a/src/main/java/org/example/team6backend/incident/dto/IncidentResponse.java b/src/main/java/org/example/team6backend/incident/dto/IncidentResponse.java index 2c1b2af..d19eabb 100644 --- a/src/main/java/org/example/team6backend/incident/dto/IncidentResponse.java +++ b/src/main/java/org/example/team6backend/incident/dto/IncidentResponse.java @@ -1,6 +1,7 @@ package org.example.team6backend.incident.dto; import lombok.Data; +import lombok.extern.slf4j.Slf4j; import org.example.team6backend.document.dto.DocumentDTO; import org.example.team6backend.incident.entity.Incident; import org.example.team6backend.incident.entity.IncidentCategory; @@ -10,7 +11,9 @@ import java.time.Instant; import java.util.ArrayList; import java.util.List; +import java.util.Objects; +@Slf4j @Data public class IncidentResponse { @@ -49,8 +52,8 @@ public static IncidentResponse fromEntityWithDocuments(Incident incident) { if (Hibernate.isInitialized(incident.getDocuments()) && incident.getDocuments() != null) { response.setHasDocuments(!incident.getDocuments().isEmpty()); if (!incident.getDocuments().isEmpty()) { - List documentDTOs = incident.getDocuments().stream() - .filter(document -> document != null).map(document -> { + List documentDTOs = incident.getDocuments().stream().filter(Objects::nonNull) + .map(document -> { DocumentDTO dto = new DocumentDTO(); dto.setFileName(document.getFileName()); dto.setFileKey(document.getFileKey()); @@ -60,6 +63,7 @@ public static IncidentResponse fromEntityWithDocuments(Incident incident) { } } } catch (Exception e) { + log.warn("Failed to load documents for incident ", e); response.setHasDocuments(false); response.setDocuments(new ArrayList<>()); } diff --git a/src/main/java/org/example/team6backend/incident/entity/Incident.java b/src/main/java/org/example/team6backend/incident/entity/Incident.java index 21576b8..cf89b33 100644 --- a/src/main/java/org/example/team6backend/incident/entity/Incident.java +++ b/src/main/java/org/example/team6backend/incident/entity/Incident.java @@ -1,6 +1,8 @@ package org.example.team6backend.incident.entity; import jakarta.persistence.*; +import lombok.Getter; +import lombok.Setter; import org.example.team6backend.document.entity.Document; import org.example.team6backend.user.entity.AppUser; @@ -8,6 +10,8 @@ import java.util.List; @Entity +@Getter +@Setter public class Incident { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -55,92 +59,4 @@ protected void onCreate() { protected void onUpdate() { updatedAt = Instant.now(); } - - public Long getId() { - return id; - } - - public String getSubject() { - return subject; - } - - public String getDescription() { - return description; - } - - public IncidentCategory getIncidentCategory() { - return incidentCategory; - } - - public IncidentStatus getIncidentStatus() { - return incidentStatus; - } - - public AppUser getCreatedBy() { - return createdBy; - } - - public AppUser getModifiedBy() { - return modifiedBy; - } - - public AppUser getAssignedTo() { - return assignedTo; - } - - public Instant getCreatedAt() { - return createdAt; - } - - public Instant getUpdatedAt() { - return updatedAt; - } - - public List getDocuments() { - return documents; - } - - public void setId(Long id) { - this.id = id; - } - - public void setSubject(String subject) { - this.subject = subject; - } - - public void setDescription(String description) { - this.description = description; - } - - public void setIncidentCategory(IncidentCategory incidentCategory) { - this.incidentCategory = incidentCategory; - } - - public void setIncidentStatus(IncidentStatus incidentStatus) { - this.incidentStatus = incidentStatus; - } - - public void setCreatedBy(AppUser createdBy) { - this.createdBy = createdBy; - } - - public void setModifiedBy(AppUser modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public void setAssignedTo(AppUser assignedTo) { - this.assignedTo = assignedTo; - } - - public void setCreatedAt(Instant createdAt) { - this.createdAt = createdAt; - } - - public void setUpdatedAt(Instant updatedAt) { - this.updatedAt = updatedAt; - } - - public void setDocuments(List documents) { - this.documents = documents; - } } diff --git a/src/main/java/org/example/team6backend/incident/service/IncidentService.java b/src/main/java/org/example/team6backend/incident/service/IncidentService.java index cb53d6f..757499f 100644 --- a/src/main/java/org/example/team6backend/incident/service/IncidentService.java +++ b/src/main/java/org/example/team6backend/incident/service/IncidentService.java @@ -1,5 +1,6 @@ package org.example.team6backend.incident.service; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.example.team6backend.activity.service.ActivityLogService; import org.example.team6backend.auditlog.service.AuditLogService; @@ -31,8 +32,13 @@ @Service @Slf4j +@RequiredArgsConstructor public class IncidentService { + private static final String TARGET_TYPE = "Incident"; + private static final String INCIDENT_PREFIX = "Incident #"; + private static final String NOT_FOUND_MESSAGE = "Incident not found with id: "; + private final IncidentRepository incidentRepository; private final ActivityLogService activityLogService; private final DocumentService documentService; @@ -41,21 +47,6 @@ public class IncidentService { private final MinioService minioService; private final AuditLogService auditLogService; - public IncidentService(IncidentRepository incidentRepository, ActivityLogService activityLogService, - DocumentService documentService, AppUserRepository userRepository, NotificationService notificationService, - MinioService minioService, AuditLogService auditLogService) { - this.incidentRepository = incidentRepository; - this.activityLogService = activityLogService; - this.documentService = documentService; - this.userRepository = userRepository; - this.notificationService = notificationService; - this.minioService = minioService; - this.auditLogService = auditLogService; - } - - /** - * Help-method for sorting - **/ private Pageable withDefaultSort(Pageable pageable) { if (pageable.isUnpaged() || pageable.getSort().isSorted()) { return pageable; @@ -63,6 +54,24 @@ private Pageable withDefaultSort(Pageable pageable) { return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(Sort.Direction.DESC, "id")); } + private void validateNotClosed(Incident incident, String message) { + if (incident.getIncidentStatus() == IncidentStatus.CLOSED) { + throw new IllegalStateException(message); + } + } + + private void validateHandlerOrAdmin(Incident incident, AppUser currentUser, String action) { + if (currentUser.getRole() != UserRole.HANDLER && currentUser.getRole() != UserRole.ADMIN) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, + "Only Handlers or Admins can " + action + " incidents!"); + } + if (currentUser.getRole() != UserRole.ADMIN && (incident.getAssignedTo() == null + || !incident.getAssignedTo().getId().equals(currentUser.getId()))) { + throw new ResponseStatusException(HttpStatus.FORBIDDEN, + "You can only " + action + " incidents assigned to you!"); + } + } + /** * Create incident **/ @@ -93,8 +102,9 @@ public Incident createIncident(IncidentRequest incidentRequest, List new ResourceNotFoundException("Incident not found!")); + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + incidentId)); String incidentSubject = incident.getSubject(); @@ -166,23 +176,22 @@ public void deleteIncident(Long incidentId, AppUser currentUser) { try { minioService.deleteFile(document.getFileKey()); } catch (Exception e) { - log.warn("Failed to delete file from S3: " + document.getFileKey(), e); + log.warn("Failed to delete file from S3: {}", document.getFileKey(), e); } } incidentRepository.delete(incident); - auditLogService.log("DELETE_INCIDENT", currentUser.getName() + " deleted incident #" + incidentId, currentUser, - "Incident", incidentId.toString()); + auditLogService.log("DELETE_INCIDENT", + currentUser.getName() + " deleted " + INCIDENT_PREFIX + incidentId + " '" + incidentSubject + "'", + currentUser, TARGET_TYPE, incidentId.toString()); } @Transactional public Incident assignIncidentToHandler(Long incidentId, String handlerId, AppUser currentUser) { Incident incident = incidentRepository.findById(incidentId) - .orElseThrow(() -> new ResourceNotFoundException("Incident not found with id: " + incidentId)); + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + incidentId)); - if (incident.getIncidentStatus() == IncidentStatus.CLOSED) { - throw new IllegalStateException("Cannot modify a closed incident. Status: " + incident.getIncidentStatus()); - } + validateNotClosed(incident, "Cannot modify a closed incident. Status: " + incident.getIncidentStatus()); AppUser handler = userRepository.findById(handlerId) .orElseThrow(() -> new ResourceNotFoundException("Handler not found with id: " + handlerId)); @@ -207,8 +216,8 @@ public Incident assignIncidentToHandler(Long incidentId, String handlerId, AppUs savedIncident, currentUser); auditLogService.log("ASSIGN_INCIDENT", - currentUser.getName() + " assigned incident #" + incidentId + " to " + handler.getName(), currentUser, - "Incident", incidentId.toString()); + currentUser.getName() + " assigned " + INCIDENT_PREFIX + incidentId + " to " + handler.getName(), + currentUser, TARGET_TYPE, incidentId.toString()); notificationService.createNotification("You have been assigned to an incident", handler, savedIncident); @@ -224,7 +233,7 @@ public Incident assignIncidentToHandler(Long incidentId, String handlerId, AppUs @Transactional public Incident updateIncidentStatus(Long incidentId, IncidentStatus newStatus, AppUser currentUser) { Incident incident = incidentRepository.findById(incidentId) - .orElseThrow(() -> new ResourceNotFoundException("Incident not found")); + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + incidentId)); IncidentStatus oldStatus = incident.getIncidentStatus(); @@ -241,8 +250,8 @@ public Incident updateIncidentStatus(Long incidentId, IncidentStatus newStatus, currentUser.getName() + " changed status from " + oldStatus + " to " + newStatus, savedIncident, currentUser); - auditLogService.log("UPDATE_STATUS", currentUser.getName() + " changed incident #" + incidentId - + " status from " + oldStatus + " to " + newStatus, currentUser); + auditLogService.log("UPDATE_STATUS", currentUser.getName() + " changed " + INCIDENT_PREFIX + incidentId + + " status from " + oldStatus + " to " + newStatus, currentUser, TARGET_TYPE, incidentId.toString()); if (savedIncident.getCreatedBy() != null && !savedIncident.getCreatedBy().getId().equals(currentUser.getId())) { @@ -251,7 +260,7 @@ public Incident updateIncidentStatus(Long incidentId, IncidentStatus newStatus, savedIncident.getCreatedBy(), savedIncident); } return incidentRepository.findByIdWithDocuments(savedIncident.getId()) - .orElseThrow(() -> new ResourceNotFoundException("Incident not found")); + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + incidentId)); } public Incident unassignIncident(Long incidentId, AppUser currentUser) { @@ -260,11 +269,9 @@ public Incident unassignIncident(Long incidentId, AppUser currentUser) { } Incident incident = incidentRepository.findById(incidentId) - .orElseThrow(() -> new ResourceNotFoundException("Incident not found with id: " + incidentId)); + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + incidentId)); - if (incident.getIncidentStatus() == IncidentStatus.CLOSED) { - throw new IllegalStateException("Cannot modify a closed incident. Status: " + incident.getIncidentStatus()); - } + validateNotClosed(incident, "Cannot unassign a closed incident. Status: " + incident.getIncidentStatus()); AppUser previousHandler = incident.getAssignedTo(); @@ -285,12 +292,11 @@ public Incident unassignIncident(Long incidentId, AppUser currentUser) { currentUser.getName() + " unassigned incident from " + previousHandler.getName(), savedIncident, currentUser); - auditLogService.log("UNASSIGN_INCIDENT", - currentUser.getName() + " unassigned incident #" + incidentId + " from " + previousHandler.getName(), - currentUser); + auditLogService.log("UNASSIGN_INCIDENT", currentUser.getName() + " unassigned " + INCIDENT_PREFIX + incidentId + + " from " + previousHandler.getName(), currentUser, TARGET_TYPE, incidentId.toString()); notificationService.createNotification( - "Incident #" + incident.getId() + " has been unassigned from you by " + currentUser.getName(), + INCIDENT_PREFIX + incident.getId() + " has been unassigned from you by " + currentUser.getName(), previousHandler, savedIncident); return savedIncident; @@ -299,21 +305,10 @@ public Incident unassignIncident(Long incidentId, AppUser currentUser) { @Transactional public Incident closeIncident(Long incidentId, AppUser currentUser) { Incident incident = incidentRepository.findById(incidentId) - .orElseThrow(() -> new ResourceNotFoundException("Incident not found with id: " + incidentId)); - - if (currentUser.getRole() != UserRole.HANDLER && currentUser.getRole() != UserRole.ADMIN) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Only handlers or admins can close incidents"); - } - - if (currentUser.getRole() != UserRole.ADMIN && (incident.getAssignedTo() == null - || !incident.getAssignedTo().getId().equals(currentUser.getId()))) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "You can only close incidents assigned to you"); - } - - if (incident.getIncidentStatus() == IncidentStatus.CLOSED) { - throw new IllegalStateException("Incident is already closed"); - } + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + incidentId)); + validateHandlerOrAdmin(incident, currentUser, "close"); + validateNotClosed(incident, "Incident is already closed"); IncidentStatus oldStatus = incident.getIncidentStatus(); incident.setIncidentStatus(IncidentStatus.CLOSED); @@ -325,10 +320,11 @@ public Incident closeIncident(Long incidentId, AppUser currentUser) { currentUser.getName() + " closed incident (status changed from " + oldStatus + " to CLOSED)", savedIncident, currentUser); - auditLogService.log("CLOSE_INCIDENT", currentUser.getName() + " closed incident #" + incidentId, currentUser); + auditLogService.log("CLOSE_INCIDENT", currentUser.getName() + " closed " + INCIDENT_PREFIX + incidentId, + currentUser, TARGET_TYPE, incidentId.toString()); notificationService.createNotification( - "Incident #" + incident.getId() + " has been closed by " + currentUser.getName(), + INCIDENT_PREFIX + incident.getId() + " has been closed by " + currentUser.getName(), savedIncident.getCreatedBy(), savedIncident); log.info("Closed incident {} by {} (role: {})", incidentId, currentUser.getId(), currentUser.getRole()); @@ -338,20 +334,10 @@ public Incident closeIncident(Long incidentId, AppUser currentUser) { @Transactional public Incident resolveIncident(Long incidentId, AppUser currentUser) { Incident incident = incidentRepository.findById(incidentId) - .orElseThrow(() -> new ResourceNotFoundException("Incident not found with id: " + incidentId)); + .orElseThrow(() -> new ResourceNotFoundException(NOT_FOUND_MESSAGE + incidentId)); - if (currentUser.getRole() != UserRole.HANDLER && currentUser.getRole() != UserRole.ADMIN) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Only handlers or admins can resolve incidents"); - } - - if (currentUser.getRole() != UserRole.ADMIN && (incident.getAssignedTo() == null - || !incident.getAssignedTo().getId().equals(currentUser.getId()))) { - throw new ResponseStatusException(HttpStatus.FORBIDDEN, "You can only resolve incidents assigned to you"); - } - - if (incident.getIncidentStatus() == IncidentStatus.CLOSED) { - throw new IllegalStateException("Cannot resolve a closed incident"); - } + validateHandlerOrAdmin(incident, currentUser, "resolve"); + validateNotClosed(incident, "Cannot resolve a closed incident"); if (incident.getIncidentStatus() == IncidentStatus.RESOLVED) { throw new IllegalStateException("Incident is already resolved"); @@ -367,11 +353,11 @@ public Incident resolveIncident(Long incidentId, AppUser currentUser) { currentUser.getName() + " resolved incident (status changed from " + oldStatus + " to RESOLVED)", savedIncident, currentUser); - auditLogService.log("RESOLVE_INCIDENT", currentUser.getName() + " resolved incident #" + incidentId, - currentUser); + auditLogService.log("RESOLVE_INCIDENT", currentUser.getName() + " resolved " + INCIDENT_PREFIX + incidentId, + currentUser, TARGET_TYPE, incidentId.toString()); notificationService.createNotification( - "Incident #" + incident.getId() + " has been marked as resolved by " + currentUser.getName(), + INCIDENT_PREFIX + incident.getId() + " has been marked as resolved by " + currentUser.getName(), savedIncident.getCreatedBy(), savedIncident); log.info("Resolved incident {} by {} (role: {})", incidentId, currentUser.getId(), currentUser.getRole()); diff --git a/src/test/java/org/example/team6backend/incident/controller/IncidentControllerTest.java b/src/test/java/org/example/team6backend/incident/controller/IncidentControllerTest.java index 86c924a..1163bff 100644 --- a/src/test/java/org/example/team6backend/incident/controller/IncidentControllerTest.java +++ b/src/test/java/org/example/team6backend/incident/controller/IncidentControllerTest.java @@ -106,31 +106,26 @@ void shouldGetAssignedIncidents() throws Exception { @Test @WithMockUser(roles = "RESIDENT") void shouldGetMyIncidents() throws Exception { - when(incidentService.findByCreatedBy(any(), any())).thenReturn(new PageImpl<>(List.of())); mockMvc.perform(get("/api/incidents/my")).andExpect(status().isOk()); } @Test - @WithMockUser(roles = "RESIDENT") void getIncidentById() throws Exception { - AppUser user = new AppUser(); user.setId("1"); user.setRole(UserRole.RESIDENT); CustomUserDetails principal = new CustomUserDetails(user, Map.of()); + SecurityContext context = SecurityContextHolder.createEmptyContext(); + context.setAuthentication(new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities())); + SecurityContextHolder.setContext(context); Incident incident = new Incident(); incident.setId(1L); - when(incidentService.getById(eq(1L), any())).thenReturn(incident); - SecurityContext context = SecurityContextHolder.createEmptyContext(); - context.setAuthentication(new UsernamePasswordAuthenticationToken(principal, null, principal.getAuthorities())); - SecurityContextHolder.setContext(context); - mockMvc.perform(get("/api/incidents/1")).andExpect(status().isOk()); } @@ -147,6 +142,7 @@ void getById_shouldReturn401_whenPrincipalIsWrongType() throws Exception { SecurityContext context = SecurityContextHolder.createEmptyContext(); context.setAuthentication(auth); SecurityContextHolder.setContext(context); + mockMvc.perform(get("/api/incidents/1")).andExpect(status().isUnauthorized()); }