From 31a4bb5a9630774059ad6f0774df8af5e659c436 Mon Sep 17 00:00:00 2001 From: Teller501 Date: Thu, 7 Dec 2023 15:30:05 +0100 Subject: [PATCH] create and delete now works --- .../api/EventController.java | 37 ++++------------ .../api/UserController.java | 36 +++++++--------- .../UserEventDetailsRepository.java | 4 +- .../repository/UserRepository.java | 2 +- .../service/AuthenticationService.java | 42 +++++++++++++++++++ .../service/EventService.java | 2 +- .../service/IUserService.java | 4 +- .../service/UserService.java | 21 ++++++++-- 8 files changed, 90 insertions(+), 58 deletions(-) create mode 100644 src/main/java/dk/kea/onav2ndproject_rest/service/AuthenticationService.java diff --git a/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java b/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java index f4bc4a7..22c3b1f 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java @@ -5,6 +5,7 @@ import dk.kea.onav2ndproject_rest.entity.Event; import dk.kea.onav2ndproject_rest.entity.Role; import dk.kea.onav2ndproject_rest.entity.User; +import dk.kea.onav2ndproject_rest.service.AuthenticationService; import dk.kea.onav2ndproject_rest.service.EventService; import dk.kea.onav2ndproject_rest.service.UserService; import org.apache.coyote.Response; @@ -32,6 +33,8 @@ public class EventController { private EventService eventService; @Autowired private UserService userService; + @Autowired + private AuthenticationService authenticationService; @GetMapping public Page getAllEvents(Pageable pageable) { @@ -46,7 +49,7 @@ public ResponseEntity getEventById(@PathVariable int id) { @PostMapping public ResponseEntity createEvent(@RequestBody EventDTO eventDTO) { - User currentUser = getCurrentUser(); + User currentUser = authenticationService.getCurrentUser(); if (currentUser == null || currentUser.getRole() != Role.MANAGER) { return new ResponseEntity<>("User not authorized", HttpStatus.UNAUTHORIZED); } @@ -57,7 +60,7 @@ public ResponseEntity createEvent(@RequestBody EventDTO eventDTO) { @PutMapping("/{id}") public ResponseEntity updateEvent(@PathVariable int id, @RequestBody EventDTO eventDTO) { - User currentUser = getCurrentUser(); + User currentUser = authenticationService.getCurrentUser(); if (currentUser == null || currentUser.getRole() != Role.MANAGER) { return new ResponseEntity<>("User not authorized", HttpStatus.UNAUTHORIZED); } @@ -68,7 +71,7 @@ public ResponseEntity updateEvent(@PathVariable int id, @RequestBody EventDTO @DeleteMapping("/{id}") public ResponseEntity deleteEvent(@PathVariable int id) { - User currentUser = getCurrentUser(); + User currentUser = authenticationService.getCurrentUser(); if (currentUser == null || currentUser.getRole() != Role.MANAGER) { return new ResponseEntity<>("User not authorized", HttpStatus.UNAUTHORIZED); } @@ -85,8 +88,8 @@ public Page getAllEventsByDepartmentId(@PathVariable int id, Pageable @PostMapping("/{eventId}/respond") public ResponseEntity respondToEvent(@PathVariable int eventId, @RequestBody UserEventResponseDTO response) { - Long userId = getCurrentUserId(); - if (userId == null) { + int userId = authenticationService.getCurrentUserId(); + if (userId == -1) { Map responseMap = new HashMap<>(); responseMap.put("message", "User not authenticated"); return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(responseMap); @@ -104,30 +107,6 @@ public ResponseEntity respondToEvent(@PathVariable int eventId, @RequestBody } } - private Long getCurrentUserId() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.getPrincipal() instanceof UserDetails) { - UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - String username = userDetails.getUsername(); - List users = userService.findByName(username); - if (!users.isEmpty()) { - return Long.valueOf(users.get(0).getId()); - } - } - return null; - } - private User getCurrentUser() { - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - if (authentication != null && authentication.getPrincipal() instanceof UserDetails) { - UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - String username = userDetails.getUsername(); - List users = userService.findByName(username); - if (!users.isEmpty()) { - return users.get(0); - } - } - return null; - } } diff --git a/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java b/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java index a7ae71e..c252324 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java @@ -5,8 +5,10 @@ import dk.kea.onav2ndproject_rest.dto.UserDTO; import dk.kea.onav2ndproject_rest.entity.JwtRequestModel; import dk.kea.onav2ndproject_rest.entity.JwtResponseModel; +import dk.kea.onav2ndproject_rest.entity.Role; import dk.kea.onav2ndproject_rest.entity.User; import dk.kea.onav2ndproject_rest.repository.UserRepository; +import dk.kea.onav2ndproject_rest.service.AuthenticationService; import dk.kea.onav2ndproject_rest.service.IUserService; import dk.kea.onav2ndproject_rest.service.JwtUserDetailsService; import dk.kea.onav2ndproject_rest.service.UserService; @@ -40,7 +42,7 @@ public class UserController { @Autowired private IUserService userService; @Autowired - private UserRepository userRepository; + private AuthenticationService authenticationService; @PostMapping("/signup") public ResponseEntity signup(@RequestBody JwtRequestModel request){ @@ -90,31 +92,25 @@ public Page getAllUsers(Pageable pageable) { return userService.getAllUsers(pageable); } - @Secured("MANAGER") @PostMapping("/createUser") - public ResponseEntity createUser(@RequestBody UserDTO userDTO) { - UserDTO createdUser = userService.createUser(userDTO); + public ResponseEntity createUser(@RequestBody User user) { + User currentUser = authenticationService.getCurrentUser(); + if (currentUser == null || currentUser.getRole() != Role.MANAGER) { + return new ResponseEntity<>("User not authorized", HttpStatus.UNAUTHORIZED); + } + UserDTO createdUser = userService.createUser(user); return new ResponseEntity<>(createdUser, HttpStatus.CREATED); } - @Secured("MANAGER") - @DeleteMapping("/deleteUser") - public ResponseEntity> deleteUser(@RequestBody User user) { - System.out.println("deleteUser is called with user: " + user.getUsername()); - List users = userService.findByName(user.getUsername()); - - if (users.isEmpty()) { - Map map = new HashMap<>(); - map.put("message", "User not found"); - return ResponseEntity.status(HttpStatus.NOT_FOUND).body(map); + @DeleteMapping("/{id}") + public ResponseEntity deleteUser(@PathVariable int id) { + User currentUser = authenticationService.getCurrentUser(); + if (currentUser == null || currentUser.getRole() != Role.MANAGER) { + return new ResponseEntity<>("User not authorized", HttpStatus.UNAUTHORIZED); } - User userToDelete = users.get(0); - userService.delete(userToDelete); - - Map map = new HashMap<>(); - map.put("message", "User deleted: " + user.getUsername()); - return ResponseEntity.ok(map); + userService.deleteUserById(id); + return new ResponseEntity<>("User with id " + id + " was deleted", HttpStatus.OK); } @GetMapping() diff --git a/src/main/java/dk/kea/onav2ndproject_rest/repository/UserEventDetailsRepository.java b/src/main/java/dk/kea/onav2ndproject_rest/repository/UserEventDetailsRepository.java index 72caf15..6fc9a03 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/repository/UserEventDetailsRepository.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/repository/UserEventDetailsRepository.java @@ -12,14 +12,14 @@ import java.util.Optional; @Repository -public interface UserEventDetailsRepository extends JpaRepository { +public interface UserEventDetailsRepository extends JpaRepository { @Query("SELECT ued.user FROM UserEventDetails ued WHERE ued.participating = true AND ued.event.id = :eventId") List findParticipatingUsersByEventId(int eventId); @Query("SELECT ued.additionalNotes FROM UserEventDetails ued WHERE ued.user.id = :userId AND ued.event.id = :eventId") List findAdditionalNotesByUserIdAndEventId(@Param("userId") int userId, @Param("eventId") int eventId); - Optional findByEventIdAndUserId(Integer eventId, Long userId); + Optional findByEventIdAndUserId(Integer eventId, int userId); @Query("SELECT CASE WHEN COUNT(ued) > 0 THEN true ELSE false END FROM UserEventDetails ued WHERE ued.user.id = :userId AND ued.event.id = :eventId AND ued.participating = true") boolean isUserParticipatingInEvent(int userId, int eventId); diff --git a/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java b/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java index cf4183e..9b0adff 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java @@ -5,6 +5,6 @@ import java.util.List; -public interface UserRepository extends JpaRepository { +public interface UserRepository extends JpaRepository { List findByUsername(String name); } diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/AuthenticationService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/AuthenticationService.java new file mode 100644 index 0000000..943db32 --- /dev/null +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/AuthenticationService.java @@ -0,0 +1,42 @@ +package dk.kea.onav2ndproject_rest.service; + +import dk.kea.onav2ndproject_rest.entity.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class AuthenticationService { + @Autowired + private UserService userService; + + public int getCurrentUserId() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.getPrincipal() instanceof UserDetails) { + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + String username = userDetails.getUsername(); + List users = userService.findByName(username); + if (!users.isEmpty()) { + return users.get(0).getId(); + } + } + return -1; + } + + public User getCurrentUser() { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null && authentication.getPrincipal() instanceof UserDetails) { + UserDetails userDetails = (UserDetails) authentication.getPrincipal(); + String username = userDetails.getUsername(); + List users = userService.findByName(username); + if (!users.isEmpty()) { + return users.get(0); + } + } + return null; + } +} diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java index 722cc5e..d5e60a8 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/EventService.java @@ -119,7 +119,7 @@ public Page findAllByDepartmentId(int id, Pageable pageable) { return events.map(eventConverter::toDTO); } - public void respondToEvent(Integer eventId, Long userId, UserEventResponseDTO response) { + public void respondToEvent(Integer eventId, int userId, UserEventResponseDTO response) { Event event = eventRepository.findById(eventId) .orElseThrow(() -> new EventNotFoundException("Event does not exist with id: " + eventId)); User user = userRepository.findById(userId) diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java index 0700ac2..05dd47d 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java @@ -14,5 +14,7 @@ public interface IUserService extends ICrudService{ Page getAllUsers(Pageable pageable); - UserDTO createUser(UserDTO userDTO); + UserDTO createUser(User user); + + void deleteUserById(int id); } diff --git a/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java b/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java index f7ce072..b9b5bed 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java @@ -51,8 +51,7 @@ public User save(User user) { } @Override - public UserDTO createUser(UserDTO userDTO) { - User user = userConverter.toEntity(userDTO); + public UserDTO createUser(User user) { user.setId(0); user.setPassword(SecurityConfiguration.passwordEncoder().encode(user.getPassword())); user = userRepository.save(user); @@ -71,11 +70,15 @@ public void deleteById(Long aLong) { @Override public Optional findById(Long aLong) { - Optional user = userRepository.findById(aLong); + return Optional.empty(); + } + + public Optional findById(int id) { + Optional user = userRepository.findById(id); if (user.isPresent()) { return user; } else { - throw new UserNotFoundException("User not found with id: " + aLong); + throw new UserNotFoundException("User not found with id: " + id); } } @@ -91,4 +94,14 @@ public UserDTO findByToken(String token) { User user = userRepository.findByUsername(username).get(0); return userConverter.toDTO(user); } + + @Override + public void deleteUserById(int id) { + Optional user = userRepository.findById(id); + if (user.isPresent()) { + userRepository.deleteById(id); + } else { + throw new UserNotFoundException("User not found with id: " + id); + } + } }