Enhance user privacy checks and improve error handling in user services
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
This commit is contained in:
@@ -6,6 +6,7 @@ import SuMoC.backend.gamification.badges.models.UserBadge;
|
||||
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.service.CurrentUserService;
|
||||
import SuMoC.backend.user.service.PrivacyService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -25,11 +26,13 @@ public class BadgeService {
|
||||
private final BadgeRepository badgeRepository;
|
||||
|
||||
private final UserBadgeRepository userBadgeRepository;
|
||||
private final PrivacyService privacyService;
|
||||
|
||||
public BadgeService(CurrentUserService currentUser, BadgeRepository badgeRepository, UserBadgeRepository userBadgeRepository) {
|
||||
public BadgeService(CurrentUserService currentUser, BadgeRepository badgeRepository, UserBadgeRepository userBadgeRepository, PrivacyService privacyService) {
|
||||
this.currentUser = currentUser;
|
||||
this.badgeRepository = badgeRepository;
|
||||
this.userBadgeRepository = userBadgeRepository;
|
||||
this.privacyService = privacyService;
|
||||
}
|
||||
|
||||
public Badge createBadge(Badge badge) {
|
||||
@@ -105,7 +108,9 @@ public class BadgeService {
|
||||
if(Objects.equals(id, sender.getId())) {
|
||||
badges = userBadgeRepository.findByUserId(sender.getId());
|
||||
} else {
|
||||
// TODO: Add Privacy/Friendship Heuristics
|
||||
if(privacyService.checkVisibility(sender, id)) {
|
||||
badges = userBadgeRepository.findByUserId(id);
|
||||
}
|
||||
}
|
||||
|
||||
return badges.stream()
|
||||
|
||||
@@ -33,6 +33,8 @@ public class UserController {
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich abgerufen",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MinimalUserDTO.class))),
|
||||
@ApiResponse(responseCode = "403", description = "Nutzerprofil darf nicht aufgerufen werden",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Nutzerprofil nicht gefunden",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@@ -45,7 +47,7 @@ public class UserController {
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich abgerufen",
|
||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = MinimalUserDTO.class))),
|
||||
@ApiResponse(responseCode = "404", description = "Nutzerprofil nicht gefunden",
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@GetMapping("/profile")
|
||||
@@ -55,10 +57,9 @@ public class UserController {
|
||||
|
||||
@Operation(summary = "Nutzer löscht sein eigenes Profil", description = "Ein Nutzer kann sein eigenes Profil löschen. Dies entfernt alle seine Daten aus dem System.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich gelöscht",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Nutzerprofil nicht gefunden",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
@ApiResponse(responseCode = "200", description = "Nutzerprofil erfolgreich gelöscht"),
|
||||
@ApiResponse(responseCode = "403", description = "Keine Berechtigung, fremdes Profil zu löschen"),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht")
|
||||
})
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public ResponseEntity<Object> deleteUser(@PathVariable @NotNull Long id) {
|
||||
@@ -71,6 +72,16 @@ public class UserController {
|
||||
}
|
||||
|
||||
@Operation(summary = "Update a users private name.", description = "A user can change it's own private name that is shown to friends.")
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(responseCode = "200", description = "Passwort erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Nur autorisierte Personen dürfen das Passwort ändern",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setPrivateName/{id}")
|
||||
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPrivateName) {
|
||||
@@ -83,6 +94,10 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "200", description = "Passwort erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Nur autorisierte Personen dürfen das Passwort ändern",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setPassword/{id}")
|
||||
@@ -96,6 +111,12 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "200", description = "E-Mail-Adresse erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Nur autorisierte Personen dürfen die Email ändern",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Der Nutzer existiert nicht",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "409", description = "Die Email wurde bereits vergeben",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setEmail/{id}")
|
||||
@@ -109,6 +130,10 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "200", description = "Sichtbarkeits- und Datenschutzeinstellungen erfolgreich geändert",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "403", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "409", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/setVisibilityPrivacy")
|
||||
|
||||
@@ -2,9 +2,11 @@ package SuMoC.backend.user.service;
|
||||
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
@Component
|
||||
public class CurrentUserService {
|
||||
@@ -19,10 +21,14 @@ public class CurrentUserService {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
throw new RuntimeException("Nicht authentifiziert");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
"Nicht authentifiziert");
|
||||
}
|
||||
|
||||
return userRepository.findByEmail(auth.getName())
|
||||
.orElseThrow(() -> new RuntimeException("User existiert nicht mehr"));
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Der Nutzer existiert nicht"));
|
||||
}
|
||||
}
|
||||
@@ -5,20 +5,21 @@ import SuMoC.backend.security.services.TokenService;
|
||||
import SuMoC.backend.trip.TripMapper;
|
||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import SuMoC.backend.user.enums.RoleName;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.mapper.FriendshipMapper;
|
||||
import SuMoC.backend.user.mapper.UserMapper;
|
||||
import SuMoC.backend.user.models.Friendship;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
@@ -29,61 +30,44 @@ public class UserService {
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final FriendshipMapper friendshipMapper;
|
||||
private final TripMapper tripMapper;
|
||||
|
||||
private final TokenService tokenService;;
|
||||
private final PrivacyService privacyService;
|
||||
private final FriendshipService friendshipService;
|
||||
|
||||
@Autowired
|
||||
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, FriendshipMapper friendshipMapper, TripMapper tripMapper, TokenService tokenService) {
|
||||
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService) {
|
||||
this.currentUser = currentUser;
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.userMapper = userMapper;
|
||||
this.friendshipMapper = friendshipMapper;
|
||||
this.tripMapper = tripMapper;
|
||||
this.tokenService = tokenService;
|
||||
this.privacyService = privacyService;
|
||||
this.friendshipService = friendshipService;
|
||||
}
|
||||
|
||||
|
||||
public MinimalUserDTO getUser(long id) {
|
||||
User sender = currentUser.get();
|
||||
|
||||
User requested = userRepository.findById(id).get();
|
||||
|
||||
FriendShipStatus status;
|
||||
// Prüfen, ob eine Freundschaft zum Sender existiert
|
||||
if(sender.equals(requested)) {
|
||||
status = FriendShipStatus.ACCEPTED;
|
||||
} else {
|
||||
status = requested.getFriendships().stream()
|
||||
.filter(f -> sender.equals(f.getFriend()) || sender.equals(f.getUser()))
|
||||
.map(Friendship::getStatus)
|
||||
.findFirst()
|
||||
.orElse(null); // nimmt die erste gefundene Freundschaft
|
||||
User requested = userRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND, "Nutzer existiert nicht"
|
||||
));
|
||||
// TODO: Check tomorrow if this makes sense
|
||||
// TODO: Can Users see the minimalDTO if they are blocked?
|
||||
if(friendshipService.getBlockedUsers(id).stream().anyMatch(blocked -> blocked.getId().equals(requested.getId()))) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Der Nutzer hat dich blockiert."
|
||||
);
|
||||
}
|
||||
if (FriendShipStatus.BLOCKED.equals(status)) throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
|
||||
//TODO: Think about private profile visibility heuristics
|
||||
// if (requested.getVisibilityPrivacy() == VisibilityPrivacy.NONE && !status.equals(FriendShipStatus.ACCEPTED)) {
|
||||
// throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
// }
|
||||
|
||||
if (status == null) {
|
||||
if (privacyService.checkVisibility(sender, id)) {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPrivateName());
|
||||
} else {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPublicName());
|
||||
}
|
||||
|
||||
switch (status) {
|
||||
case ACCEPTED -> {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPrivateName());
|
||||
}
|
||||
|
||||
default -> {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPublicName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -94,11 +78,15 @@ public class UserService {
|
||||
boolean isOwnProfile = sender.getId().equals(id);
|
||||
|
||||
if (!isAdmin && !isOwnProfile) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Profil löschen.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Ein Nutzer kann nur sein eigenes Profil löschen.");
|
||||
}
|
||||
|
||||
if (!userRepository.existsById(id)) {
|
||||
throw new RuntimeException("User existiert nicht.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Nutzer existiert nicht.");
|
||||
}
|
||||
|
||||
userRepository.deleteById(id);
|
||||
@@ -110,22 +98,34 @@ public class UserService {
|
||||
public LoginResponseDTO setPassword(Long id, String newPassword) {
|
||||
User sender = currentUser.get();
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Passwort ändern.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Ein Nutzer kann nur sein eigenes Passwort ändern.");
|
||||
}
|
||||
|
||||
if (newPassword.isBlank()) {
|
||||
throw new RuntimeException("Das Passwort darf nicht leer sein.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Das Passwort darf nicht leer sein."
|
||||
);
|
||||
}
|
||||
|
||||
if (newPassword.length() < 8) {
|
||||
throw new RuntimeException("Das Passwort muss mindestens 8 Zeichen lang sein.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Das Passwort muss mindestens 8 Zeichen lang sein."
|
||||
);
|
||||
}
|
||||
// TODO: Add Email Notification for password change
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
sender.setPassword(passwordEncoder.encode(newPassword));
|
||||
userRepository.save(sender);
|
||||
|
||||
User updatedSender = userRepository.findById(id).get();
|
||||
User updatedSender = userRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Nutzer existiert nicht"
|
||||
));
|
||||
|
||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedSender),
|
||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedSender)));
|
||||
@@ -137,18 +137,26 @@ public class UserService {
|
||||
System.out.println(sender.getId());
|
||||
|
||||
if (!sender.getId().equals(id)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur seine eigene E-Mail-Adresse ändern.");
|
||||
}
|
||||
|
||||
if (userRepository.existsByEmail(newEmail)) {
|
||||
throw new RuntimeException("Diese E-Mail ist bereits vergeben.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.FORBIDDEN,
|
||||
"Ein Nutzer kann nur seine eigene E-Mail-Adresse ändern."
|
||||
);
|
||||
}
|
||||
|
||||
String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
|
||||
if (!newEmail.matches(emailRegex)) {
|
||||
throw new RuntimeException("Ungültige E-Mail-Adresse.");
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
"Ungültige E-Mail-Adresse."
|
||||
);
|
||||
}
|
||||
|
||||
if (userRepository.existsByEmail(newEmail)) {
|
||||
throw new ResponseStatusException(
|
||||
HttpStatus.CONFLICT,
|
||||
"Diese E-Mail ist bereits vergeben."
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: Add Email Notification for password change
|
||||
System.out.println("################ Changing Email ################");
|
||||
@@ -156,7 +164,11 @@ public class UserService {
|
||||
sender.setEmail(newEmail);
|
||||
userRepository.save(sender);
|
||||
|
||||
User updatedUser = userRepository.findById(sender.getId()).orElseThrow();
|
||||
User updatedUser = userRepository.findById(sender.getId())
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Der Nutzer existiert nicht"
|
||||
));
|
||||
System.out.println("################# Returning LoginResponse ################");
|
||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedUser),
|
||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedUser), newEmail));
|
||||
@@ -173,9 +185,14 @@ public class UserService {
|
||||
public void setPrivateName(Long id, String newPrivateName) {
|
||||
User sender = currentUser.get();
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur seinen eigenen privaten Namen ändern.");
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Ein Nutzer kann nur seinen eigenen privaten Namen ändern.");
|
||||
}
|
||||
User userToChange = userRepository.findById(id).orElseThrow();
|
||||
User userToChange = userRepository.findById(id)
|
||||
.orElseThrow(() -> new ResponseStatusException(
|
||||
HttpStatus.NOT_FOUND,
|
||||
"Der Nutzer Existitert nicht."));
|
||||
|
||||
// TODO: Add String Validator
|
||||
userToChange.setPrivateName(newPrivateName);
|
||||
userRepository.save(userToChange);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user