Skip to content

Commit

Permalink
Merge pull request #638 from hngprojects/feat/delete-user-by-email
Browse files Browse the repository at this point in the history
feat: delete user by email
  • Loading branch information
Am0du authored Aug 25, 2024
2 parents 4fa36df + 902d540 commit 82cc4a5
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,8 @@ public SecurityFilterChain httpSecurity(HttpSecurity httpSecurity) throws Except
"/api/v1/accounts/**",
"api/v1/auth/2fa/**",
"/api/v1/users/members",
"/api/v1/users/me/{id}").authenticated())
"/api/v1/users/me/{id}",
"/api/v1/users/delete").authenticated())
.logout(logout -> logout
.deleteCookies("remove")
.invalidateHttpSession(true)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package hng_java_boilerplate.user.controller;

import hng_java_boilerplate.exception.BadRequestException;
import hng_java_boilerplate.exception.NotFoundException;
import hng_java_boilerplate.exception.UnAuthorizedException;
import hng_java_boilerplate.user.dto.request.DeleteUserRequest;
import hng_java_boilerplate.user.dto.response.MembersResponse;
import hng_java_boilerplate.user.dto.response.Response;
import hng_java_boilerplate.user.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -30,12 +31,23 @@ public ResponseEntity<?> getUserDetails(@PathVariable String userId) {
@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@GetMapping(value = "/members", produces = "application/json")
public ResponseEntity<?> getAllMembers(@RequestParam int page, Authentication authentication) {
if (authentication == null) return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
.body(Response.builder().message("Unauthorized").status_code("401").build());

List<MembersResponse> allUsers = userService.getAllUsers(page, authentication);
Response<?> response = Response.builder().message("Users List Successfully Fetched").status_code("200").data(allUsers).build();
return ResponseEntity.status(HttpStatus.OK).body(response);
}


@PreAuthorize("hasRole('ROLE_SUPER_ADMIN')")
@DeleteMapping("/delete")
public ResponseEntity<?> deleteUserByEmail(@Valid @RequestBody DeleteUserRequest request, Authentication authentication) {
Response<?> response = userService.deleteUserByEmail(request, authentication);
return ResponseEntity.status(HttpStatus.OK).body(response);
}


@GetMapping("/me/{id}")
public Response<?> getUserById(@PathVariable String id, Authentication authentication) {
return userService.getUserById(id, authentication);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package hng_java_boilerplate.user.dto.request;

import jakarta.validation.constraints.NotBlank;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class DeleteUserRequest {

@NotBlank(message = "Email is required and cannot be blank.")
private String email;

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@


public interface UserService {

GetUserDto getUserWithDetails(String userId);
ResponseEntity<ApiResponse<ResponseData>> registerUser(SignupDto signupDto);
ResponseEntity<String> verifyOtp(String email, String token, HttpServletRequest request);
Expand All @@ -27,5 +28,10 @@ public interface UserService {
void requestToken(EmailSenderDto emailSenderDto, HttpServletRequest request);
void sendMagicLink(String email, HttpServletRequest request);
List<MembersResponse> getAllUsers(int page, Authentication authentication);

Response<?> deleteUserByEmail(DeleteUserRequest request, Authentication authentication);

Response<?> getUserById(String userId, Authentication authentication);


}
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@
import hng_java_boilerplate.exception.UnAuthorizedException;
import hng_java_boilerplate.organisation.entity.Organisation;
import hng_java_boilerplate.organisation.repository.OrganisationRepository;
import hng_java_boilerplate.user.dto.request.EmailSenderDto;
import hng_java_boilerplate.user.dto.request.*;
import hng_java_boilerplate.plans.entity.Plan;
import hng_java_boilerplate.plans.service.PlanService;
import hng_java_boilerplate.user.dto.request.GetUserDto;
import hng_java_boilerplate.user.dto.request.LoginDto;
import hng_java_boilerplate.user.dto.request.SignupDto;
import hng_java_boilerplate.user.dto.request.*;
import hng_java_boilerplate.user.dto.response.ApiResponse;
import hng_java_boilerplate.user.dto.response.MembersResponse;
import hng_java_boilerplate.user.dto.response.ResponseData;
Expand Down Expand Up @@ -382,6 +381,18 @@ public List<MembersResponse> getAllUsers(int page, Authentication authentication
return users;
}


@Transactional
public Response<?> deleteUserByEmail(DeleteUserRequest request, Authentication authentication) {
String email = request.getEmail();
if (userRepository.existsByEmail(email)) {
userRepository.deleteByEmail(email);
return Response.builder().status_code("success").message("The account has been successfully deleted.").build();
}
throw new NotFoundException("User not found with email: " + email);

}

@Override
public Response<?> getUserById(String userId, Authentication authentication) {
String email = authentication.getName();
Expand All @@ -403,6 +414,7 @@ public Response<?> getUserById(String userId, Authentication authentication) {
} else {
throw new NotFoundException("User not found with id: " + userId);
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package hng_java_boilerplate.user.crud_operations_test;

import hng_java_boilerplate.exception.BadRequestException;
import hng_java_boilerplate.exception.NotFoundException;
import hng_java_boilerplate.user.dto.request.DeleteUserRequest;
import hng_java_boilerplate.user.dto.response.Response;
import hng_java_boilerplate.user.repository.UserRepository;
import hng_java_boilerplate.user.serviceImpl.UserServiceImpl;
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.security.core.Authentication;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
public class DeleteUserTest {

@InjectMocks
private UserServiceImpl userService;

@Mock
private UserRepository userRepository;

@Mock
private Authentication authentication;

@Test
void deleteUserSuccessfullyTest() {
String email = "[email protected]";
DeleteUserRequest request = new DeleteUserRequest();
request.setEmail(email);

when(userRepository.existsByEmail(email)).thenReturn(true);

Response<?> response = userService.deleteUserByEmail(request, authentication);

assertEquals("success", response.getStatus_code());
assertEquals("The account has been successfully deleted.", response.getMessage());
verify(userRepository, times(1)).deleteByEmail(email);
}

@Test
void deleteUserNotFoundTest() {
String email = "[email protected]";
DeleteUserRequest request = new DeleteUserRequest();
request.setEmail(email);

when(userRepository.existsByEmail(email)).thenReturn(false);
NotFoundException exception = assertThrows(NotFoundException.class, () -> {
userService.deleteUserByEmail(request, authentication);
});
assertEquals("User not found with email: [email protected]", exception.getMessage());
verify(userRepository, never()).deleteByEmail(anyString());
}


}

0 comments on commit 82cc4a5

Please sign in to comment.