Prototypische implementierug der UserService und Controller
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
package SuMoC.backend.controller;
|
||||
|
||||
import SuMoC.backend.models.dto.MinimalUserDTO;
|
||||
import SuMoC.backend.models.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.security.services.Userservice;
|
||||
import SuMoC.backend.service.UserService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
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 org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/user")
|
||||
public class UserController {
|
||||
|
||||
private UserService userService;
|
||||
|
||||
@Autowired
|
||||
public UserController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Nutzer fragt ein fremdes Nutzerprofil an", description = "Ein Nutzer kann das Profil eines anderen Nutzers anfragen, um dessen öffentliche 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{id}")
|
||||
public ResponseEntity<MinimalUserDTO> getUser(@PathVariable long id) {
|
||||
return new ResponseEntity<>(this.userService.getUser(id), 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",
|
||||
content = @Content(mediaType = "application/json")),
|
||||
@ApiResponse(responseCode = "404", description = "Nutzerprofil nicht gefunden",
|
||||
content = @Content(mediaType = "application/json"))
|
||||
})
|
||||
@DeleteMapping("/delete/{id}")
|
||||
public ResponseEntity<Object> deleteUser(@PathVariable Long id) {
|
||||
this.userService.deleteUser(id);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
public void updateUser(Long id){
|
||||
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Nutzer ändert sein Passwort", description = "Ein Nutzer kann sein Passwort ändern, um die Sicherheit seines Kontos zu gewährleisten.")
|
||||
@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"))
|
||||
})
|
||||
@PutMapping("/changePassword/{id}")
|
||||
public ResponseEntity<Object> changePassword(@PathVariable Long id, @RequestParam String newPassword){
|
||||
this.userService.changePassword(id, newPassword);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
@Operation(summary = "Nutzer ändert seine E-Mail-Adresse", description = "Ein Nutzer kann seine E-Mail-Adresse ändern, um sicherzustellen, dass seine Kontaktdaten aktuell sind.")
|
||||
@ApiResponses(value = {
|
||||
@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"))
|
||||
})
|
||||
@PutMapping("/changeEmail/{id}")
|
||||
public ResponseEntity<Object> changeEmail(@PathVariable Long id, @RequestParam String newEmail){
|
||||
this.userService.changeEmail(id, newEmail);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
@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.")
|
||||
@ApiResponses(value = {
|
||||
@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"))
|
||||
})
|
||||
@PutMapping("/changeVisibilityPrivacy")
|
||||
public void changeVisibilityPrivacy(@RequestParam VisibilityPrivacy visibilityPrivacy){
|
||||
this.userService.changeVisibilityPrivacy(visibilityPrivacy);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package SuMoC.backend.models;
|
||||
|
||||
import SuMoC.backend.models.enums.FriendShipStatus;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package SuMoC.backend.models;
|
||||
|
||||
|
||||
import SuMoC.backend.models.enums.Modality;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package SuMoC.backend.models;
|
||||
|
||||
import SuMoC.backend.models.enums.RoleName;
|
||||
import SuMoC.backend.models.enums.VisibilityPrivacy;
|
||||
import jakarta.persistence.*;
|
||||
|
||||
import java.util.HashSet;
|
||||
@@ -51,17 +53,28 @@ public class User {
|
||||
|
||||
public User() {}
|
||||
|
||||
public User(Long id, String publicName, String privateName, String email, String password, VisibilityPrivacy visibilityPrivacy, String friendCode, Set<Trip> trips, Set<Friendship> friendships, Set<RoleName> roles) {
|
||||
this.id = id;
|
||||
// public User(Long id, String publicName, String privateName, String email, String password, VisibilityPrivacy visibilityPrivacy, String friendCode, Set<Trip> trips, Set<Friendship> friendships, Set<RoleName> roles) {
|
||||
// this.id = id;
|
||||
// this.publicName = publicName;
|
||||
// this.privateName = privateName;
|
||||
// this.email = email;
|
||||
// this.password = password;
|
||||
// this.visibilityPrivacy = visibilityPrivacy;
|
||||
// this.friendCode = friendCode;
|
||||
// this.trips = trips;
|
||||
// this.friendships = friendships;
|
||||
// this.roles = roles;
|
||||
// }
|
||||
|
||||
public User(String publicName, String privateName, String email, String password) {
|
||||
this.publicName = publicName;
|
||||
this.privateName = privateName;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.visibilityPrivacy = visibilityPrivacy;
|
||||
this.friendCode = friendCode;
|
||||
this.trips = trips;
|
||||
this.friendships = friendships;
|
||||
this.roles = roles;
|
||||
this.visibilityPrivacy = VisibilityPrivacy.NONE;
|
||||
this.friendCode = java.util.UUID.randomUUID().toString(); // generate unique friend code
|
||||
this.roles = new HashSet<>();
|
||||
this.roles.add(RoleName.USER);
|
||||
}
|
||||
|
||||
// TODO getter for friend users?
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package SuMoC.backend.models.dto;
|
||||
|
||||
public class MinimalUserDTO {
|
||||
|
||||
private Long id;
|
||||
private String displayName;
|
||||
|
||||
|
||||
|
||||
public MinimalUserDTO() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
public MinimalUserDTO(Long id, String username) {
|
||||
this.id = id;
|
||||
this.displayName = username;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,27 @@
|
||||
package SuMoC.backend.models.dto;
|
||||
|
||||
import SuMoC.backend.models.RoleName;
|
||||
import SuMoC.backend.models.enums.RoleName;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
public class UserDTO {
|
||||
private Long userId;
|
||||
private String username;
|
||||
private Set<RoleName> authorities;
|
||||
private String privateName;
|
||||
private String publicName;
|
||||
private Set<RoleName> roles;
|
||||
|
||||
public UserDTO(Long userId, String username, Set<RoleName> authorities){
|
||||
|
||||
|
||||
public UserDTO(Long userId, String privateName, String publicName, Set<RoleName> roles){
|
||||
this.userId = userId;
|
||||
this.username = username;
|
||||
this.authorities = authorities;
|
||||
this.privateName = privateName;
|
||||
this.publicName = publicName;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
|
||||
public Long getUserId() {
|
||||
return userId;
|
||||
}
|
||||
|
||||
public Long getId() {
|
||||
@@ -23,19 +32,27 @@ public class UserDTO {
|
||||
this.userId = userId;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
public Set<RoleName> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
public void setRoles(Set<RoleName> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public Set<RoleName> getAuthorities() {
|
||||
return authorities;
|
||||
public String getPrivateName() {
|
||||
return privateName;
|
||||
}
|
||||
|
||||
public void setAuthorities(Set<RoleName> authorities) {
|
||||
this.authorities = authorities;
|
||||
public void setPrivateName(String privateName) {
|
||||
this.privateName = privateName;
|
||||
}
|
||||
|
||||
public String getPublicName() {
|
||||
return publicName;
|
||||
}
|
||||
|
||||
public void setPublicName(String publicName) {
|
||||
this.publicName = publicName;
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package SuMoC.backend.models;
|
||||
package SuMoC.backend.models.enums;
|
||||
|
||||
public enum FriendShipStatus {
|
||||
PENDING,
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package SuMoC.backend.models;
|
||||
package SuMoC.backend.models.enums;
|
||||
|
||||
public enum Modality {
|
||||
IDLE,
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package SuMoC.backend.models;
|
||||
package SuMoC.backend.models.enums;
|
||||
|
||||
public enum RoleName {
|
||||
USER,
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package SuMoC.backend.models;
|
||||
package SuMoC.backend.models.enums;
|
||||
|
||||
/**
|
||||
* Privacy enum, representing different levels of visibility for the user in leaderboards etc.
|
||||
@@ -0,0 +1,10 @@
|
||||
package SuMoC.backend.repositories;
|
||||
|
||||
import SuMoC.backend.models.Trip;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface TripRepository extends JpaRepository<Trip,Long> {
|
||||
Optional<Trip> findTripById(Long id);
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
|
||||
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
@@ -99,7 +100,14 @@ public class SecurityConfiguration {
|
||||
jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter());
|
||||
});
|
||||
})
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
/* .headers(headers ->
|
||||
headers.xssProtection(
|
||||
xss -> xss.headerValue(XXssProtectionHeaderWriter.HeaderValue.ENABLED_MODE_BLOCK)
|
||||
).contentSecurityPolicy(
|
||||
cps -> cps.policyDirectives("script-src 'self'")
|
||||
))*/;
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ public class UserAuthenticationController {
|
||||
public ResponseEntity<LoginResponseDTO> registerUser(@RequestBody UserRegistrationDTO registrationDTO) {
|
||||
|
||||
System.out.println("###################### Register Request #####################");
|
||||
System.out.println(registrationDTO.getUsername() + " " + registrationDTO.getPassword() + " " + registrationDTO.getEmail());
|
||||
System.out.println(registrationDTO.getPublicName() + " " + registrationDTO.getPrivateName() + " " + registrationDTO.getPassword() + " " + registrationDTO.getEmail());
|
||||
return new ResponseEntity<>(authenticationService.registerUser(registrationDTO), HttpStatus.OK);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,23 +2,22 @@ package SuMoC.backend.security.models;
|
||||
|
||||
public class UserRegistrationDTO {
|
||||
|
||||
private String username;
|
||||
private String privateName;
|
||||
private String publicName;
|
||||
private String email;
|
||||
private String password;
|
||||
|
||||
public UserRegistrationDTO(String username, String email, String password){
|
||||
this.username = username;
|
||||
public UserRegistrationDTO(String privateName, String publicName, String email, String password){
|
||||
this.privateName = privateName;
|
||||
this.publicName = publicName;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
public String getPrivateName() { return privateName; }
|
||||
public void setPrivateName(String privateName) { this.privateName = privateName; }
|
||||
public String getPublicName() { return publicName; }
|
||||
public void setPublicName(String publicName) { this.publicName = publicName; }
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package SuMoC.backend.security.services;
|
||||
|
||||
import SuMoC.backend.mapper.UserMapper;
|
||||
import SuMoC.backend.models.RoleName;
|
||||
import SuMoC.backend.models.enums.RoleName;
|
||||
import SuMoC.backend.models.User;
|
||||
import SuMoC.backend.models.dto.UserDTO;
|
||||
|
||||
@@ -50,7 +50,7 @@ public class AuthenticationService {
|
||||
|
||||
try {
|
||||
// Prüfen, ob der Benutzername bereits existiert
|
||||
if (userRepository.existsByPublicName(registrationDTO.getUsername())) {
|
||||
if (userRepository.existsByPublicName(registrationDTO.getPublicName())) {
|
||||
throw new IllegalArgumentException("Benutzername ist bereits vergeben");
|
||||
}
|
||||
|
||||
@@ -63,14 +63,16 @@ public class AuthenticationService {
|
||||
// Passwort verschlüsseln
|
||||
String encodedPassword = passwordEncoder.encode(registrationDTO.getPassword());
|
||||
|
||||
// Rolle "USER" zuweisen
|
||||
Set<RoleName> roles = new HashSet<>();
|
||||
roles.add(RoleName.USER);
|
||||
|
||||
|
||||
// Neuen Benutzer erstellen und speichern
|
||||
User user = new User();
|
||||
// TODO patch, commented out
|
||||
//User user = new User(registrationDTO.getUsername(), registrationDTO.getEmail(), encodedPassword, roles);
|
||||
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail(), encodedPassword);
|
||||
|
||||
// Sicherheitshalber nochmal explizit setzen
|
||||
if (user.getRoles() == null || user.getRoles().isEmpty()) {
|
||||
user.setRoles(new HashSet<>());
|
||||
user.getRoles().add(RoleName.USER);
|
||||
}
|
||||
|
||||
userRepository.save(user);
|
||||
|
||||
@@ -96,6 +98,7 @@ public class AuthenticationService {
|
||||
);
|
||||
|
||||
User user = userRepository.findByEmail(authPairDTO.getEmail()).get();
|
||||
System.out.println(user.getEmail());
|
||||
UserDTO userDTO = userMapper.toUserDTO(user);
|
||||
// TODO patch, commented out
|
||||
//UserDTO userDTO = new UserDTO(user.getId(), user.getUsername(), user.getRoles());
|
||||
|
||||
@@ -43,7 +43,7 @@ public class TokenService {
|
||||
.subject(auth.getName())
|
||||
.claim("roles",roles)
|
||||
.claim("userId", userDTO.getId())
|
||||
.claim("username", userDTO.getUsername())
|
||||
.claim("privateName", userDTO.getPrivateName())
|
||||
.build();
|
||||
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package SuMoC.backend.service;
|
||||
|
||||
import SuMoC.backend.models.Friendship;
|
||||
import SuMoC.backend.models.User;
|
||||
import SuMoC.backend.models.dto.MinimalUserDTO;
|
||||
import SuMoC.backend.models.enums.FriendShipStatus;
|
||||
import SuMoC.backend.models.enums.RoleName;
|
||||
import SuMoC.backend.models.enums.VisibilityPrivacy;
|
||||
import SuMoC.backend.repositories.UserRepository;
|
||||
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.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@Transactional
|
||||
public class UserService {
|
||||
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Autowired
|
||||
public UserService(UserRepository userRepository) {
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
public MinimalUserDTO getUser(long id) {
|
||||
User sender = getSender();
|
||||
|
||||
User requested = userRepository.findById(id).get();
|
||||
|
||||
// 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");
|
||||
|
||||
//TODO: Think about private profile visibility heuristics
|
||||
// if (requested.getVisibilityPrivacy() == VisibilityPrivacy.PRIVATE && !status.equals(FriendShipStatus.ACCEPTED)) {
|
||||
// throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
// }
|
||||
|
||||
switch (status) {
|
||||
case ACCEPTED -> {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPrivateName());
|
||||
}
|
||||
|
||||
case BLOCKED -> {
|
||||
throw new RuntimeException("Kein Zugriff auf dieses Profil");
|
||||
}
|
||||
|
||||
default -> {
|
||||
return new MinimalUserDTO(requested.getId(), requested.getPublicName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void deleteUser(Long id) {
|
||||
User sender = getSender();
|
||||
|
||||
if (!sender.getId().equals(id) && !sender.getRoles().contains(RoleName.ADMIN)) {
|
||||
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Profil löschen.");
|
||||
}
|
||||
// User is admin or deleting own profile
|
||||
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)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur sein eigenes Passwort ändern.");
|
||||
}
|
||||
// TODO: Add Email Notification for password change
|
||||
sender.setPassword(newPassword);
|
||||
userRepository.save(sender);
|
||||
}
|
||||
|
||||
public void changeEmail(Long id, String newEmail) {
|
||||
|
||||
User sender = getSender();
|
||||
if (!sender.getId().equals(id)) {
|
||||
throw new RuntimeException("Ein Nutzer kann nur seine eigene E-Mail-Adresse ändern.");
|
||||
}
|
||||
// TODO: Add Email Notification for password change
|
||||
sender.setEmail(newEmail);
|
||||
userRepository.save(sender);
|
||||
}
|
||||
|
||||
public void changeVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||
User user = getSender();
|
||||
user.setVisibilityPrivacy(visibilityPrivacy);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user