Compare commits
44
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab9b930bcc | ||
|
|
7eed50f17b | ||
|
|
91d9be1c98 | ||
|
|
bfcb1597ba | ||
|
|
85b427f0d5 | ||
|
|
7344ed7f17 | ||
|
|
31ea7ab80e | ||
|
|
ade57e384e | ||
|
|
7862029773 | ||
|
|
bba0b73adf | ||
|
|
04e17e7995 | ||
|
|
aabb036de9 | ||
|
|
2df20aa374 | ||
|
|
2e60ed3153 | ||
|
|
ad7dd4693c | ||
|
|
2b267400c4 | ||
|
|
b817cf216e | ||
|
|
58ccbdc01a | ||
|
|
f277e8b8b0 | ||
|
|
4063160133 | ||
|
|
427267c4bf | ||
|
|
82b9ae15d9 | ||
|
|
29e4096e95 | ||
|
|
1d2c04d95c | ||
|
|
29956d0b92 | ||
|
|
932fc88b2e | ||
|
|
d7cb3c0e8e | ||
|
|
7c347caea9 | ||
|
|
29fb04d6ec | ||
|
|
82014b1d9c | ||
|
|
57e9beb33f | ||
|
|
30de34b47a | ||
|
|
05a8252d65 | ||
|
|
a57115a6d6 | ||
|
|
ce9dbf4a79 | ||
|
|
007680fccf | ||
|
|
cf7d847993 | ||
|
|
dad0077279 | ||
|
|
0bc692d64a | ||
|
|
16bf41beaa | ||
|
|
98cb2536a2 | ||
|
|
776b8857b6 | ||
|
|
b6ce9a73ce | ||
|
|
906050ad89 |
Vendored
+15
-3
@@ -2,6 +2,13 @@
|
||||
|
||||
// this groovy script is executed by jenkins
|
||||
node('built-in') {
|
||||
def DEPLOYMENT_LOCKED = false // Set to false to re-enable deployments
|
||||
def RESET_DB = false // change to reset DB on redeploy
|
||||
|
||||
if (DEPLOYMENT_LOCKED) {
|
||||
echo "⚠️ Deployment is currently locked for testing. Skipping pipeline."
|
||||
return
|
||||
}
|
||||
|
||||
// checkout code from scm
|
||||
stage('Checkout') {
|
||||
@@ -26,9 +33,14 @@ node('built-in') {
|
||||
sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~'
|
||||
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
|
||||
echo "Resetting database..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
|
||||
if (RESET_DB) {
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down -v"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose rm -f db"'
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
|
||||
} else {
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker compose down"'
|
||||
|
||||
}
|
||||
echo "Load docker images on server ..."
|
||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
|
||||
echo "Restarting docker containers on server ..."
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ services:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
restart: always
|
||||
restart: unless-stopped
|
||||
|
||||
# nominatim:
|
||||
# image: mediagis/nominatim:5.2
|
||||
|
||||
+62
-17
@@ -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":
|
||||
@@ -852,19 +852,19 @@ paths:
|
||||
"304":
|
||||
description: Profile picture not modified since last request
|
||||
content:
|
||||
'*/*':
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ImageRequestDTO"
|
||||
"403":
|
||||
description: Only authorized persons may see the profiles picture
|
||||
content:
|
||||
'*/*':
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ImageRequestDTO"
|
||||
"404":
|
||||
description: The user does not exist
|
||||
content:
|
||||
'*/*':
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/ImageRequestDTO"
|
||||
/trip/getAllUserTrips:
|
||||
@@ -1384,6 +1384,21 @@ paths:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/BadgeDTO"
|
||||
/user/deleteMobilityData:
|
||||
delete:
|
||||
tags:
|
||||
- user-controller
|
||||
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."
|
||||
operationId: deleteMobilityData
|
||||
responses:
|
||||
"204":
|
||||
description: Mobility data successfully deleted
|
||||
"403":
|
||||
description: Not authorized
|
||||
content:
|
||||
application/json: {}
|
||||
/user/delete/{id}:
|
||||
delete:
|
||||
tags:
|
||||
@@ -1418,6 +1433,31 @@ paths:
|
||||
'*/*':
|
||||
schema:
|
||||
type: object
|
||||
/trip/deleteTrip/{tripId}:
|
||||
delete:
|
||||
tags:
|
||||
- trip-controller
|
||||
summary: Delete a trip for the authenticated user.
|
||||
operationId: deleteTrip
|
||||
parameters:
|
||||
- name: tripId
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
/trip/deleteAllTrips:
|
||||
delete:
|
||||
tags:
|
||||
- trip-controller
|
||||
summary: Delete all trips of the authenticated user.
|
||||
operationId: deleteAllTrips
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
/friendship/unfriend/{friendId}:
|
||||
delete:
|
||||
tags:
|
||||
@@ -1810,14 +1850,14 @@ components:
|
||||
description: The temporal difference in minutes compared to the original
|
||||
route (in case alternative was requested) / the car route (when simply
|
||||
directions requested) .
|
||||
physicalActivity:
|
||||
type: boolean
|
||||
durationSeconds:
|
||||
type: integer
|
||||
format: int64
|
||||
walkingRoute:
|
||||
type: boolean
|
||||
cyclingRoute:
|
||||
type: boolean
|
||||
physicalActivity:
|
||||
walkingRoute:
|
||||
type: boolean
|
||||
StepDTO:
|
||||
type: object
|
||||
@@ -1894,11 +1934,16 @@ components:
|
||||
PasswordResetDTO:
|
||||
type: object
|
||||
properties:
|
||||
otp_code:
|
||||
otpCode:
|
||||
type: string
|
||||
email:
|
||||
type: string
|
||||
new_password:
|
||||
newPassword:
|
||||
type: string
|
||||
OtpRequestDTO:
|
||||
type: object
|
||||
properties:
|
||||
email:
|
||||
type: string
|
||||
UserRegistrationDTO:
|
||||
type: object
|
||||
@@ -1949,7 +1994,10 @@ components:
|
||||
km_PUBLIC_TRANSPORT:
|
||||
type: integer
|
||||
format: int64
|
||||
xp:
|
||||
mobility_SCORE:
|
||||
type: integer
|
||||
format: int64
|
||||
co2_SAVED:
|
||||
type: integer
|
||||
format: int64
|
||||
km_CYCLED:
|
||||
@@ -1961,10 +2009,7 @@ components:
|
||||
km_DRIVEN:
|
||||
type: integer
|
||||
format: int64
|
||||
mobility_SCORE:
|
||||
type: integer
|
||||
format: int64
|
||||
co2_SAVED:
|
||||
xp:
|
||||
type: integer
|
||||
format: int64
|
||||
StatsList:
|
||||
|
||||
@@ -149,6 +149,14 @@
|
||||
<artifactId>h3</artifactId>
|
||||
<version>4.4.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.flywaydb</groupId>
|
||||
<artifactId>flyway-database-postgresql</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -10,8 +10,9 @@ public class ImageEntity {
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private int id;
|
||||
|
||||
@Lob
|
||||
//@Column(columnDefinition = "BYTEA")
|
||||
//@Lob
|
||||
@Basic(fetch = FetchType.EAGER)
|
||||
@Column(columnDefinition = "bytea")
|
||||
//@Column(columnDefinition = "BLOB")
|
||||
private byte[] imageData;
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+4
-4
@@ -1,11 +1,11 @@
|
||||
package SuMoC.backend.gamification.badges;
|
||||
package SuMoC.backend.seed;
|
||||
|
||||
import SuMoC.backend.gamification.badges.BadgeRepository;
|
||||
import SuMoC.backend.gamification.badges.BadgeService;
|
||||
import SuMoC.backend.gamification.badges.mapper.BadgeMapper;
|
||||
import SuMoC.backend.gamification.badges.models.Badge;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||
import jakarta.transaction.Transactional;
|
||||
import kotlin.collections.ArrayDeque;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
@@ -16,7 +16,7 @@ import java.util.*;
|
||||
|
||||
@Component
|
||||
@Profile("dev")
|
||||
@Order(3)
|
||||
@Order(2)
|
||||
public class DevBadgeSeeder implements CommandLineRunner {
|
||||
|
||||
private final BadgeService badgeService;
|
||||
@@ -8,13 +8,15 @@ 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
|
||||
@Profile("dev")
|
||||
@Order(4)
|
||||
@Order(3)
|
||||
public class DevChallengeSeeder implements CommandLineRunner {
|
||||
|
||||
private final ChallengeService challengeService;
|
||||
@@ -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(
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
package SuMoC.backend.seed.trip;
|
||||
|
||||
import SuMoC.backend.trip.TripFactory;
|
||||
import SuMoC.backend.trip.TripService;
|
||||
import SuMoC.backend.trip.dtos.NewTripDTO;
|
||||
import SuMoC.backend.user.repository.UserRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Profile("dev")
|
||||
@Order(2)
|
||||
public class DevTripSeeder implements CommandLineRunner {
|
||||
|
||||
private final TripService tripService;
|
||||
|
||||
private final UserRepository userRepository;
|
||||
|
||||
|
||||
@Autowired
|
||||
public DevTripSeeder(TripService tripService, UserRepository userRepository) {
|
||||
this.tripService = tripService;
|
||||
this.userRepository = userRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(String... args) throws Exception {
|
||||
// Iterate over all users and create 5 random trips for each of the last 5 weeks + adds car trips for every day at same time
|
||||
userRepository.findAll().forEach(user -> {
|
||||
for (int week = 0; week < 5; week++) {
|
||||
for (int day = 0; day < 7; day++) {
|
||||
// NewTripDTO carTrip = TripFactory.newCarTripDTO(
|
||||
// Instant.now()
|
||||
// .minus(Duration.ofDays(week * 7 + day)).atZone(ZoneId.systemDefault()).toInstant()
|
||||
// );
|
||||
// This should definitly trigger regularTripDetection
|
||||
NewTripDTO triggerCarTrip = TripFactory.newTriggeringCarMock(
|
||||
java.time.Instant.now().minus(java.time.Duration.ofDays(week * 7 + day))
|
||||
);
|
||||
tripService.addTrip(user, triggerCarTrip);
|
||||
}
|
||||
|
||||
// Create 5 trips per week
|
||||
// for (int i = 0; i < 5; i++) {
|
||||
// // Create trips within each week's time range
|
||||
// long daysAgo = week * 7 + (long) (Math.random() * 7);
|
||||
// NewTripDTO newTrip = TripFactory.randomNewTripDTO(
|
||||
// java.time.Instant.now().minus(java.time.Duration.ofDays((long) (Math.random() * 30))));
|
||||
// tripService.addTrip(user, newTrip);
|
||||
// }
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -39,17 +40,18 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) throws Exception {
|
||||
List<User> pgMembers = seedPgMembers();
|
||||
List<User> defaultTestUsers = seedDefaultTestUsers();
|
||||
|
||||
Long positionIndex = 1L;
|
||||
for (var user : pgMembers) {
|
||||
addDummyStats(user, positionIndex);
|
||||
addDummyStats(user);
|
||||
positionIndex++;
|
||||
}
|
||||
for (var user : defaultTestUsers) {
|
||||
addDummyStats(user, positionIndex);
|
||||
addDummyStats(user);
|
||||
positionIndex++;
|
||||
}
|
||||
//List<User> nTestUsers = seedNtestUsers(10);
|
||||
@@ -261,31 +263,31 @@ public class DevUserSeeder implements CommandLineRunner {
|
||||
return createdUsers;
|
||||
}
|
||||
|
||||
private void addDummyStats(User user, Long positionIndex) {
|
||||
private void addDummyStats(User user) {
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"XP",
|
||||
100L * positionIndex
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"CO2_SAVED",
|
||||
500L * positionIndex
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"KM_CYCLED",
|
||||
20L * positionIndex
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"KM_WALKED",
|
||||
10L * positionIndex
|
||||
0
|
||||
);
|
||||
user.getStats().addToStat(
|
||||
Timeframe.WEEKLY,
|
||||
"KM_PUBLIC_TRANSPORT",
|
||||
15L * positionIndex
|
||||
0
|
||||
);
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,9 +73,7 @@ public class FriendshipController {
|
||||
@PostMapping("/request/by-friendcode/{friendCode}")
|
||||
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
|
||||
User user = currentUserService.get();
|
||||
User requestedFriend = userRepository.findByFriendCode(friendCode).orElseThrow();
|
||||
checkSelfAction(user.getId(), requestedFriend.getId());
|
||||
friendshipService.requestFriendship(user, requestedFriend.getId());
|
||||
friendshipService.requestFriendshipByFriendcode(user, friendCode);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,16 @@ public interface UserMapper {
|
||||
User toUser(UserDTO userDTO);
|
||||
|
||||
static MaximalUserDTO toMaximalUserDTO(User user) {
|
||||
MaximalUserDTO maximalUserDTO = new MaximalUserDTO(
|
||||
// Force-initialize lazy collections while session is still open
|
||||
user.getTrips().size();
|
||||
user.getFriendships().size();
|
||||
|
||||
String base64Image = null;
|
||||
if (user.getProfileImage() != null && user.getProfileImage().getImageData() != null) {
|
||||
base64Image = ImageBase64Util.encode(user.getProfileImage().getImageData());
|
||||
}
|
||||
|
||||
return new MaximalUserDTO(
|
||||
user.getId(),
|
||||
user.getPublicName(),
|
||||
user.getPrivateName(),
|
||||
@@ -24,9 +33,8 @@ public interface UserMapper {
|
||||
user.getTrips(),
|
||||
user.getFriendships(),
|
||||
user.getFriendCode(),
|
||||
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||
base64Image
|
||||
);
|
||||
return maximalUserDTO;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package SuMoC.backend.user.models;
|
||||
|
||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
||||
import jakarta.persistence.*;
|
||||
import lombok.*;
|
||||
|
||||
@@ -26,10 +27,12 @@ public class Friendship {
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
@JsonBackReference("user-friendships")
|
||||
private User user;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "friend_id", nullable = false)
|
||||
@JsonBackReference("friend-friendships")
|
||||
private User friend;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
|
||||
@@ -11,7 +11,9 @@ import SuMoC.backend.user.repository.UserRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -344,6 +346,17 @@ public class FriendshipService {
|
||||
return friends;
|
||||
}
|
||||
|
||||
public void requestFriendshipByFriendcode(User sender, String friendCode) {
|
||||
User requestedFriend = userRepository.findByFriendCode(friendCode)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
|
||||
|
||||
if (sender.getId().equals(requestedFriend.getId())) {
|
||||
throw new IllegalArgumentException("Action cannot be performed on oneself.");
|
||||
}
|
||||
|
||||
requestFriendship(sender, requestedFriend.getId());
|
||||
}
|
||||
|
||||
public record NameWithFriendship(
|
||||
Long id,
|
||||
String name,
|
||||
|
||||
@@ -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,15 +210,15 @@ 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);
|
||||
userRepository.save(userToChange);
|
||||
}
|
||||
|
||||
|
||||
@Transactional
|
||||
public MaximalUserDTO getSelf() {
|
||||
User sender = currentUser.get();
|
||||
return UserMapper.toMaximalUserDTO(sender);
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/sumoc
|
||||
spring.datasource.username=postgres
|
||||
spring.datasource.password=admin
|
||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.flyway.enabled=true
|
||||
spring.jpa.hibernate.ddl-auto=validate
|
||||
spring.flyway.baseline-on-migrate=true
|
||||
spring.flyway.baseline-version=0
|
||||
spring.jpa.show-sql=true
|
||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||
logging.level.org.springframework.security=Trace
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE image_entity
|
||||
ALTER COLUMN image_data TYPE bytea
|
||||
USING lo_get(image_data);
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.4 MiB |
Reference in New Issue
Block a user