diff --git a/server/src/main/java/com/usatiuk/tjv/y/server/controller/ChatController.java b/server/src/main/java/com/usatiuk/tjv/y/server/controller/ChatController.java index 56400d2..10065b0 100644 --- a/server/src/main/java/com/usatiuk/tjv/y/server/controller/ChatController.java +++ b/server/src/main/java/com/usatiuk/tjv/y/server/controller/ChatController.java @@ -56,6 +56,16 @@ public class ChatController { return chatMapper.makeDto(chat); } + @DeleteMapping(path = "/by-id/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void delete(Principal principal, @PathVariable Long id) { + var chat = chatService.readById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Chat not found")); + if (!Objects.equals(chat.getCreator().getUuid(), principal.getName())) + throw new ResponseStatusException(HttpStatus.FORBIDDEN, "User isn't creator of the chat"); + chatService.deleteById(id); + } + + @GetMapping(path = "/my") public Stream getMy(Principal principal) { return chatService.readByMember(principal.getName()).stream().map(chatMapper::makeDto); diff --git a/server/src/test/java/com/usatiuk/tjv/y/server/controller/ChatControllerTest.java b/server/src/test/java/com/usatiuk/tjv/y/server/controller/ChatControllerTest.java index a8e760a..7092b54 100644 --- a/server/src/test/java/com/usatiuk/tjv/y/server/controller/ChatControllerTest.java +++ b/server/src/test/java/com/usatiuk/tjv/y/server/controller/ChatControllerTest.java @@ -76,6 +76,38 @@ public class ChatControllerTest extends DemoDataDbTest { Assertions.assertIterableEquals(Stream.of(chat1, chat2).map(chatMapper::makeDto).toList(), Arrays.asList(toResponse)); } + @Test + void shouldDeleteChat() { + Long chat1Id = chat1.getId(); + var response = restTemplate.exchange(addr + "/chat/by-id/" + chat1Id, HttpMethod.DELETE, + new HttpEntity<>(createAuthHeaders(person1Auth)), + Object.class); + + Assertions.assertNotNull(response); + Assertions.assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + + Assertions.assertFalse(chatRepository.existsById(chat1Id)); + } + + @Test + void shouldNotDeleteChatUnauthorized() { + Long chatId = chat2.getId(); + var response = restTemplate.exchange(addr + "/chat/by-id/" + chatId, HttpMethod.DELETE, + new HttpEntity<>(createAuthHeaders(person1Auth)), + ErrorTo.class); + + Assertions.assertNotNull(response); + Assertions.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode()); + + var toResponse = response.getBody(); + Assertions.assertNotNull(toResponse); + + Assertions.assertEquals(HttpStatus.FORBIDDEN.value(), toResponse.code()); + + Assertions.assertTrue(chatRepository.existsById(chatId)); + } + + @Test void shouldNotChatUnauthorized() { var response = restTemplate.exchange(addr + "/chat/by-id/" + chat1.getId(), HttpMethod.GET,