Skip to content

Commit

Permalink
Merge pull request #9 from ONAV-KEA/7-create-edit-delete-employees
Browse files Browse the repository at this point in the history
#7 create edit delete employees
  • Loading branch information
OmarKayed authored Dec 8, 2023
2 parents f069633 + 31a4bb5 commit 0fcc6d5
Show file tree
Hide file tree
Showing 8 changed files with 129 additions and 50 deletions.
37 changes: 8 additions & 29 deletions src/main/java/dk/kea/onav2ndproject_rest/api/EventController.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -32,6 +33,8 @@ public class EventController {
private EventService eventService;
@Autowired
private UserService userService;
@Autowired
private AuthenticationService authenticationService;

@GetMapping
public Page<EventDTO> getAllEvents(Pageable pageable) {
Expand All @@ -46,7 +49,7 @@ public ResponseEntity<EventDTO> 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);
}
Expand All @@ -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);
}
Expand All @@ -68,7 +71,7 @@ public ResponseEntity<?> updateEvent(@PathVariable int id, @RequestBody EventDTO

@DeleteMapping("/{id}")
public ResponseEntity<String> 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);
}
Expand All @@ -85,8 +88,8 @@ public Page<EventDTO> 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<String, String> responseMap = new HashMap<>();
responseMap.put("message", "User not authenticated");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(responseMap);
Expand All @@ -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<User> 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<User> users = userService.findByName(username);
if (!users.isEmpty()) {
return users.get(0);
}
}
return null;
}

}
44 changes: 34 additions & 10 deletions src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -21,6 +28,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/api/user")
Expand All @@ -33,6 +41,8 @@ public class UserController {
private JwtTokenManager jwtTokenManager;
@Autowired
private IUserService userService;
@Autowired
private AuthenticationService authenticationService;

@PostMapping("/signup")
public ResponseEntity<JwtResponseModel> signup(@RequestBody JwtRequestModel request){
Expand Down Expand Up @@ -77,16 +87,30 @@ public ResponseEntity<Map> getSecret() {
return ResponseEntity.ok(map);
}

@Secured("MANAGER")
@DeleteMapping("/deleteUser")
public ResponseEntity<Map> deleteUser(@RequestBody User user) {
System.out.println("deleteUser is called with user: " + user.getUsername());
List<User> users = userService.findByName(user.getUsername());
User userToDelete = users.get(0);
userService.delete(userToDelete);
Map<String,String > map = new HashMap<>();
map.put("message","user deleted, if found " + user.getUsername());
return ResponseEntity.ok(map);
@GetMapping("/getAllUsers")
public Page<UserDTO> 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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
import java.util.Optional;

@Repository
public interface UserEventDetailsRepository extends JpaRepository<UserEventDetails, Long> {
public interface UserEventDetailsRepository extends JpaRepository<UserEventDetails, Integer> {
@Query("SELECT ued.user FROM UserEventDetails ued WHERE ued.participating = true AND ued.event.id = :eventId")
List<User> findParticipatingUsersByEventId(int eventId);

@Query("SELECT ued.additionalNotes FROM UserEventDetails ued WHERE ued.user.id = :userId AND ued.event.id = :eventId")
List<String> findAdditionalNotesByUserIdAndEventId(@Param("userId") int userId, @Param("eventId") int eventId);

Optional<UserEventDetails> findByEventIdAndUserId(Integer eventId, Long userId);
Optional<UserEventDetails> 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);

Expand Down
Original file line number Diff line number Diff line change
@@ -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<User,Long> {
public interface UserRepository extends JpaRepository<User,Integer> {
List<User> findByUsername(String name);
//List<User> findUserByPasswordContains(String passwordPart);

}
Original file line number Diff line number Diff line change
@@ -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<User> 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<User> users = userService.findByName(username);
if (!users.isEmpty()) {
return users.get(0);
}
}
return null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public Page<EventDTO> 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@

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;

public interface IUserService extends ICrudService<User,Long>{
List<User> findByName(String name);

UserDTO findByToken(String token);

Page<UserDTO> getAllUsers(Pageable pageable);

UserDTO createUser(User user);

void deleteUserById(int id);
}
37 changes: 33 additions & 4 deletions src/main/java/dk/kea/onav2ndproject_rest/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -27,6 +31,11 @@ public class UserService implements IUserService{
private UserConverter userConverter;
private UserEventDetailsRepository userEventDetailsRepository;

public Page<UserDTO> getAllUsers(Pageable pageable) {
Page<User> users = userRepository.findAll(pageable);
return users.map(userConverter::toDTO);
}

@Override
public Set<User> findAll() {
Set<User> set = new HashSet<>();
Expand All @@ -36,13 +45,19 @@ public Set<User> 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);
Expand All @@ -55,11 +70,15 @@ public void deleteById(Long aLong) {

@Override
public Optional<User> findById(Long aLong) {
Optional<User> user = userRepository.findById(aLong);
return Optional.empty();
}

public Optional<User> findById(int id) {
Optional<User> 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);
}
}

Expand All @@ -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> user = userRepository.findById(id);
if (user.isPresent()) {
userRepository.deleteById(id);
} else {
throw new UserNotFoundException("User not found with id: " + id);
}
}
}

0 comments on commit 0fcc6d5

Please sign in to comment.