Skip to content

Commit

Permalink
create and delete now works
Browse files Browse the repository at this point in the history
  • Loading branch information
Teller501 committed Dec 7, 2023
1 parent fe1da90 commit 31a4bb5
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 58 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;
}

}
36 changes: 16 additions & 20 deletions src/main/java/dk/kea/onav2ndproject_rest/api/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -40,7 +42,7 @@ public class UserController {
@Autowired
private IUserService userService;
@Autowired
private UserRepository userRepository;
private AuthenticationService authenticationService;

@PostMapping("/signup")
public ResponseEntity<JwtResponseModel> signup(@RequestBody JwtRequestModel request){
Expand Down Expand Up @@ -90,31 +92,25 @@ public Page<UserDTO> getAllUsers(Pageable pageable) {
return userService.getAllUsers(pageable);
}

@Secured("MANAGER")
@PostMapping("/createUser")
public ResponseEntity<UserDTO> 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<Map<String, String>> deleteUser(@RequestBody User user) {
System.out.println("deleteUser is called with user: " + user.getUsername());
List<User> users = userService.findByName(user.getUsername());

if (users.isEmpty()) {
Map<String, String> 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<String, String> 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()
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
Expand Up @@ -5,6 +5,6 @@

import java.util.List;

public interface UserRepository extends JpaRepository<User,Long> {
public interface UserRepository extends JpaRepository<User,Integer> {
List<User> findByUsername(String name);
}
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 @@ -14,5 +14,7 @@ public interface IUserService extends ICrudService<User,Long>{

Page<UserDTO> getAllUsers(Pageable pageable);

UserDTO createUser(UserDTO userDTO);
UserDTO createUser(User user);

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

0 comments on commit 31a4bb5

Please sign in to comment.