Author SHA1 Message Date
Elias Harb 932fc88b2e Bug fix: getPicture Endpoint
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
- got error that object was too large for transaction ... again
2026-02-25 01:55:10 +01:00
Elias Harb 7c347caea9 add challenge Dummy picture
LocationBasedServices/sumoc-backend/pipeline/pr-main Build queued...
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-25 00:17:35 +01:00
kakoschke 29fb04d6ec Merge pull request 'make reset password Kotlin/Android app functional' (#22) from passwordResetRefactoring into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #22

passt!
2026-02-23 18:47:33 +01:00
Elias Harb 82014b1d9c make reset password Kotlin/Android app functional
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
- small refactor for resetPassword
2026-02-23 18:30:15 +01:00
neuhauss 57e9beb33f Merge pull request 'WIP FirebaseMessageBuilder.java adaptiert, sodass auch iOS Apps Push Benachrichtigungen erhalten und intercepten können.' (#21) from add-ios-notification into main
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
Reviewed-on: #21
2026-02-23 11:47:24 +01:00
neuhauss 30de34b47a Merge branch 'main' into add-ios-notification
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-23 11:40:49 +01:00
neuhauss 007680fccf include supporting trip ids in regulartrip dto that is used for carrousel display
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-22 18:43:02 +01:00
neuhauss cf7d847993 bugfix, stupid back and forth conversion of instant and localtime caused wrong resulting time 2026-02-22 18:21:49 +01:00
neuhauss dad0077279 bugfix, arrival and departure were mixed up 2026-02-22 18:04:34 +01:00
neuhauss 0bc692d64a fix logic bug, no exception should be thrown if weather is bad 2026-02-22 17:51:06 +01:00
neuhauss 16bf41beaa add endpoint to delete all mobility data of a user 2026-02-22 17:39:49 +01:00
neuhauss 98cb2536a2 add endpoint to delete all trips of user 2026-02-22 17:26:42 +01:00
neuhauss 776b8857b6 add endpoint to delete trip with given id 2026-02-22 17:23:38 +01:00
Daniel b6ce9a73ce FirebaseMessageBuilder.java adaptiert, sodass auch iOS Apps Push Benachrichtigungen erhalten und intercepten können.
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
LocationBasedServices/sumoc-backend/pipeline/pr-main This commit looks good
2026-02-20 16:26:22 +01:00
Daniel 906050ad89 openapi.yaml
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
2026-02-20 12:38:13 +01:00
22 changed files with 194 additions and 77 deletions
+18 -13
View File
@@ -650,7 +650,7 @@ paths:
summary: 'Veränderung des Passworts eines Profils '
description: Durch Eingabe eines Validen OTP Codes zu einer zugehörigen Email
kann das Passwort des Profils geändert werden.
operationId: handlePasswordResetRequest
operationId: resetPassword
requestBody:
content:
application/json:
@@ -664,7 +664,7 @@ paths:
'*/*':
schema:
type: string
/auth/user/request-password-reset:
/auth/user/request-otp-for-password-reset:
post:
tags:
- user-authentication-controller
@@ -672,12 +672,12 @@ paths:
description: "Erstellt bei Anfrage einen neuen 6-stelligen OTP Code, mit welchem\
\ das Passwort des Accounts mit der zugehörigen Email einmalig verändert werden\
\ kann. Dieser wird per Mail an den Nutzer gesendet."
operationId: handleForgotPasswordRequest
operationId: requestOtpForPasswordReset
requestBody:
content:
application/json:
schema:
type: string
$ref: "#/components/schemas/OtpRequestDTO"
required: true
responses:
"200":
@@ -1813,11 +1813,11 @@ components:
durationSeconds:
type: integer
format: int64
walkingRoute:
physicalActivity:
type: boolean
cyclingRoute:
type: boolean
physicalActivity:
walkingRoute:
type: boolean
StepDTO:
type: object
@@ -1900,6 +1900,11 @@ components:
type: string
new_password:
type: string
OtpRequestDTO:
type: object
properties:
email:
type: string
UserRegistrationDTO:
type: object
properties:
@@ -1946,25 +1951,25 @@ components:
Stats:
type: object
properties:
km_PUBLIC_TRANSPORT:
type: integer
format: int64
xp:
type: integer
format: int64
km_CYCLED:
type: integer
format: int64
mobility_SCORE:
type: integer
format: int64
co2_SAVED:
type: integer
format: int64
km_WALKED:
type: integer
format: int64
km_DRIVEN:
type: integer
format: int64
mobility_SCORE:
type: integer
format: int64
co2_SAVED:
km_PUBLIC_TRANSPORT:
type: integer
format: int64
StatsList:
@@ -17,4 +17,6 @@ public interface CarrouselCandidateRepository extends JpaRepository<CarrouselCan
ORDER BY c.suggestedAt DESC
""")
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
void deleteAllByUserId(Long userId);
}
@@ -1,6 +1,9 @@
package SuMoC.backend.firebase;
import SuMoC.backend.notification.models.Notification;
import com.google.firebase.messaging.ApnsConfig;
import com.google.firebase.messaging.Aps;
import com.google.firebase.messaging.ApsAlert;
import com.google.firebase.messaging.Message;
import org.springframework.stereotype.Service;
@@ -11,6 +14,21 @@ public class FirebaseMessageBuilder {
var builder = Message.builder().setToken(token);
builder.putData("type", notification.getType().toString());
builder.putData("data", notification.getData());
//Setup, so iOS can receive and intercept Push Notifications
builder.setNotification(com.google.firebase.messaging.Notification.builder()
.setTitle("Sumoc Update")
.setBody("Deine Nachricht ist da!")
.build())
.setApnsConfig(ApnsConfig.builder()
.setAps(Aps.builder()
.setMutableContent(true)
.setSound("default") // WICHTIG: Ohne Sound oft keine Anzeige
.setBadge(1)
.build())
.build());
return builder.build();
}
@@ -34,11 +34,11 @@ public interface ChallengeMapper {
challenge.setCriteria(dto.getCriteria());
challenge.setReward(dto.getReward());
if (dto.getBase64image() != null && !dto.getBase64image().isEmpty()) {
challenge.setImage(new ChallengeImageEntity(
challenge,
ImageBase64Util.decode(dto.getBase64image())
));
if (dto.getBase64image() != null && !dto.getBase64image().isBlank()) {
byte[] bytes = ImageBase64Util.decode(dto.getBase64image());
ChallengeImageEntity img = new ChallengeImageEntity();
img.setImageData(bytes);
challenge.setImage(img);
}
return challenge;
@@ -85,6 +85,9 @@ public class Challenge {
public void setImage(ChallengeImageEntity image) {
this.image = image;
if (image != null) {
image.setChallenge(this);
}
}
public Map<String, Integer> getCriteria() {
@@ -1,6 +1,7 @@
package SuMoC.backend.notification.repositories;
import SuMoC.backend.notification.models.Notification;
import SuMoC.backend.user.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
@@ -36,4 +37,6 @@ public interface NotificationRepository extends JpaRepository<Notification, Long
WHERE n.createdAt < :cutOff
""")
void deleteNotificationsOlder(Instant cutOff);
void deleteAllByUser(User user);
}
@@ -5,10 +5,7 @@ import SuMoC.backend.trip.Modality;
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
import lombok.*;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.*;
import java.util.List;
/**
@@ -68,13 +65,13 @@ public class DetectedRegularTripDTO {
.build();
}
public LocalTime getAverageArrivalTime() {
int totalSeconds = 0;
public Instant getAverageArrivalTime() {
long totalSeconds = 0;
for (RegularTripDetectionDTO trip : supportingTrips) {
totalSeconds += trip.getEndTime().atOffset(ZoneOffset.UTC).toLocalTime().toSecondOfDay();
totalSeconds += trip.getEndTime().getEpochSecond();
}
int averageSeconds = totalSeconds / supportingTrips.size();
return LocalTime.ofSecondOfDay(averageSeconds);
long averageSeconds = totalSeconds / supportingTrips.size();
return Instant.ofEpochSecond(averageSeconds);
}
public int getAverageDurationMinutes() {
@@ -28,6 +28,8 @@ public class MinimalDetectedRegularTripDTO {
private LocalTime arrivalWindowStart;
@Schema(description = "Latest arrival time among the supporting trips, in the user's local time")
private LocalTime arrivalWindowEnd;
@Schema(description = "Backend trip ids of the trips that support this detected regular trip.")
private List<Long> supportingTripIds;
private String startH3Center;
private String endH3Center;
@@ -41,12 +43,15 @@ public class MinimalDetectedRegularTripDTO {
minimalDTO.arrivalWindowEnd = getLatestArrival(regularTrip.getSupportingTrips());
minimalDTO.startH3Center = regularTrip.getStartH3Center();
minimalDTO.endH3Center = regularTrip.getEndH3Center();
minimalDTO.supportingTripIds = regularTrip.getSupportingTrips().stream()
.map(RegularTripDetectionDTO::getTripId)
.toList();
return minimalDTO;
}
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
var earliest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getStartTime)
.map(RegularTripDetectionDTO::getEndTime)
.min(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
@@ -54,7 +59,7 @@ public class MinimalDetectedRegularTripDTO {
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
var latest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getStartTime)
.map(RegularTripDetectionDTO::getEndTime)
.max(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
@@ -62,7 +67,7 @@ public class MinimalDetectedRegularTripDTO {
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
var earliest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getEndTime)
.map(RegularTripDetectionDTO::getStartTime)
.min(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
@@ -70,7 +75,7 @@ public class MinimalDetectedRegularTripDTO {
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
var latest = supportingTrips.stream()
.map(RegularTripDetectionDTO::getEndTime)
.map(RegularTripDetectionDTO::getStartTime)
.max(Comparator.naturalOrder())
.orElseThrow();
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
@@ -82,14 +82,16 @@ public class AlternativeFilterService {
ArrayList<RouteDTO> filteredAlternatives = new ArrayList<>();
for (RouteDTO route : alternatives) {
if (route.isPhysicalActivity()) {
if (!route.isCyclingRoute() && !route.isWalkingRoute()) {
throw new RuntimeException("Unexpected case of a physical activity route that is not pure cycling or walking");
}
var weatherConditions = forecast.getWeatherConditionsBetween(route.getStartDateTime(), route.getEndDateTime());
if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
filteredAlternatives.add(route);
} else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
filteredAlternatives.add(route);
} else {
throw new RuntimeException("Unexpected case of a physical activity route that is not pure cycling or walking");
}
// else: weather conditions not acceptable, route is silently dropped
} else {
filteredAlternatives.add(route);
}
@@ -102,9 +102,11 @@ public class UserAuthenticationController {
authenticationService.resetPassword(passwordResetDTO);
return ResponseEntity.ok("Passwort erfolgreich geändert");
} catch (InvalidTokenException | UsernameNotFoundException e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(e.getMessage());
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Fehler beim Zurücksetzen des Passworts");
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
@@ -1,5 +1,6 @@
package SuMoC.backend.security.dtos;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
@@ -8,7 +9,9 @@ import lombok.Setter;
@Setter
@AllArgsConstructor
public class PasswordResetDTO {
String otp_code;
@JsonAlias({"otp_code", "otpCode"})
String otpCode;
String email;
String new_password;
@JsonAlias({"new_password", "newPassword"})
String newPassword;
}
@@ -17,12 +17,12 @@ public class PasswordResetToken{
private Long id;
private String email;
private String otp_code;
private String otpCode;
private LocalDateTime expiryDate;
public PasswordResetToken(String email, String code) {
this.email = email;
this.otp_code = code;
this.otpCode = code;
this.expiryDate = LocalDateTime.now().plusMinutes(EXPIRY_TIME_MINUTES);
}
@@ -13,8 +13,6 @@ 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.http.ResponseEntity;
import org.springframework.mail.MailException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@@ -155,7 +153,6 @@ public class AuthenticationService {
});
String otp = generate_six_digit_OTP();
passwordResetTokenRepository.save(new PasswordResetToken(email, passwordEncoder.encode(otp))); //encoded otp
emailService.sendPasswordResetEmail(email, otp);
}
@@ -171,18 +168,17 @@ public class AuthenticationService {
}
//use .matches() so compare raw otp to (salted!) encoded otp
if(!passwordEncoder.matches(passwordResetDTO.getOtp_code(),token.getOtp_code())){
if(!passwordEncoder.matches(passwordResetDTO.getOtpCode(),token.getOtpCode())){
throw new InvalidTokenException("Code ist ungültig");
}
if(!isPasswordFormatCorrect(passwordResetDTO.getNew_password())) {
if(!isPasswordFormatCorrect(passwordResetDTO.getNewPassword())) {
throw new InvalidTokenException("Passwortformat ist nicht korrekt");
}
User user = userRepository.findByEmail(passwordResetDTO.getEmail())
.orElseThrow(() -> new UsernameNotFoundException("User existiert nicht"));
user.setPassword(passwordEncoder.encode(passwordResetDTO.getNew_password()));
user.setPassword(passwordEncoder.encode(passwordResetDTO.getNewPassword()));
userRepository.save(user);
passwordResetTokenRepository.delete(token);
}
@@ -8,8 +8,10 @@ import jakarta.transaction.Transactional;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import java.io.InputStream;
import java.util.*;
@Component
@@ -31,6 +33,7 @@ public class DevChallengeSeeder implements CommandLineRunner {
@Override
@Transactional
public void run(String... args) {
final String dummyImageBase64 = loadBase64FromClasspath("images/ChallengeDummy.png");
List<Seed> seeds = generateSeeds();
for (Seed seed : seeds) {
@@ -38,20 +41,20 @@ public class DevChallengeSeeder implements CommandLineRunner {
.map(ChallengeMapper::toDTO)
.ifPresentOrElse(
existingChallenge -> {
// Update existing challenge
existingChallenge.setName(seed.name());
existingChallenge.setDescription(seed.description());
existingChallenge.setCriteria(seed.criteria());
existingChallenge.setReward(seed.reward());
existingChallenge.setBase64image(dummyImageBase64);
challengeService.modifyChallenge(existingChallenge);
},
() -> {
// Create new challenge
ChallengeDTO newChallenge = new ChallengeDTO();
newChallenge.setName(seed.name());
newChallenge.setDescription(seed.description());
newChallenge.setCriteria(seed.criteria());
newChallenge.setReward(seed.reward());
newChallenge.setBase64image(dummyImageBase64);
challengeService.createChallenge(newChallenge);
}
);
@@ -60,6 +63,15 @@ public class DevChallengeSeeder implements CommandLineRunner {
challengeService.weeklyChallengeScheduler();
}
private String loadBase64FromClasspath(String classpathLocation) {
try (InputStream in = new ClassPathResource(classpathLocation).getInputStream()) {
byte[] bytes = in.readAllBytes();
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
throw new IllegalStateException("Could not load image from classpath: " + classpathLocation, e);
}
}
private record Seed(String name, String description, Map<String, Integer> criteria, Integer reward) {}
private static Seed seed(
@@ -22,7 +22,10 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.time.*;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -131,10 +134,7 @@ public class RegularTripSuggestionService {
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
// we plan the trip to arrive at the average arrival time of the regular trip
Instant arrivalTime = LocalDateTime.now()
.with(trip.getAverageArrivalTime())
.atZone(ZoneId.systemDefault())
.toInstant();
Instant arrivalTime = trip.getAverageArrivalTime();
Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L);
return RoutingAlternativeRequestDTO.builder()
@@ -2,6 +2,7 @@ package SuMoC.backend.trend;
import SuMoC.backend.trend.models.WeeklyMobilityStats;
import SuMoC.backend.trend.models.WeeklyMobilityStatsId;
import SuMoC.backend.user.models.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
@@ -13,4 +14,6 @@ public interface WeeklyMobilityStatsRepository extends JpaRepository<WeeklyMobil
@Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber")
List<WeeklyMobilityStats> findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
void deleteAllByUser(User user);
}
@@ -12,7 +12,6 @@ import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -67,4 +66,22 @@ public class TripController {
return ResponseEntity.ok().build();
}
@Operation(summary = "Delete a trip for the authenticated user.")
@DeleteMapping("/deleteTrip/{tripId}")
public ResponseEntity<Void> deleteTrip(@PathVariable Long tripId) {
User user = currentUser.get();
tripService.deleteTrip(user, tripId);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Delete all trips of the authenticated user.")
@DeleteMapping("/deleteAllTrips")
public ResponseEntity<Void> deleteAllTrips() {
User user = currentUser.get();
tripService.deleteAllTripsOfUser(user);
return ResponseEntity.noContent().build();
}
}
@@ -17,6 +17,8 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
Optional<List<Trip>> findAllByUser(User user);
void deleteAllByUser(User user);
@Query("SELECT trip FROM Trip trip " +
"JOIN FETCH trip.user " +
"JOIN FETCH trip.tripSegments " +
@@ -7,7 +7,9 @@ import SuMoC.backend.trip.models.Trip;
import SuMoC.backend.user.models.User;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
@@ -26,18 +28,20 @@ public class TripService {
}
public void invalidateTrip(User user, Long tripId) {
Trip trip = tripRepository.findById(tripId).orElseThrow();
Trip trip = tripRepository.findById(tripId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
if (!trip.getUser().equals(user)) {
throw new RuntimeException("Trip does not belong to user");
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
}
trip.setInvalidated(true);
tripRepository.save(trip);
}
public void validateTrip(User user, Long tripId) {
Trip trip = tripRepository.findById(tripId).orElseThrow();
Trip trip = tripRepository.findById(tripId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
if (!trip.getUser().equals(user)) {
throw new RuntimeException("Trip does not belong to user");
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
}
trip.setInvalidated(false);
tripRepository.save(trip);
@@ -55,4 +59,17 @@ public class TripService {
List<Trip> trips = tripRepository.findAllByUser(user).orElseThrow();
return tripMapper.toTripDTOs(trips);
}
public void deleteTrip(User user, Long tripId) {
Trip trip = tripRepository.findById(tripId)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
if (!trip.getUser().equals(user)) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
}
tripRepository.delete(trip);
}
public void deleteAllTripsOfUser(User user) {
tripRepository.deleteAllByUser(user);
}
}
@@ -2,7 +2,10 @@ package SuMoC.backend.user.controller;
import SuMoC.backend.images.ImageRequestDTO;
import SuMoC.backend.security.dtos.LoginResponseDTO;
import SuMoC.backend.user.dtos.*;
import SuMoC.backend.user.dtos.AddStatRequestDTO;
import SuMoC.backend.user.dtos.MaximalUserDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
import SuMoC.backend.user.dtos.StatScope;
import SuMoC.backend.user.enums.VisibilityPrivacy;
import SuMoC.backend.user.service.UserService;
import SuMoC.backend.user.stats.StatsList;
@@ -23,6 +26,7 @@ import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.concurrent.TimeUnit;
@Validated
@@ -101,7 +105,7 @@ public class UserController {
})
@PutMapping("/setPrivateName/{id}")
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
@RequestParam @NotBlank String newPrivateName) {
@RequestParam @NotBlank String newPrivateName) {
this.userService.setPrivateName(id, newPrivateName);
return ResponseEntity.ok().build();
}
@@ -119,7 +123,7 @@ public class UserController {
})
@PutMapping("/setPassword/{id}")
public ResponseEntity<LoginResponseDTO> setPassword(@PathVariable @NotNull Long id,
@RequestParam @NotBlank String newPassword) {
@RequestParam @NotBlank String newPassword) {
return new ResponseEntity<>(this.userService.setPassword(id, newPassword), HttpStatus.OK);
}
@@ -138,7 +142,7 @@ public class UserController {
})
@PutMapping("/setEmail/{id}")
public ResponseEntity<LoginResponseDTO> setEmail(@PathVariable @NotNull Long id,
@RequestParam @NotBlank String newEmail) {
@RequestParam @NotBlank String newEmail) {
return new ResponseEntity<>(this.userService.setEmail(id, newEmail), HttpStatus.OK);
}
@@ -229,16 +233,15 @@ public class UserController {
@ApiResponse(responseCode = "403", description = "Only authorized persons may see the profiles picture"),
@ApiResponse(responseCode = "404", description = "The user does not exist")
})
@GetMapping("/getProfilePicture/{id}")
@GetMapping(value = "/getProfilePicture/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ImageRequestDTO> getProfilePicture(@PathVariable @NotNull Long id) {
ImageRequestDTO imageData = userService.getProfilePicture(id);
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_JPEG)
.contentType(MediaType.APPLICATION_JSON)
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
.body(imageData);
}
@Operation(summary = "Get the users own xp", description = "A user can get their own xp.")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "XP successfully retrieved",
@@ -253,4 +256,17 @@ public class UserController {
Long xp = userService.getTotalXP();
return ResponseEntity.ok().body(xp);
}
@Operation(summary = "Delete all mobility data of the authenticated user",
description = "Deletes all trips (including trip segments), notifications, weekly mobility stats and carrousel candidates belonging to the current user.")
@ApiResponses(value = {
@ApiResponse(responseCode = "204", description = "Mobility data successfully deleted"),
@ApiResponse(responseCode = "403", description = "Not authorized",
content = @Content(mediaType = "application/json"))
})
@DeleteMapping("/deleteMobilityData")
public ResponseEntity<Void> deleteMobilityData() {
this.userService.deleteMobilityData();
return ResponseEntity.noContent().build();
}
}
@@ -1,16 +1,18 @@
package SuMoC.backend.user.service;
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
import SuMoC.backend.gamification.Timeframe;
import SuMoC.backend.images.ImageBase64Util;
import SuMoC.backend.images.ImageRequestDTO;
import SuMoC.backend.notification.repositories.NotificationRepository;
import SuMoC.backend.security.dtos.LoginResponseDTO;
import SuMoC.backend.security.services.TokenService;
import SuMoC.backend.trip.TripMapper;
import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
import SuMoC.backend.trip.TripService;
import SuMoC.backend.user.dtos.MaximalUserDTO;
import SuMoC.backend.user.dtos.MinimalUserDTO;
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.ProfileImageEntity;
import SuMoC.backend.user.models.User;
@@ -22,7 +24,6 @@ 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.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
@@ -33,15 +34,18 @@ public class UserService {
private final CurrentUserService currentUser;
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final UserMapper userMapper;
private final TokenService tokenService;;
private final TokenService tokenService;
;
private final PrivacyService privacyService;
private final FriendshipService friendshipService;
private final TripService tripService;
private final NotificationRepository notificationRepository;
private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
private final CarrouselCandidateRepository carrouselCandidateRepository;
@Autowired
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService) {
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService, TripService tripService, NotificationRepository notificationRepository, WeeklyMobilityStatsRepository weeklyMobilityStatsRepository, CarrouselCandidateRepository carrouselCandidateRepository) {
this.currentUser = currentUser;
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
@@ -49,6 +53,10 @@ public class UserService {
this.tokenService = tokenService;
this.privacyService = privacyService;
this.friendshipService = friendshipService;
this.tripService = tripService;
this.notificationRepository = notificationRepository;
this.weeklyMobilityStatsRepository = weeklyMobilityStatsRepository;
this.carrouselCandidateRepository = carrouselCandidateRepository;
}
@@ -60,7 +68,7 @@ public class UserService {
));
// 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()))) {
if (friendshipService.getBlockedUsers(id).stream().anyMatch(blocked -> blocked.getId().equals(requested.getId()))) {
throw new ResponseStatusException(
HttpStatus.FORBIDDEN,
"Der Nutzer hat dich blockiert."
@@ -97,7 +105,13 @@ public class UserService {
userRepository.deleteById(id);
}
public void deleteMobilityData() {
User user = currentUser.get();
tripService.deleteAllTripsOfUser(user);
notificationRepository.deleteAllByUser(user);
weeklyMobilityStatsRepository.deleteAllByUser(user);
carrouselCandidateRepository.deleteAllByUserId(user.getId());
}
public LoginResponseDTO setPassword(Long id, String newPassword) {
@@ -178,7 +192,7 @@ public class UserService {
));
System.out.println("################# Returning LoginResponse ################");
return new LoginResponseDTO(userMapper.toUserDTO(updatedUser),
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedUser), newEmail));
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedUser), newEmail));
}
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
@@ -196,8 +210,8 @@ public class UserService {
}
User userToChange = userRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND,
"Der Nutzer Existitert nicht."));
HttpStatus.NOT_FOUND,
"Der Nutzer Existitert nicht."));
// TODO: Add String Validator
userToChange.setPrivateName(newPrivateName);
@@ -258,7 +272,7 @@ public class UserService {
public Long getTotalXP() {
User sender = currentUser.get();
return sender.getStats().getStatValue(Timeframe.TOTAL,"XP");
return sender.getStats().getStatValue(Timeframe.TOTAL, "XP");
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB