Refactor authentication and user service. Adding Tests for UserService.java and AuthenticationService.java
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
This commit is contained in:
@@ -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, "");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,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,7 +35,7 @@ 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);
|
||||
}
|
||||
|
||||
@@ -43,7 +47,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();
|
||||
}
|
||||
@@ -54,7 +58,8 @@ 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) {
|
||||
public ResponseEntity<Void> changePrivateName(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPrivateName) {
|
||||
this.userService.changePrivateName(id, newPrivateName);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -67,7 +72,8 @@ public class UserController {
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/changePassword/{id}")
|
||||
public ResponseEntity<Object> changePassword(@PathVariable Long id, @RequestParam String newPassword) {
|
||||
public ResponseEntity<Object> changePassword(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newPassword) {
|
||||
this.userService.changePassword(id, newPassword);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -80,7 +86,8 @@ public class UserController {
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/changeEmail/{id}")
|
||||
public ResponseEntity<Object> changeEmail(@PathVariable Long id, @RequestParam String newEmail) {
|
||||
public ResponseEntity<Object> changeEmail(@PathVariable @NotNull Long id,
|
||||
@RequestParam @NotBlank String newEmail) {
|
||||
this.userService.changeEmail(id, newEmail);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
@@ -93,7 +100,7 @@ public class UserController {
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@PutMapping("/changeVisibilityPrivacy")
|
||||
public ResponseEntity<Void> changeVisibilityPrivacy(@RequestParam VisibilityPrivacy visibilityPrivacy) {
|
||||
public ResponseEntity<Void> changeVisibilityPrivacy(@RequestParam @NotNull VisibilityPrivacy visibilityPrivacy) {
|
||||
this.userService.changeVisibilityPrivacy(visibilityPrivacy);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ public class UserDTO {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public UserDTO(){}
|
||||
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
|
||||
@@ -11,34 +11,43 @@ 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;
|
||||
|
||||
@Autowired
|
||||
public UserService(UserRepository userRepository) {
|
||||
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
|
||||
this.userRepository = userRepository;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
}
|
||||
|
||||
|
||||
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,29 +68,42 @@ 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) {
|
||||
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);
|
||||
sender.setPassword(passwordEncoder.encode(newPassword));
|
||||
userRepository.save(sender);
|
||||
}
|
||||
|
||||
@@ -90,7 +112,19 @@ public class UserService {
|
||||
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
|
||||
|
||||
sender.setEmail(newEmail);
|
||||
userRepository.save(sender);
|
||||
}
|
||||
@@ -103,10 +137,22 @@ public class UserService {
|
||||
public void changePrivateName(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 User getSender() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth == null || !auth.isAuthenticated()) {
|
||||
throw new RuntimeException("Nicht authentifiziert");
|
||||
}
|
||||
return userRepository.findByEmail(auth.getName()).get();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user