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 47b4ae3..c252324 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java @@ -1,14 +1,21 @@ package dk.kea.onav2ndproject_rest.api; import dk.kea.onav2ndproject_rest.JwtTokenManager; +import dk.kea.onav2ndproject_rest.dto.EventDTO; 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; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.security.authentication.AuthenticationManager; @@ -21,6 +28,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; @RestController @RequestMapping("/api/user") @@ -33,6 +41,8 @@ public class UserController { private JwtTokenManager jwtTokenManager; @Autowired private IUserService userService; + @Autowired + private AuthenticationService authenticationService; @PostMapping("/signup") public ResponseEntity signup(@RequestBody JwtRequestModel request){ @@ -77,16 +87,30 @@ public ResponseEntity getSecret() { return ResponseEntity.ok(map); } - @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()); - User userToDelete = users.get(0); - userService.delete(userToDelete); - Map map = new HashMap<>(); - map.put("message","user deleted, if found " + user.getUsername()); - return ResponseEntity.ok(map); + @GetMapping("/getAllUsers") + public Page getAllUsers(Pageable pageable) { + return userService.getAllUsers(pageable); + } + + @PostMapping("/createUser") + 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); + } + + @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); + } + + 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 7099a6a..9b0adff 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/repository/UserRepository.java @@ -1,13 +1,10 @@ package dk.kea.onav2ndproject_rest.repository; -import dk.kea.onav2ndproject_rest.dto.UserDTO; import dk.kea.onav2ndproject_rest.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; -public interface UserRepository extends JpaRepository { +public interface UserRepository extends JpaRepository { List findByUsername(String name); - //List findUserByPasswordContains(String passwordPart); - } 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 65f7fc0..05dd47d 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/IUserService.java @@ -2,6 +2,8 @@ import dk.kea.onav2ndproject_rest.dto.UserDTO; import dk.kea.onav2ndproject_rest.entity.User; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import java.util.List; @@ -9,4 +11,10 @@ public interface IUserService extends ICrudService{ List findByName(String name); UserDTO findByToken(String token); + + Page getAllUsers(Pageable pageable); + + 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 393c7c3..b9b5bed 100644 --- a/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java +++ b/src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java @@ -3,13 +3,17 @@ import dk.kea.onav2ndproject_rest.JwtTokenManager; import dk.kea.onav2ndproject_rest.config.SecurityConfiguration; +import dk.kea.onav2ndproject_rest.dto.EventDTO; import dk.kea.onav2ndproject_rest.dto.UserConverter; import dk.kea.onav2ndproject_rest.dto.UserDTO; +import dk.kea.onav2ndproject_rest.entity.Event; import dk.kea.onav2ndproject_rest.entity.User; import dk.kea.onav2ndproject_rest.exception.UserNotFoundException; import dk.kea.onav2ndproject_rest.repository.UserEventDetailsRepository; import dk.kea.onav2ndproject_rest.repository.UserRepository; import lombok.AllArgsConstructor; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; @@ -27,6 +31,11 @@ public class UserService implements IUserService{ private UserConverter userConverter; private UserEventDetailsRepository userEventDetailsRepository; + public Page getAllUsers(Pageable pageable) { + Page users = userRepository.findAll(pageable); + return users.map(userConverter::toDTO); + } + @Override public Set findAll() { Set set = new HashSet<>(); @@ -36,13 +45,19 @@ public Set findAll() { @Override public User save(User user) { -// if(user.getPassword() == null) { PasswordEncoder pw = SecurityConfiguration.passwordEncoder(); user.setPassword(pw.encode(user.getPassword())); -// } return userRepository.save(user); } + @Override + public UserDTO createUser(User user) { + user.setId(0); + user.setPassword(SecurityConfiguration.passwordEncoder().encode(user.getPassword())); + user = userRepository.save(user); + return userConverter.toDTO(user); + } + @Override public void delete(User object) { userRepository.delete(object); @@ -55,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); } } @@ -75,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); + } + } }