test_current #2
@@ -134,7 +134,7 @@
|
||||
<version>1.18.30</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
<compilerArgs>--enable-preview</compilerArgs>
|
||||
<!--<compilerArgs>- -enable-preview</compilerArgs> -->
|
||||
</configuration>
|
||||
</plugin>
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ public class RegistrationResponseDTO {
|
||||
private UserDTO userDTO;
|
||||
@Nullable
|
||||
private String jwt;
|
||||
private RegistrationStatus registrationStatus;
|
||||
private RegistrationStatus status;
|
||||
|
||||
public RegistrationResponseDTO(@Nullable UserDTO userDTO, String jwt, RegistrationStatus registrationStatus) {
|
||||
public RegistrationResponseDTO(@Nullable UserDTO userDTO, String jwt, RegistrationStatus status) {
|
||||
this.userDTO = userDTO;
|
||||
this.jwt = jwt;
|
||||
this.registrationStatus = registrationStatus;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
@@ -34,11 +34,7 @@ public class RegistrationResponseDTO {
|
||||
this.jwt = jwt;
|
||||
}
|
||||
|
||||
public RegistrationStatus getRegistrationStatus() {
|
||||
return registrationStatus;
|
||||
}
|
||||
public RegistrationStatus getStatus() { return status; }
|
||||
|
||||
public void setRegistrationStatus(RegistrationStatus registrationStatus) {
|
||||
this.registrationStatus = registrationStatus;
|
||||
}
|
||||
public void setStatus(RegistrationStatus status) { this.status = status; }
|
||||
}
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
package SuMoC.backend.security.dtos;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class UserAuthenticationPairDTO {
|
||||
|
||||
@NotNull
|
||||
private String email;
|
||||
|
||||
@NotNull
|
||||
private String password;
|
||||
|
||||
public UserAuthenticationPairDTO(String email, String password) {
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
package SuMoC.backend.security.dtos;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
public class UserRegistrationDTO {
|
||||
|
||||
@NotNull
|
||||
private String privateName;
|
||||
|
||||
@NotNull
|
||||
private String publicName;
|
||||
|
||||
@NotNull
|
||||
private String email;
|
||||
|
||||
@NotNull
|
||||
private String password;
|
||||
|
||||
public UserRegistrationDTO(String privateName, String publicName, String email, String password) {
|
||||
|
||||
@@ -99,17 +99,18 @@ public class AuthenticationService {
|
||||
new UsernamePasswordAuthenticationToken(authPairDTO.getEmail(), authPairDTO.getPassword())
|
||||
);
|
||||
|
||||
User user = userRepository.findByEmail(authPairDTO.getEmail()).get();
|
||||
System.out.println(user.getEmail());
|
||||
User user = userRepository.findByEmail(authPairDTO.getEmail())
|
||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||
|
||||
UserDTO userDTO = userMapper.toUserDTO(user);
|
||||
// TODO patch, commented out
|
||||
//UserDTO userDTO = new UserDTO(user.getId(), user.getUsername(), user.getRoles());
|
||||
|
||||
String token = tokenService.generateUserJwt(auth, userDTO);
|
||||
return new LoginResponseDTO(userDTO, token);
|
||||
|
||||
} catch (AuthenticationException e) {
|
||||
System.out.println("AuthenticationException: " + e.getMessage());
|
||||
//System.out.println("AuthenticationException: " + e.getMessage());
|
||||
return new LoginResponseDTO(null, "");
|
||||
} catch ( RuntimeException e) {
|
||||
return new LoginResponseDTO(null, "");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,30 @@ public class TokenService {
|
||||
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
||||
}
|
||||
|
||||
|
||||
// Re-Authentification after change of email
|
||||
public String generateUserJwt(Authentication auth, UserDTO userDTO, String email){
|
||||
|
||||
System.out.println(auth.getName());
|
||||
|
||||
Instant now = Instant.now();
|
||||
|
||||
List<String> roles = auth.getAuthorities().stream()
|
||||
.map(authority -> authority.getAuthority().replace("ROLE_", "")) // <- WICHTIG!
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//CLAIMS define the Payload of the JWT, stores user Data etc. Payload is not encrypted, so no secret data shall be saved stored in a jwt
|
||||
JwtClaimsSet claims = JwtClaimsSet.builder()
|
||||
.issuer("self")
|
||||
.issuedAt(now)
|
||||
.subject(email)
|
||||
.claim("roles",roles)
|
||||
.claim("userId", userDTO.getId())
|
||||
.claim("privateName", userDTO.getPrivateName())
|
||||
.build();
|
||||
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
||||
}
|
||||
|
||||
//TODO: change return type
|
||||
public void decodeJwt(String jwt){
|
||||
System.out.println("###############DECODED JWT##################");
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package SuMoC.backend.user.controller;
|
||||
|
||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.service.UserService;
|
||||
@@ -8,11 +10,15 @@ import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
public class UserController {
|
||||
@@ -31,10 +37,22 @@ public class UserController {
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@GetMapping("/profile/{id}")
|
||||
public ResponseEntity<MinimalUserDTO> getUser(@PathVariable long id) {
|
||||
public ResponseEntity<MinimalUserDTO> getUser(@PathVariable @NotNull long id) {
|
||||
return new ResponseEntity<>(this.userService.getUser(id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Operation(summary = "Nutzer fragt sein eigenes Profil an", description = "Ein Nutzer kann sein eigenes Profil anfragen, um dessen Informationen einzusehen.")
|
||||
@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",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@GetMapping("/profile")
|
||||
public ResponseEntity<MaximalUserDTO> getUser() {
|
||||
return new ResponseEntity<>(this.userService.getSelf(), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@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",
|
||||
@@ -43,7 +61,7 @@ public class UserController {
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public ResponseEntity<Object> deleteUser(@PathVariable Long id) {
|
||||
public ResponseEntity<Object> deleteUser(@PathVariable @NotNull Long id) {
|
||||
this.userService.deleteUser(id);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -53,9 +71,10 @@ 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.")
|
||||
@PutMapping("/changePrivateName/{id}")
|
||||
public ResponseEntity<Void> changePrivateName(@PathVariable Long id, @RequestParam String newPrivateName) {
|
||||
this.userService.changePrivateName(id, newPrivateName);
|
||||
@PutMapping("/setPrivateName/{id}")
|
||||
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPrivateName) {
|
||||
this.userService.setPrivateName(id, newPrivateName);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@@ -66,10 +85,10 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/changePassword/{id}")
|
||||
public ResponseEntity<Object> changePassword(@PathVariable Long id, @RequestParam String newPassword) {
|
||||
this.userService.changePassword(id, newPassword);
|
||||
return ResponseEntity.ok().build();
|
||||
@PutMapping("/setPassword/{id}")
|
||||
public ResponseEntity<LoginResponseDTO> setPassword(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPassword) {
|
||||
return new ResponseEntity<>(this.userService.setPassword(id, newPassword), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Operation(summary = "Nutzer ändert seine E-Mail-Adresse", description = "Ein Nutzer kann seine E-Mail-Adresse ändern, um sicherzustellen, dass seine Kontaktdaten aktuell sind.")
|
||||
@@ -79,10 +98,10 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/changeEmail/{id}")
|
||||
public ResponseEntity<Object> changeEmail(@PathVariable Long id, @RequestParam String newEmail) {
|
||||
this.userService.changeEmail(id, newEmail);
|
||||
return ResponseEntity.ok().build();
|
||||
@PutMapping("/setEmail/{id}")
|
||||
public ResponseEntity<LoginResponseDTO> setEmail(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newEmail) {
|
||||
return new ResponseEntity<>(this.userService.setEmail(id, newEmail), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Operation(summary = "Nutzer ändert seine Sichtbarkeits- und Datenschutzeinstellungen", description = "Ein Nutzer kann seine Sichtbarkeits- und Datenschutzeinstellungen ändern, um zu steuern, wer seine Informationen sehen kann.")
|
||||
@@ -92,9 +111,9 @@ public class UserController {
|
||||
@ApiResponse(responseCode = "400", description = "Ungültige Eingabedaten",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/changeVisibilityPrivacy")
|
||||
public ResponseEntity<Void> changeVisibilityPrivacy(@RequestParam VisibilityPrivacy visibilityPrivacy) {
|
||||
this.userService.changeVisibilityPrivacy(visibilityPrivacy);
|
||||
@PutMapping("/setVisibilityPrivacy")
|
||||
public ResponseEntity<Void> setVisibilityPrivacy(@RequestParam @NotNull VisibilityPrivacy visibilityPrivacy) {
|
||||
this.userService.setVisibilityPrivacy(visibilityPrivacy);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package SuMoC.backend.user.dtos;
|
||||
|
||||
import SuMoC.backend.trip.models.Trip;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.models.Friendship;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class MaximalUserDTO {
|
||||
|
||||
private Long id;
|
||||
|
||||
private String publicName;
|
||||
|
||||
private String privateName;
|
||||
|
||||
private String email;
|
||||
|
||||
private VisibilityPrivacy visibilityPrivacy;
|
||||
|
||||
private Set<Trip> trips;
|
||||
|
||||
private Set<Friendship> friendships;
|
||||
|
||||
public MaximalUserDTO() {
|
||||
}
|
||||
|
||||
public MaximalUserDTO(Long id, String publicName, String privateName, String email, VisibilityPrivacy visibilityPrivacy, Set<Trip> trips, Set<Friendship> friendships) {
|
||||
this.id = id;
|
||||
this.publicName = publicName;
|
||||
this.privateName = privateName;
|
||||
this.email = email;
|
||||
this.visibilityPrivacy = visibilityPrivacy;
|
||||
this.trips = trips;
|
||||
this.friendships = friendships;
|
||||
}
|
||||
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getPublicName() {
|
||||
return publicName;
|
||||
}
|
||||
|
||||
public void setPublicName(String publicName) {
|
||||
this.publicName = publicName;
|
||||
}
|
||||
|
||||
public String getPrivateName() {
|
||||
return privateName;
|
||||
}
|
||||
|
||||
public void setPrivateName(String privateName) {
|
||||
this.privateName = privateName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public VisibilityPrivacy getVisibilityPrivacy() {
|
||||
return visibilityPrivacy;
|
||||
}
|
||||
|
||||
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||
this.visibilityPrivacy = visibilityPrivacy;
|
||||
}
|
||||
|
||||
public Set<Trip> getTrips() {
|
||||
return trips;
|
||||
}
|
||||
|
||||
public void setTrips(Set<Trip> trips) {
|
||||
this.trips = trips;
|
||||
}
|
||||
|
||||
public Set<Friendship> getFriendships() {
|
||||
return friendships;
|
||||
}
|
||||
|
||||
public void setFriendships(Set<Friendship> friendships) {
|
||||
this.friendships = friendships;
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ public class UserDTO {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public UserDTO(){}
|
||||
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
|
||||
@@ -4,7 +4,11 @@ import SuMoC.backend.user.dtos.FriendshipDTO;
|
||||
import SuMoC.backend.user.models.Friendship;
|
||||
import org.mapstruct.Mapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper(componentModel = "spring", uses = UserMapper.class)
|
||||
public interface FriendshipMapper {
|
||||
FriendshipDTO toFriendshipDTO(Friendship friendship);
|
||||
|
||||
List<FriendshipDTO> toFriendshipDTOs(List<Friendship> friendships);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package SuMoC.backend.user.mapper;
|
||||
|
||||
|
||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||
import SuMoC.backend.user.dtos.UserDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import org.mapstruct.Mapper;
|
||||
@@ -10,6 +11,8 @@ public interface UserMapper {
|
||||
UserDTO toUserDTO(User user);
|
||||
|
||||
User toUser(UserDTO userDTO);
|
||||
|
||||
MaximalUserDTO toMaximalUserDTO(User user);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
package SuMoC.backend.user.service;
|
||||
|
||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||
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;
|
||||
@@ -11,34 +17,53 @@ import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
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;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class UserService {
|
||||
|
||||
private final UserRepository userRepository;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final UserMapper userMapper;
|
||||
private final FriendshipMapper friendshipMapper;
|
||||
private final TripMapper tripMapper;
|
||||
|
||||
private final TokenService tokenService;;
|
||||
|
||||
@Autowired
|
||||
public UserService(UserRepository userRepository) {
|
||||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, FriendshipMapper friendshipMapper, TripMapper tripMapper, TokenService tokenService) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.userMapper = userMapper;
|
||||
this.friendshipMapper = friendshipMapper;
|
||||
this.tripMapper = tripMapper;
|
||||
this.tokenService = tokenService;
|
||||
}
|
||||
|
||||
|
||||
public MinimalUserDTO getUser(long id) {
|
||||
User sender = getSender();
|
||||
|
||||
User requested = userRepository.findById(id).get();
|
||||
|
||||
FriendShipStatus status;
|
||||
// Prüfen, ob eine Freundschaft zum Sender existiert
|
||||
FriendShipStatus 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
|
||||
|
||||
if (status == FriendShipStatus.BLOCKED) throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
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
|
||||
}
|
||||
if (FriendShipStatus.BLOCKED.equals(status)) throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
|
||||
//TODO: Think about private profile visibility heuristics
|
||||
// if (requested.getVisibilityPrivacy() == VisibilityPrivacy.PRIVATE && !status.equals(FriendShipStatus.ACCEPTED)) {
|
||||
// if (requested.getVisibilityPrivacy() == VisibilityPrivacy.NONE && !status.equals(FriendShipStatus.ACCEPTED)) {
|
||||
// throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
// }
|
||||
|
||||
@@ -59,54 +84,122 @@ public class UserService {
|
||||
|
||||
}
|
||||
|
||||
|
||||
public void deleteUser(Long id) {
|
||||
User sender = getSender();
|
||||
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
boolean isAdmin = sender.getRoles().contains(RoleName.ADMIN);
|
||||
boolean isOwnProfile = sender.getId().equals(id);
|
||||
|
||||
if (!isAdmin && !isOwnProfile) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Profil löschen.");
|
||||
}
|
||||
// User is admin or deleting own profile
|
||||
|
||||
if (!userRepository.existsById(id)) {
|
||||
throw new RuntimeException("User existiert nicht.");
|
||||
}
|
||||
|
||||
userRepository.deleteById(id);
|
||||
}
|
||||
|
||||
public User getSender() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
return userRepository.findByEmail(authentication.getName()).get();
|
||||
}
|
||||
|
||||
public void changePassword(Long id, String newPassword) {
|
||||
|
||||
|
||||
public LoginResponseDTO setPassword(Long id, String newPassword) {
|
||||
User sender = getSender();
|
||||
if (!sender.getId().equals(id)) {
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Passwort ändern.");
|
||||
}
|
||||
|
||||
if (newPassword.isBlank()) {
|
||||
throw new RuntimeException("Das Passwort darf nicht leer sein.");
|
||||
}
|
||||
|
||||
if (newPassword.length() < 8) {
|
||||
throw new RuntimeException("Das Passwort muss mindestens 8 Zeichen lang sein.");
|
||||
}
|
||||
// TODO: Add Email Notification for password change
|
||||
sender.setPassword(newPassword);
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
sender.setPassword(passwordEncoder.encode(newPassword));
|
||||
userRepository.save(sender);
|
||||
|
||||
User updatedSender = userRepository.findById(id).get();
|
||||
|
||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedSender),
|
||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedSender)));
|
||||
|
||||
}
|
||||
|
||||
public void changeEmail(Long id, String newEmail) {
|
||||
public LoginResponseDTO setEmail(Long id, String newEmail) {
|
||||
User sender = getSender();
|
||||
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.");
|
||||
}
|
||||
|
||||
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.");
|
||||
}
|
||||
|
||||
|
||||
// TODO: Add Email Notification for password change
|
||||
System.out.println("################ Changing Email ################");
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
sender.setEmail(newEmail);
|
||||
userRepository.save(sender);
|
||||
|
||||
User updatedUser = userRepository.findById(sender.getId()).orElseThrow();
|
||||
System.out.println("################# Returning LoginResponse ################");
|
||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedUser),
|
||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedUser), newEmail));
|
||||
}
|
||||
|
||||
public void changeVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||
User user = getSender();
|
||||
user.setVisibilityPrivacy(visibilityPrivacy);
|
||||
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||
User sender = getSender();
|
||||
|
||||
sender.setVisibilityPrivacy(visibilityPrivacy);
|
||||
userRepository.save(sender);
|
||||
|
||||
}
|
||||
|
||||
public void changePrivateName(Long id, String newPrivateName) {
|
||||
public void setPrivateName(Long id, String newPrivateName) {
|
||||
User sender = getSender();
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
throw new RuntimeException("Not allowed to change private name of other users unless admin.");
|
||||
throw new RuntimeException("Ein Nutzer kann nur seinen eigenen privaten Namen ändern.");
|
||||
}
|
||||
User userToChange = userRepository.findById(id).orElseThrow();
|
||||
userToChange.setPrivateName(newPrivateName);
|
||||
userRepository.save(userToChange);
|
||||
}
|
||||
|
||||
|
||||
public MaximalUserDTO getSelf() {
|
||||
User sender = getSender();
|
||||
return userMapper.toMaximalUserDTO(sender);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public User getSender() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
throw new RuntimeException("Nicht authentifiziert");
|
||||
}
|
||||
|
||||
return userRepository.findByEmail(auth.getName())
|
||||
.orElseThrow(() -> new RuntimeException(
|
||||
"Authentifizierter Nutzer existiert nicht mehr: " + auth.getName()
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package SuMoC.backend.Factories;
|
||||
|
||||
|
||||
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
|
||||
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||
import SuMoC.backend.user.dtos.UserDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
|
||||
|
||||
public class UserTestFactory {
|
||||
|
||||
private UserTestFactory() {}
|
||||
|
||||
public static User validUser() {
|
||||
User user = new User(
|
||||
"privateName",
|
||||
"publicName",
|
||||
"test@test.de",
|
||||
"password"
|
||||
);
|
||||
return user;
|
||||
}
|
||||
|
||||
public static User userWithEmail(String email) {
|
||||
User user = validUser();
|
||||
user.setEmail(email);
|
||||
return user;
|
||||
}
|
||||
|
||||
public static User uniqueUser(int i) {
|
||||
return new User(
|
||||
"privateName" + i,
|
||||
"publicName" + i,
|
||||
"test" + i + "@test.de",
|
||||
"password" + i
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
public static UserDTO getUserDTO(User user) {
|
||||
return new UserDTO(
|
||||
user.getId(),
|
||||
user.getPrivateName(),
|
||||
user.getPublicName(),
|
||||
user.getRoles()
|
||||
);
|
||||
}
|
||||
|
||||
public static UserRegistrationDTO getUserRegistrationDTO(User user) {
|
||||
return new UserRegistrationDTO(
|
||||
user.getPrivateName(),
|
||||
user.getPublicName(),
|
||||
user.getEmail(),
|
||||
user.getPassword()
|
||||
);
|
||||
}
|
||||
|
||||
public static UserAuthenticationPairDTO getUserAuthenticationPairDTO(User user) {
|
||||
return new UserAuthenticationPairDTO(
|
||||
user.getEmail(),
|
||||
user.getPassword()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package SuMoC.backend.security;
|
||||
|
||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||
import SuMoC.backend.security.dtos.RegistrationResponseDTO;
|
||||
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
|
||||
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||
import SuMoC.backend.security.enums.RegistrationStatus;
|
||||
import SuMoC.backend.security.services.AuthenticationService;
|
||||
|
||||
import SuMoC.backend.user.dtos.UserDTO;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static SuMoC.backend.Factories.UserTestFactory.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
|
||||
public class AuthentificationServiceTest {
|
||||
|
||||
@Autowired
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
|
||||
@Test
|
||||
public void testRegistrationSuccessful() {
|
||||
User user = validUser();
|
||||
UserDTO userDTO = getUserDTO(user);
|
||||
|
||||
RegistrationResponseDTO responseDTO =
|
||||
authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
|
||||
assertNotNull(responseDTO);
|
||||
assertNotNull(responseDTO.getStatus());
|
||||
assertNotNull(responseDTO.getUserDTO());
|
||||
assertNotNull(responseDTO.getJwt());
|
||||
|
||||
assertEquals(RegistrationStatus.SUCCESS, responseDTO.getStatus());
|
||||
|
||||
assertNotNull(responseDTO.getUserDTO().getId());
|
||||
assertEquals(userDTO.getPrivateName(), responseDTO.getUserDTO().getPrivateName());
|
||||
assertEquals(userDTO.getPublicName(), responseDTO.getUserDTO().getPublicName());
|
||||
assertEquals(userDTO.getRoles(), responseDTO.getUserDTO().getRoles());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegistrationUnsuccessful() {
|
||||
|
||||
// Register normal user
|
||||
User user = validUser();
|
||||
UserDTO userDTO = getUserDTO(user);
|
||||
|
||||
RegistrationResponseDTO responseDTO =
|
||||
authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
|
||||
assertNotNull(responseDTO);
|
||||
assertEquals(RegistrationStatus.SUCCESS, responseDTO.getStatus());
|
||||
|
||||
// Register again with same data
|
||||
|
||||
// Same user with same email
|
||||
RegistrationResponseDTO responseError = authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
|
||||
assertNotNull(responseDTO);
|
||||
assertEquals(RegistrationStatus.EMAIL_EXISTS, responseError.getStatus());
|
||||
assertNull(responseError.getUserDTO());
|
||||
assertNull(responseError.getJwt());
|
||||
|
||||
|
||||
// Same public name
|
||||
user.setEmail("ab@bc.de");
|
||||
RegistrationResponseDTO responseError2 = authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
|
||||
assertNotNull(responseDTO);
|
||||
assertEquals(RegistrationStatus.PUBLIC_NAME_EXISTS, responseError2.getStatus());
|
||||
assertNull(responseError2.getUserDTO());
|
||||
assertNull(responseError2.getJwt());
|
||||
|
||||
// Register with invalid data
|
||||
|
||||
// Invalid email
|
||||
user.setEmail("test");
|
||||
user.setPublicName("uniquePublicName");
|
||||
RegistrationResponseDTO responseError3 = authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
assertEquals(RegistrationStatus.EMAIL_INVALID, responseError3.getStatus());
|
||||
assertNull(responseError3.getUserDTO());
|
||||
assertNull(responseError3.getJwt());
|
||||
|
||||
// Register with empty data
|
||||
user.setEmail("");
|
||||
user.setPublicName("");
|
||||
RegistrationResponseDTO responseError4 = authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
assertEquals(RegistrationStatus.EMAIL_INVALID, responseError4.getStatus());
|
||||
assertNull(responseError4.getUserDTO());
|
||||
assertNull(responseError4.getJwt());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRegistrationMultipleUsers() {
|
||||
for (int i = 0; i < 10; i++) {
|
||||
User user = uniqueUser(i);
|
||||
|
||||
RegistrationResponseDTO responseDTO = authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
|
||||
assertEquals(RegistrationStatus.SUCCESS, responseDTO.getStatus());
|
||||
assertNotNull(responseDTO.getUserDTO());
|
||||
assertNotNull(responseDTO.getJwt());
|
||||
|
||||
assertEquals(user.getPrivateName(), responseDTO.getUserDTO().getPrivateName());
|
||||
assertEquals(user.getPublicName(), responseDTO.getUserDTO().getPublicName());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testLoginSuccessful() {
|
||||
User user = validUser();
|
||||
UserAuthenticationPairDTO authPair = getUserAuthenticationPairDTO(user);
|
||||
|
||||
// First register the user
|
||||
RegistrationResponseDTO responseDTO = authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
assertNotNull(responseDTO);
|
||||
assertEquals(RegistrationStatus.SUCCESS, responseDTO.getStatus());
|
||||
|
||||
User dbUser = userRepository.findByEmail(user.getEmail()).get();
|
||||
|
||||
|
||||
// Login with correct credentials
|
||||
LoginResponseDTO loginResponse = authenticationService.login(authPair);
|
||||
assertNotNull(loginResponse);
|
||||
assertNotNull(loginResponse.getUserDTO());
|
||||
assertNotNull(loginResponse.getJwt());
|
||||
|
||||
assertEquals(user.getPrivateName(), loginResponse.getUserDTO().getPrivateName());
|
||||
assertEquals(user.getPublicName(), loginResponse.getUserDTO().getPublicName());
|
||||
|
||||
assertEquals(dbUser.getId(), loginResponse.getUserDTO().getId());
|
||||
assertEquals(dbUser.getPrivateName(), loginResponse.getUserDTO().getPrivateName());
|
||||
assertEquals(dbUser.getPublicName(), loginResponse.getUserDTO().getPublicName());
|
||||
assertEquals(dbUser.getRoles(), loginResponse.getUserDTO().getRoles());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoginUnsuccessful() {
|
||||
User user = validUser();
|
||||
|
||||
// First, register the user
|
||||
RegistrationResponseDTO responseDTO = authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||
assertNotNull(responseDTO);
|
||||
assertEquals(RegistrationStatus.SUCCESS, responseDTO.getStatus());
|
||||
|
||||
User dbUser = userRepository.findByEmail(user.getEmail()).get();
|
||||
assertNotNull(dbUser);
|
||||
assertEquals(dbUser.getId(), responseDTO.getUserDTO().getId());
|
||||
|
||||
// Login with wrong credentials
|
||||
|
||||
// Wrong password
|
||||
LoginResponseDTO loginResponse = authenticationService.login(new UserAuthenticationPairDTO("test@test.de", "wrongPassword"));
|
||||
assertNotNull(loginResponse);
|
||||
assertNull(loginResponse.getUserDTO());
|
||||
assertEquals("", loginResponse.getJwt());
|
||||
|
||||
// Not existing email
|
||||
loginResponse = authenticationService.login(new UserAuthenticationPairDTO("wrongEmail@email.de", "wrongPassword"));
|
||||
assertNotNull(loginResponse);
|
||||
assertNull(loginResponse.getUserDTO());
|
||||
assertEquals("", loginResponse.getJwt());
|
||||
|
||||
// Wrong email format
|
||||
loginResponse = authenticationService.login(new UserAuthenticationPairDTO("wrongEmail", "wrongPassword"));
|
||||
assertNotNull(loginResponse);
|
||||
assertNull(loginResponse.getUserDTO());
|
||||
assertEquals("", loginResponse.getJwt());
|
||||
|
||||
// Empty credentials
|
||||
loginResponse = authenticationService.login(new UserAuthenticationPairDTO("", ""));
|
||||
assertNotNull(loginResponse);
|
||||
assertNull(loginResponse.getUserDTO());
|
||||
assertEquals("", loginResponse.getJwt());
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package SuMoC.backend.user.service;
|
||||
|
||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.user.models.User;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
|
||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.test.context.support.WithMockUser;
|
||||
|
||||
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@SpringBootTest
|
||||
@Transactional
|
||||
@AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2)
|
||||
public class UserServiceTest {
|
||||
|
||||
@Autowired
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
private PasswordEncoder passwordEncoder;
|
||||
|
||||
private User sender;
|
||||
private User differentUser;
|
||||
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
sender = userRepository.save(uniqueUser(1));
|
||||
differentUser = userRepository.save(uniqueUser(2));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||
void testGetUser() {
|
||||
|
||||
// Set different user to Private
|
||||
MinimalUserDTO noneSetting = userService.getUser(differentUser.getId());
|
||||
assertNotNull(noneSetting);
|
||||
assertEquals(differentUser.getPublicName(), noneSetting.getDisplayName());
|
||||
|
||||
// Set different user to Friends Only
|
||||
differentUser.setVisibilityPrivacy(VisibilityPrivacy.FRIENDS_ONLY);
|
||||
userRepository.save(differentUser);
|
||||
MinimalUserDTO friendsOnlySetting = userService.getUser(differentUser.getId());
|
||||
assertNotNull(friendsOnlySetting);
|
||||
assertEquals(differentUser.getPublicName(), friendsOnlySetting.getDisplayName());
|
||||
|
||||
// Set different user to Public
|
||||
differentUser.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
||||
userRepository.save(differentUser);
|
||||
MinimalUserDTO publicSetting = userService.getUser(differentUser.getId());
|
||||
assertNotNull(publicSetting);
|
||||
assertEquals(differentUser.getPublicName(), publicSetting.getDisplayName());
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||
public void testDeleteUser() {
|
||||
// Try deleting another user
|
||||
assertThrows(RuntimeException.class, () -> userService.deleteUser(differentUser.getId()));
|
||||
assertEquals(2, userRepository.count());
|
||||
|
||||
|
||||
// Deleting own Profile
|
||||
userService.deleteUser(sender.getId());
|
||||
assertEquals(1, userRepository.count());
|
||||
|
||||
assertTrue(userRepository.findById(sender.getId()).isEmpty());
|
||||
assertTrue(userRepository.findById(differentUser.getId()).isPresent());
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||
public void testSetPassword() {
|
||||
String newPassword = "newPassword";
|
||||
|
||||
// Check if user can change different user's password
|
||||
assertThrows(RuntimeException.class, () -> userService.setPassword(differentUser.getId(), newPassword));
|
||||
assertEquals(differentUser.getPassword(), userRepository.findById(differentUser.getId()).get().getPassword());
|
||||
|
||||
// Check if user can change his own password
|
||||
|
||||
// Too short password
|
||||
assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test"));
|
||||
// TODO: check why this assertion fails (most likely because of password encoding internals)
|
||||
// assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword()));
|
||||
|
||||
// Valid password
|
||||
userService.setPassword(sender.getId(), newPassword);
|
||||
assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword()));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||
public void testSetEmail() {
|
||||
String newEmail = "wd@wd.wd";
|
||||
String invalidEmail = "test";
|
||||
|
||||
// Check if user can change different user's email
|
||||
assertThrows(RuntimeException.class, () -> userService.setEmail(differentUser.getId(), newEmail));
|
||||
assertEquals(differentUser.getEmail(), userRepository.findById(differentUser.getId()).get().getEmail());
|
||||
|
||||
|
||||
// Check if user can change his own email
|
||||
|
||||
// Other user's email
|
||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail()));
|
||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||
|
||||
// Invalid email format
|
||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail));
|
||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||
|
||||
// Valid email
|
||||
userService.setEmail(sender.getId(), newEmail);
|
||||
assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||
public void testSetVisibilityPrivacy() {
|
||||
userService.setVisibilityPrivacy(VisibilityPrivacy.NONE);
|
||||
assertEquals(VisibilityPrivacy.NONE, userRepository.findById(sender.getId()).get().getVisibilityPrivacy());
|
||||
|
||||
userService.setVisibilityPrivacy(VisibilityPrivacy.FRIENDS_ONLY);
|
||||
assertEquals(VisibilityPrivacy.FRIENDS_ONLY, userRepository.findById(sender.getId()).get().getVisibilityPrivacy());
|
||||
|
||||
userService.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
||||
assertEquals(VisibilityPrivacy.PUBLIC, userRepository.findById(sender.getId()).get().getVisibilityPrivacy());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||
public void testSetPrivateName() {
|
||||
String newPrivateName = "newPrivateName";
|
||||
assertThrows(RuntimeException.class, () -> userService.setPrivateName(differentUser.getId(), newPrivateName));
|
||||
assertEquals(differentUser.getPrivateName(), userRepository.findById(differentUser.getId()).get().getPrivateName());
|
||||
|
||||
userService.setPrivateName(sender.getId(), newPrivateName);
|
||||
assertEquals(newPrivateName, userRepository.findById(sender.getId()).get().getPrivateName());
|
||||
}
|
||||
|
||||
@Test
|
||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||
public void testGetSelf() {
|
||||
MaximalUserDTO selfDTO = userService.getSelf();
|
||||
assertNotNull(selfDTO);
|
||||
assertEquals(sender.getId(), selfDTO.getId());
|
||||
assertEquals(sender.getPublicName(), selfDTO.getPublicName());
|
||||
assertEquals(sender.getPrivateName(), selfDTO.getPrivateName());
|
||||
assertEquals(sender.getEmail(), selfDTO.getEmail());
|
||||
assertEquals(sender.getVisibilityPrivacy(), selfDTO.getVisibilityPrivacy());
|
||||
assertEquals(0, selfDTO.getTrips().size());
|
||||
assertEquals(0, selfDTO.getFriendships().size());
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user