Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
856f530f99 | ||
|
|
80abd0f34f |
Vendored
+4
-16
@@ -2,13 +2,6 @@
|
|||||||
|
|
||||||
// this groovy script is executed by jenkins
|
// this groovy script is executed by jenkins
|
||||||
node('built-in') {
|
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
|
// checkout code from scm
|
||||||
stage('Checkout') {
|
stage('Checkout') {
|
||||||
@@ -32,15 +25,10 @@ node('built-in') {
|
|||||||
sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~'
|
sh 'scp -i $KEYFILE docker-compose.yml pg-sumoc@apps-dev.nes:~'
|
||||||
sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~'
|
sh 'scp -i $KEYFILE docker-load.sh pg-sumoc@apps-dev.nes:~'
|
||||||
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
|
sh 'scp -i $KEYFILE -r docker_images pg-sumoc@apps-dev.nes:~'
|
||||||
echo "Resetting database..."
|
// echo "Resetting database..."
|
||||||
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 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 compose rm -f db"'
|
// sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "docker volume rm -f sumoc-backend_postgres_data"'
|
||||||
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 ..."
|
echo "Load docker images on server ..."
|
||||||
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
|
sh 'ssh -i $KEYFILE pg-sumoc@apps-dev.nes "chmod +x ~/docker-load.sh && ~/docker-load.sh"'
|
||||||
echo "Restarting docker containers on server ..."
|
echo "Restarting docker containers on server ..."
|
||||||
|
|||||||
+1
-1
@@ -44,7 +44,7 @@ services:
|
|||||||
- postgres_data:/var/lib/postgresql/data
|
- postgres_data:/var/lib/postgresql/data
|
||||||
ports:
|
ports:
|
||||||
- "5432:5432"
|
- "5432:5432"
|
||||||
restart: unless-stopped
|
restart: always
|
||||||
|
|
||||||
# nominatim:
|
# nominatim:
|
||||||
# image: mediagis/nominatim:5.2
|
# image: mediagis/nominatim:5.2
|
||||||
|
|||||||
+51
-166
@@ -249,16 +249,6 @@ paths:
|
|||||||
responses:
|
responses:
|
||||||
"200":
|
"200":
|
||||||
description: OK
|
description: OK
|
||||||
/notifications/unregister-device-token:
|
|
||||||
put:
|
|
||||||
tags:
|
|
||||||
- notification-controller
|
|
||||||
description: Unregisters the device token for push notifications for the authenticated
|
|
||||||
user.
|
|
||||||
operationId: unregisterDeviceToken
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
/notifications/register-device-token:
|
/notifications/register-device-token:
|
||||||
put:
|
put:
|
||||||
tags:
|
tags:
|
||||||
@@ -643,49 +633,6 @@ paths:
|
|||||||
responses:
|
responses:
|
||||||
"200":
|
"200":
|
||||||
description: Check successful
|
description: Check successful
|
||||||
/auth/user/reset-password:
|
|
||||||
post:
|
|
||||||
tags:
|
|
||||||
- user-authentication-controller
|
|
||||||
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: resetPassword
|
|
||||||
requestBody:
|
|
||||||
content:
|
|
||||||
application/json:
|
|
||||||
schema:
|
|
||||||
$ref: "#/components/schemas/PasswordResetDTO"
|
|
||||||
required: true
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
content:
|
|
||||||
'*/*':
|
|
||||||
schema:
|
|
||||||
type: string
|
|
||||||
/auth/user/request-otp-for-password-reset:
|
|
||||||
post:
|
|
||||||
tags:
|
|
||||||
- user-authentication-controller
|
|
||||||
summary: OTP Code zur änderung des Passworts
|
|
||||||
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: requestOtpForPasswordReset
|
|
||||||
requestBody:
|
|
||||||
content:
|
|
||||||
application/json:
|
|
||||||
schema:
|
|
||||||
$ref: "#/components/schemas/OtpRequestDTO"
|
|
||||||
required: true
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
content:
|
|
||||||
'*/*':
|
|
||||||
schema:
|
|
||||||
type: string
|
|
||||||
/auth/user/registration:
|
/auth/user/registration:
|
||||||
post:
|
post:
|
||||||
tags:
|
tags:
|
||||||
@@ -745,9 +692,7 @@ paths:
|
|||||||
"200":
|
"200":
|
||||||
description: Stats were found
|
description: Stats were found
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json: {}
|
||||||
schema:
|
|
||||||
$ref: "#/components/schemas/StatsList"
|
|
||||||
"403":
|
"403":
|
||||||
description: Not authorized
|
description: Not authorized
|
||||||
content:
|
content:
|
||||||
@@ -816,10 +761,7 @@ paths:
|
|||||||
"200":
|
"200":
|
||||||
description: XP successfully retrieved
|
description: XP successfully retrieved
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json: {}
|
||||||
schema:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
"403":
|
"403":
|
||||||
description: Not authorized
|
description: Not authorized
|
||||||
content:
|
content:
|
||||||
@@ -846,25 +788,23 @@ paths:
|
|||||||
"200":
|
"200":
|
||||||
description: Profile picture successfully retrieved
|
description: Profile picture successfully retrieved
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json: {}
|
||||||
schema:
|
|
||||||
$ref: "#/components/schemas/ImageRequestDTO"
|
|
||||||
"304":
|
"304":
|
||||||
description: Profile picture not modified since last request
|
description: Profile picture not modified since last request
|
||||||
content:
|
content:
|
||||||
application/json:
|
'*/*':
|
||||||
schema:
|
schema:
|
||||||
$ref: "#/components/schemas/ImageRequestDTO"
|
$ref: "#/components/schemas/ImageRequestDTO"
|
||||||
"403":
|
"403":
|
||||||
description: Only authorized persons may see the profiles picture
|
description: Only authorized persons may see the profiles picture
|
||||||
content:
|
content:
|
||||||
application/json:
|
'*/*':
|
||||||
schema:
|
schema:
|
||||||
$ref: "#/components/schemas/ImageRequestDTO"
|
$ref: "#/components/schemas/ImageRequestDTO"
|
||||||
"404":
|
"404":
|
||||||
description: The user does not exist
|
description: The user does not exist
|
||||||
content:
|
content:
|
||||||
application/json:
|
'*/*':
|
||||||
schema:
|
schema:
|
||||||
$ref: "#/components/schemas/ImageRequestDTO"
|
$ref: "#/components/schemas/ImageRequestDTO"
|
||||||
/trip/getAllUserTrips:
|
/trip/getAllUserTrips:
|
||||||
@@ -1384,21 +1324,6 @@ paths:
|
|||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
$ref: "#/components/schemas/BadgeDTO"
|
$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}:
|
/user/delete/{id}:
|
||||||
delete:
|
delete:
|
||||||
tags:
|
tags:
|
||||||
@@ -1433,31 +1358,6 @@ paths:
|
|||||||
'*/*':
|
'*/*':
|
||||||
schema:
|
schema:
|
||||||
type: object
|
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}:
|
/friendship/unfriend/{friendId}:
|
||||||
delete:
|
delete:
|
||||||
tags:
|
tags:
|
||||||
@@ -1850,14 +1750,14 @@ components:
|
|||||||
description: The temporal difference in minutes compared to the original
|
description: The temporal difference in minutes compared to the original
|
||||||
route (in case alternative was requested) / the car route (when simply
|
route (in case alternative was requested) / the car route (when simply
|
||||||
directions requested) .
|
directions requested) .
|
||||||
physicalActivity:
|
cyclingRoute:
|
||||||
|
type: boolean
|
||||||
|
walkingRoute:
|
||||||
type: boolean
|
type: boolean
|
||||||
durationSeconds:
|
durationSeconds:
|
||||||
type: integer
|
type: integer
|
||||||
format: int64
|
format: int64
|
||||||
cyclingRoute:
|
physicalActivity:
|
||||||
type: boolean
|
|
||||||
walkingRoute:
|
|
||||||
type: boolean
|
type: boolean
|
||||||
StepDTO:
|
StepDTO:
|
||||||
type: object
|
type: object
|
||||||
@@ -1931,20 +1831,6 @@ components:
|
|||||||
- destinationLon
|
- destinationLon
|
||||||
- originLat
|
- originLat
|
||||||
- originLon
|
- originLon
|
||||||
PasswordResetDTO:
|
|
||||||
type: object
|
|
||||||
properties:
|
|
||||||
otpCode:
|
|
||||||
type: string
|
|
||||||
email:
|
|
||||||
type: string
|
|
||||||
newPassword:
|
|
||||||
type: string
|
|
||||||
OtpRequestDTO:
|
|
||||||
type: object
|
|
||||||
properties:
|
|
||||||
email:
|
|
||||||
type: string
|
|
||||||
UserRegistrationDTO:
|
UserRegistrationDTO:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
@@ -1976,7 +1862,6 @@ components:
|
|||||||
- EMAIL_INVALID
|
- EMAIL_INVALID
|
||||||
- PUBLIC_NAME_EXISTS
|
- PUBLIC_NAME_EXISTS
|
||||||
- PUBLIC_NAME_FORBIDDEN
|
- PUBLIC_NAME_FORBIDDEN
|
||||||
- PASSWORD_INVALID
|
|
||||||
- UNKNOWN_ERROR
|
- UNKNOWN_ERROR
|
||||||
UserAuthenticationPairDTO:
|
UserAuthenticationPairDTO:
|
||||||
type: object
|
type: object
|
||||||
@@ -1988,47 +1873,6 @@ components:
|
|||||||
required:
|
required:
|
||||||
- email
|
- email
|
||||||
- password
|
- password
|
||||||
Stats:
|
|
||||||
type: object
|
|
||||||
properties:
|
|
||||||
km_PUBLIC_TRANSPORT:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
mobility_SCORE:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
co2_SAVED:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
km_CYCLED:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
km_WALKED:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
km_DRIVEN:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
xp:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
StatsList:
|
|
||||||
type: object
|
|
||||||
properties:
|
|
||||||
id:
|
|
||||||
type: integer
|
|
||||||
format: int64
|
|
||||||
description: Unique identifier of the StatsList.
|
|
||||||
example: 1
|
|
||||||
totalStats:
|
|
||||||
$ref: "#/components/schemas/Stats"
|
|
||||||
description: Total stats of the user.
|
|
||||||
monthlyStats:
|
|
||||||
$ref: "#/components/schemas/Stats"
|
|
||||||
description: Monthly stats of the user.
|
|
||||||
weeklyStats:
|
|
||||||
$ref: "#/components/schemas/Stats"
|
|
||||||
description: Weekly stats of the user.
|
|
||||||
Badge:
|
Badge:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
@@ -2177,6 +2021,47 @@ components:
|
|||||||
- CAR
|
- CAR
|
||||||
- MOTORCYCLE
|
- MOTORCYCLE
|
||||||
- TAXI
|
- TAXI
|
||||||
|
Stats:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
co2_SAVED:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
km_CYCLED:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
km_WALKED:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
km_DRIVEN:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
xp:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
km_PUBLIC_TRANSPORT:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
mobility_SCORE:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
StatsList:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: integer
|
||||||
|
format: int64
|
||||||
|
description: Unique identifier of the StatsList.
|
||||||
|
example: 1
|
||||||
|
totalStats:
|
||||||
|
$ref: "#/components/schemas/Stats"
|
||||||
|
description: Total stats of the user.
|
||||||
|
monthlyStats:
|
||||||
|
$ref: "#/components/schemas/Stats"
|
||||||
|
description: Monthly stats of the user.
|
||||||
|
weeklyStats:
|
||||||
|
$ref: "#/components/schemas/Stats"
|
||||||
|
description: Weekly stats of the user.
|
||||||
Trip:
|
Trip:
|
||||||
type: object
|
type: object
|
||||||
properties:
|
properties:
|
||||||
|
|||||||
@@ -149,14 +149,6 @@
|
|||||||
<artifactId>h3</artifactId>
|
<artifactId>h3</artifactId>
|
||||||
<version>4.4.0</version>
|
<version>4.4.0</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.flywaydb</groupId>
|
|
||||||
<artifactId>flyway-core</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.flywaydb</groupId>
|
|
||||||
<artifactId>flyway-database-postgresql</artifactId>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -1,18 +1,26 @@
|
|||||||
package SuMoC.backend.carrousel.dto;
|
package SuMoC.backend.carrousel.dto;
|
||||||
|
|
||||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||||
|
import SuMoC.backend.geocoding.AddressDTO;
|
||||||
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
||||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
|
|
||||||
@Getter
|
@Getter
|
||||||
public class RegularTripAlternativeContext extends RouteAlternativeContext {
|
public class RegularTripAlternativeContext extends RouteAlternativeContext {
|
||||||
|
|
||||||
private final MinimalDetectedRegularTripDTO detectedRegularTrip;
|
private final MinimalDetectedRegularTripDTO detectedRegularTrip;
|
||||||
|
@Schema(description = "The address of the departure h3 center cell. Note that this is not necessarily the actual departure location of the user, but suburb etc. should match.")
|
||||||
|
private final AddressDTO departureCenter;
|
||||||
|
@Schema(description = "The address of the arrival h3 center cell. Note that this is not necessarily the actual arrival location of the user, but suburb etc. should match.")
|
||||||
|
private final AddressDTO arrivalCenter;
|
||||||
|
|
||||||
public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip) {
|
public RegularTripAlternativeContext(RouteDTO alternative, MinimalDetectedRegularTripDTO detectedRegularTrip, AddressDTO departureCenter, AddressDTO arrivalCenter) {
|
||||||
super(alternative, CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE);
|
super(alternative, CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE);
|
||||||
this.detectedRegularTrip = detectedRegularTrip;
|
this.detectedRegularTrip = detectedRegularTrip;
|
||||||
|
this.departureCenter = departureCenter;
|
||||||
|
this.arrivalCenter = arrivalCenter;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,4 @@ public interface CarrouselCandidateRepository extends JpaRepository<CarrouselCan
|
|||||||
ORDER BY c.suggestedAt DESC
|
ORDER BY c.suggestedAt DESC
|
||||||
""")
|
""")
|
||||||
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
|
List<CarrouselCandidate> findByUserIdDesc(Long userId, Instant cutOff);
|
||||||
|
|
||||||
void deleteAllByUserId(Long userId);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,16 +8,19 @@ import SuMoC.backend.carrousel.dto.RouteAlternativeContext;
|
|||||||
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||||
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
||||||
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
||||||
|
import SuMoC.backend.geocoding.AddressDTO;
|
||||||
|
import SuMoC.backend.geocoding.GeoCodingService;
|
||||||
|
import SuMoC.backend.h3.H3Service;
|
||||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||||
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
||||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
import SuMoC.backend.trip.models.Trip;
|
import SuMoC.backend.trip.models.Trip;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@@ -28,6 +31,10 @@ public class CarrouselService {
|
|||||||
|
|
||||||
private final CarrouselProperties carrouselProperties;
|
private final CarrouselProperties carrouselProperties;
|
||||||
|
|
||||||
|
private final H3Service h3Service;
|
||||||
|
|
||||||
|
private final GeoCodingService geoCodingService;
|
||||||
|
|
||||||
public void addAdHocTripCandidates(Trip trip, List<RouteDTO> suggestedAlternatives) {
|
public void addAdHocTripCandidates(Trip trip, List<RouteDTO> suggestedAlternatives) {
|
||||||
for (var alternative : suggestedAlternatives) {
|
for (var alternative : suggestedAlternatives) {
|
||||||
CarrouselCandidate candidate = CarrouselCandidate.builder()
|
CarrouselCandidate candidate = CarrouselCandidate.builder()
|
||||||
@@ -42,9 +49,7 @@ public class CarrouselService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<CarrouselCandidate> getRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
|
public void addRegularTripCandidates(Long userId, DetectedRegularTripDTO detectedRegularTrip, List<RouteDTO> suggestedAlternatives) {
|
||||||
List<CarrouselCandidate> candidates = new ArrayList<>();
|
|
||||||
|
|
||||||
for (var alternative : suggestedAlternatives) {
|
for (var alternative : suggestedAlternatives) {
|
||||||
CarrouselCandidate candidate = CarrouselCandidate.builder()
|
CarrouselCandidate candidate = CarrouselCandidate.builder()
|
||||||
.userId(userId)
|
.userId(userId)
|
||||||
@@ -53,10 +58,9 @@ public class CarrouselService {
|
|||||||
.suggestedAt(Instant.now())
|
.suggestedAt(Instant.now())
|
||||||
.candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE)
|
.candidateType(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE)
|
||||||
.build();
|
.build();
|
||||||
candidates.add(candidate);
|
|
||||||
}
|
|
||||||
|
|
||||||
return candidates;
|
carrouselCandidateRepository.save(candidate);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public AlternativeCarrouselDTO getCarrouselForUser(Long userId) {
|
public AlternativeCarrouselDTO getCarrouselForUser(Long userId) {
|
||||||
@@ -99,9 +103,24 @@ public class CarrouselService {
|
|||||||
private RouteAlternativeContext fromRegularTripCandidate(CarrouselCandidate candidate) {
|
private RouteAlternativeContext fromRegularTripCandidate(CarrouselCandidate candidate) {
|
||||||
var minRegularTrip = candidate.getDetectedRegularTrip();
|
var minRegularTrip = candidate.getDetectedRegularTrip();
|
||||||
|
|
||||||
|
var startLatLong = h3Service.cellToLatLng(minRegularTrip.getStartH3Center());
|
||||||
|
var endLatLong = h3Service.cellToLatLng(minRegularTrip.getEndH3Center());
|
||||||
|
|
||||||
|
// TODO we might want to remove the center addresses, we already have the start and end place names from the original trip - could save compute time and API calls here
|
||||||
|
// Fetch origin and destination addresses concurrently
|
||||||
|
var addressesMono = Mono.zip(
|
||||||
|
geoCodingService.getAddress(startLatLong.lat, startLatLong.lng),
|
||||||
|
geoCodingService.getAddress(endLatLong.lat, endLatLong.lng)
|
||||||
|
);
|
||||||
|
var addressesTuple = addressesMono.block();
|
||||||
|
AddressDTO startCenterAddress = addressesTuple.getT1();
|
||||||
|
AddressDTO endCenterAddress = addressesTuple.getT2();
|
||||||
|
|
||||||
return new RegularTripAlternativeContext(
|
return new RegularTripAlternativeContext(
|
||||||
candidate.getSuggestedAlternative(),
|
candidate.getSuggestedAlternative(),
|
||||||
minRegularTrip
|
minRegularTrip,
|
||||||
|
startCenterAddress,
|
||||||
|
endCenterAddress
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,39 +0,0 @@
|
|||||||
package SuMoC.backend.config;
|
|
||||||
|
|
||||||
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
|
||||||
import org.springframework.context.annotation.Bean;
|
|
||||||
import org.springframework.context.annotation.Configuration;
|
|
||||||
import org.springframework.scheduling.annotation.EnableAsync;
|
|
||||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
|
||||||
|
|
||||||
import java.util.concurrent.Executor;
|
|
||||||
|
|
||||||
@Configuration
|
|
||||||
@EnableAsync
|
|
||||||
@RequiredArgsConstructor
|
|
||||||
public class AsyncConfiguration {
|
|
||||||
|
|
||||||
private final RegularTripSuggestionProperties regularTripSuggestionProperties;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Custom thread pool executor for parallel processing of regular trip suggestions.
|
|
||||||
* Configured with parallelism setting from application properties.
|
|
||||||
*/
|
|
||||||
@Bean(name = "regularTripSuggestionExecutor")
|
|
||||||
public Executor regularTripSuggestionExecutor() {
|
|
||||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
|
||||||
int parallelism = regularTripSuggestionProperties.getParallelism();
|
|
||||||
|
|
||||||
executor.setCorePoolSize(parallelism);
|
|
||||||
executor.setMaxPoolSize(parallelism);
|
|
||||||
executor.setQueueCapacity(500); // Queue capacity for pending tasks
|
|
||||||
executor.setThreadNamePrefix("regular-trip-");
|
|
||||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
|
||||||
executor.setAwaitTerminationSeconds(60);
|
|
||||||
executor.initialize();
|
|
||||||
|
|
||||||
return executor;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -116,7 +116,10 @@ public class DevController {
|
|||||||
|
|
||||||
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
|
@GetMapping("/test-firebase-adhoc-route-notification/{fcm_token}")
|
||||||
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
|
@Operation(description = "Immediately sends a test notification of type ADHOC_ALTERNATIVE to the provided FCM token.")
|
||||||
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(@PathVariable("fcm_token") @NotNull String fcmToken) {
|
public ResponseEntity<String> SendTestAdhocRouteNotificationFirebase(
|
||||||
|
@PathVariable("fcm_token") @NotNull String fcmToken,
|
||||||
|
@RequestParam(required = false, defaultValue = "false") boolean isIos
|
||||||
|
) {
|
||||||
if (firebaseMessaging == null) {
|
if (firebaseMessaging == null) {
|
||||||
return ResponseEntity.status(503)
|
return ResponseEntity.status(503)
|
||||||
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
.body("✗ Firebase is not configured (firebase.config.enabled=false)");
|
||||||
@@ -127,7 +130,12 @@ public class DevController {
|
|||||||
List<RouteDTO> mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO());
|
List<RouteDTO> mockRoutes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO());
|
||||||
notification.setData(objectMapper.writeValueAsString(mockRoutes));
|
notification.setData(objectMapper.writeValueAsString(mockRoutes));
|
||||||
|
|
||||||
Message mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
Message mockAdhocMessage;
|
||||||
|
if (isIos) {
|
||||||
|
mockAdhocMessage = firebaseMessageBuilder.generateMessageIos(notification, fcmToken);
|
||||||
|
} else {
|
||||||
|
mockAdhocMessage = firebaseMessageBuilder.generateMessage(notification, fcmToken);
|
||||||
|
}
|
||||||
|
|
||||||
// Send to a topic (no device registration needed)
|
// Send to a topic (no device registration needed)
|
||||||
String message = firebaseMessaging.sendAsync(
|
String message = firebaseMessaging.sendAsync(
|
||||||
@@ -292,3 +300,4 @@ public class DevController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package SuMoC.backend.firebase;
|
package SuMoC.backend.firebase;
|
||||||
|
|
||||||
import SuMoC.backend.notification.models.Notification;
|
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 com.google.firebase.messaging.Message;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -14,21 +11,19 @@ public class FirebaseMessageBuilder {
|
|||||||
var builder = Message.builder().setToken(token);
|
var builder = Message.builder().setToken(token);
|
||||||
builder.putData("type", notification.getType().toString());
|
builder.putData("type", notification.getType().toString());
|
||||||
builder.putData("data", notification.getData());
|
builder.putData("data", notification.getData());
|
||||||
|
return builder.build();
|
||||||
|
}
|
||||||
|
|
||||||
//Setup, so iOS can receive and intercept Push Notifications
|
public Message generateMessageIos(Notification notification, String token) {
|
||||||
builder.setNotification(com.google.firebase.messaging.Notification.builder()
|
var builder = Message.builder().setToken(token);
|
||||||
.setTitle("Sumoc Update")
|
builder.putData("type", notification.getType().toString());
|
||||||
.setBody("Deine Nachricht ist da!")
|
builder.putData("data", notification.getData());
|
||||||
|
var apnConfig = com.google.firebase.messaging.ApnsConfig.builder()
|
||||||
|
.setAps(com.google.firebase.messaging.Aps.builder()
|
||||||
|
.setContentAvailable(true)
|
||||||
.build())
|
.build())
|
||||||
.setApnsConfig(ApnsConfig.builder()
|
.build();
|
||||||
.setAps(Aps.builder()
|
builder.setApnsConfig(apnConfig);
|
||||||
.setMutableContent(true)
|
|
||||||
.setSound("default") // WICHTIG: Ohne Sound oft keine Anzeige
|
|
||||||
.setBadge(1)
|
|
||||||
.build())
|
|
||||||
.build());
|
|
||||||
|
|
||||||
|
|
||||||
return builder.build();
|
return builder.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
|||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import SuMoC.backend.user.service.CurrentUserService;
|
import SuMoC.backend.user.service.CurrentUserService;
|
||||||
import SuMoC.backend.user.service.PrivacyService;
|
import SuMoC.backend.user.service.PrivacyService;
|
||||||
import jakarta.transaction.Transactional;
|
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
@@ -22,7 +21,6 @@ import java.util.Map;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Transactional
|
|
||||||
public class BadgeService {
|
public class BadgeService {
|
||||||
|
|
||||||
private final CurrentUserService currentUser;
|
private final CurrentUserService currentUser;
|
||||||
|
|||||||
+4
-4
@@ -1,11 +1,11 @@
|
|||||||
package SuMoC.backend.seed;
|
package SuMoC.backend.gamification.badges;
|
||||||
|
|
||||||
import SuMoC.backend.gamification.badges.BadgeRepository;
|
|
||||||
import SuMoC.backend.gamification.badges.BadgeService;
|
|
||||||
import SuMoC.backend.gamification.badges.mapper.BadgeMapper;
|
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.BadgeCategory;
|
||||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
|
import kotlin.collections.ArrayDeque;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.CommandLineRunner;
|
import org.springframework.boot.CommandLineRunner;
|
||||||
import org.springframework.context.annotation.Profile;
|
import org.springframework.context.annotation.Profile;
|
||||||
@@ -16,7 +16,7 @@ import java.util.*;
|
|||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Profile("dev")
|
@Profile("dev")
|
||||||
@Order(2)
|
@Order(3)
|
||||||
public class DevBadgeSeeder implements CommandLineRunner {
|
public class DevBadgeSeeder implements CommandLineRunner {
|
||||||
|
|
||||||
private final BadgeService badgeService;
|
private final BadgeService badgeService;
|
||||||
@@ -16,7 +16,7 @@ public class Badge {
|
|||||||
private String description;
|
private String description;
|
||||||
private BadgeCategory category;
|
private BadgeCategory category;
|
||||||
|
|
||||||
@OneToOne(mappedBy = "badge", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
@OneToOne(mappedBy = "badge", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
private BadgeImageEntity image;
|
private BadgeImageEntity image;
|
||||||
|
|
||||||
@ElementCollection
|
@ElementCollection
|
||||||
|
|||||||
@@ -34,11 +34,11 @@ public interface ChallengeMapper {
|
|||||||
challenge.setCriteria(dto.getCriteria());
|
challenge.setCriteria(dto.getCriteria());
|
||||||
challenge.setReward(dto.getReward());
|
challenge.setReward(dto.getReward());
|
||||||
|
|
||||||
if (dto.getBase64image() != null && !dto.getBase64image().isBlank()) {
|
if (dto.getBase64image() != null && !dto.getBase64image().isEmpty()) {
|
||||||
byte[] bytes = ImageBase64Util.decode(dto.getBase64image());
|
challenge.setImage(new ChallengeImageEntity(
|
||||||
ChallengeImageEntity img = new ChallengeImageEntity();
|
challenge,
|
||||||
img.setImageData(bytes);
|
ImageBase64Util.decode(dto.getBase64image())
|
||||||
challenge.setImage(img);
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
return challenge;
|
return challenge;
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ import java.util.List;
|
|||||||
import static java.lang.Math.min;
|
import static java.lang.Math.min;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Transactional
|
|
||||||
public class ChallengeService {
|
public class ChallengeService {
|
||||||
|
|
||||||
private final CurrentUserService currentUser;
|
private final CurrentUserService currentUser;
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ public class Challenge {
|
|||||||
private String description;
|
private String description;
|
||||||
|
|
||||||
|
|
||||||
@OneToOne(mappedBy = "challenge", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
@OneToOne(mappedBy = "challenge", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
private ChallengeImageEntity image;
|
private ChallengeImageEntity image;
|
||||||
|
|
||||||
@ElementCollection
|
@ElementCollection
|
||||||
@@ -85,9 +85,6 @@ public class Challenge {
|
|||||||
|
|
||||||
public void setImage(ChallengeImageEntity image) {
|
public void setImage(ChallengeImageEntity image) {
|
||||||
this.image = image;
|
this.image = image;
|
||||||
if (image != null) {
|
|
||||||
image.setChallenge(this);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Integer> getCriteria() {
|
public Map<String, Integer> getCriteria() {
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import SuMoC.backend.user.service.CurrentUserService;
|
|||||||
import SuMoC.backend.user.service.FriendshipService;
|
import SuMoC.backend.user.service.FriendshipService;
|
||||||
import SuMoC.backend.user.service.PrivacyService;
|
import SuMoC.backend.user.service.PrivacyService;
|
||||||
import SuMoC.backend.user.stats.*;
|
import SuMoC.backend.user.stats.*;
|
||||||
import jakarta.transaction.Transactional;
|
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
@@ -21,7 +20,6 @@ import java.util.List;
|
|||||||
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Transactional
|
|
||||||
public class LeaderboardService {
|
public class LeaderboardService {
|
||||||
private final FriendshipService friendshipService;
|
private final FriendshipService friendshipService;
|
||||||
private final StatsListRepository statsListRepository;
|
private final StatsListRepository statsListRepository;
|
||||||
|
|||||||
@@ -10,9 +10,8 @@ public class ImageEntity {
|
|||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||||
private int id;
|
private int id;
|
||||||
|
|
||||||
//@Lob
|
@Lob
|
||||||
@Basic(fetch = FetchType.EAGER)
|
//@Column(columnDefinition = "BYTEA")
|
||||||
@Column(columnDefinition = "bytea")
|
|
||||||
//@Column(columnDefinition = "BLOB")
|
//@Column(columnDefinition = "BLOB")
|
||||||
private byte[] imageData;
|
private byte[] imageData;
|
||||||
|
|
||||||
|
|||||||
@@ -37,14 +37,6 @@ public class NotificationController {
|
|||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@PutMapping("/unregister-device-token")
|
|
||||||
@Operation(description = "Unregisters the device token for push notifications for the authenticated user.")
|
|
||||||
public ResponseEntity<Void> unregisterDeviceToken() {
|
|
||||||
User user = getAuthenticatedUser();
|
|
||||||
notificationTokenService.unregisterDeviceToken(user);
|
|
||||||
return ResponseEntity.ok().build();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Simple record for request body
|
// Simple record for request body
|
||||||
public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) {
|
public record RegisterDeviceTokenRequest(String token, NotificationProvider provider) {
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,12 +37,18 @@ Each notification type includes a data payload. The main DTOs in the notificatio
|
|||||||
To receive push notifications, clients must register their device token. Token registration is handled in the
|
To receive push notifications, clients must register their device token. Token registration is handled in the
|
||||||
`NotificationController`. The backend stores or updates the token for the authenticated user.
|
`NotificationController`. The backend stores or updates the token for the authenticated user.
|
||||||
|
|
||||||
### Unregistering Device Token
|
### Notification Providers
|
||||||
|
|
||||||
When a user logs out, the client should call the device token unregistration endpoint to remove the device token from
|
When registering a device token, clients must specify the notification provider. The supported providers are defined in
|
||||||
the backend. This ensures the user will no longer receive push notifications on that device after logout.
|
`NotificationProvider.java`:
|
||||||
|
|
||||||
- **Endpoint:** `PUT /notifications/unregister-device-token`
|
- **FIREBASE**: Use this provider for Android devices. Tokens registered with this type will be used to send
|
||||||
|
notifications via Firebase Cloud Messaging (FCM) for Android.
|
||||||
|
- **FIREBASE_IOS**: Use this provider for iOS devices. Tokens registered with this type will be used to send
|
||||||
|
notifications via Firebase Cloud Messaging (FCM) for iOS.
|
||||||
|
|
||||||
|
Specify the appropriate provider when registering the device token to ensure notifications are delivered correctly to
|
||||||
|
the device platform.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -2,4 +2,5 @@ package SuMoC.backend.notification.enums;
|
|||||||
|
|
||||||
public enum NotificationProvider {
|
public enum NotificationProvider {
|
||||||
FIREBASE,
|
FIREBASE,
|
||||||
|
FIREBASE_IOS
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +0,0 @@
|
|||||||
package SuMoC.backend.notification.interfaces;
|
|
||||||
|
|
||||||
import java.time.LocalTime;
|
|
||||||
|
|
||||||
public interface NotifieableWithTime {
|
|
||||||
Long getUserId();
|
|
||||||
|
|
||||||
LocalTime getEarliestTimeOfDayToSend();
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package SuMoC.backend.notification.repositories;
|
package SuMoC.backend.notification.repositories;
|
||||||
|
|
||||||
import SuMoC.backend.notification.models.Notification;
|
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.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Modifying;
|
import org.springframework.data.jpa.repository.Modifying;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
@@ -37,6 +36,4 @@ public interface NotificationRepository extends JpaRepository<Notification, Long
|
|||||||
WHERE n.createdAt < :cutOff
|
WHERE n.createdAt < :cutOff
|
||||||
""")
|
""")
|
||||||
void deleteNotificationsOlder(Instant cutOff);
|
void deleteNotificationsOlder(Instant cutOff);
|
||||||
|
|
||||||
void deleteAllByUser(User user);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
package SuMoC.backend.notification.services;
|
|
||||||
|
|
||||||
import SuMoC.backend.security.dtos.PasswordResetDTO;
|
|
||||||
import SuMoC.backend.security.models.PasswordResetToken;
|
|
||||||
import SuMoC.backend.security.services.AuthenticationService;
|
|
||||||
import jdk.dynalink.linker.support.SimpleLinkRequest;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
|
||||||
import org.springframework.mail.MailException;
|
|
||||||
import org.springframework.mail.SimpleMailMessage;
|
|
||||||
import org.springframework.mail.javamail.JavaMailSender;
|
|
||||||
import org.springframework.scheduling.annotation.Async;
|
|
||||||
import org.springframework.stereotype.Service;
|
|
||||||
|
|
||||||
@Service
|
|
||||||
public class EmailService {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private JavaMailSender mailSender;
|
|
||||||
|
|
||||||
@Async
|
|
||||||
public void sendPasswordResetEmail(String email, String otp_code) throws MailException {
|
|
||||||
SimpleMailMessage message = new SimpleMailMessage();
|
|
||||||
|
|
||||||
message.setFrom("SuMoC@outlook.de");
|
|
||||||
message.setTo(email);
|
|
||||||
message.setSubject("Dein Passwort-Reset Code");
|
|
||||||
message.setText("Hallo!\n\nDein OTP Code lautet: " + otp_code +
|
|
||||||
"\nDieser Code ist für " + String.valueOf(PasswordResetToken.EXPIRY_TIME_MINUTES) + " Minuten gültig.");
|
|
||||||
|
|
||||||
mailSender.send(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -3,7 +3,6 @@ package SuMoC.backend.notification.services;
|
|||||||
import SuMoC.backend.notification.enums.NotificationStatus;
|
import SuMoC.backend.notification.enums.NotificationStatus;
|
||||||
import SuMoC.backend.notification.enums.NotificationType;
|
import SuMoC.backend.notification.enums.NotificationType;
|
||||||
import SuMoC.backend.notification.interfaces.Notifieable;
|
import SuMoC.backend.notification.interfaces.Notifieable;
|
||||||
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
|
|
||||||
import SuMoC.backend.notification.models.Notification;
|
import SuMoC.backend.notification.models.Notification;
|
||||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
import SuMoC.backend.notification.repositories.NotificationRepository;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
@@ -66,33 +65,6 @@ public class NotificationSchedulerService {
|
|||||||
notificationRepository.saveAll(notifications);
|
notificationRepository.saveAll(notifications);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void scheduleAll(List<NotifieableWithTime> dataBodies,
|
|
||||||
NotificationType notificationType
|
|
||||||
) {
|
|
||||||
List<Notification> notifications = dataBodies.stream().map(dataBody -> {
|
|
||||||
String dataBodyJson;
|
|
||||||
try {
|
|
||||||
dataBodyJson = objectMapper.writeValueAsString(dataBody);
|
|
||||||
} catch (Exception e) {
|
|
||||||
throw new RuntimeException("Failed to serialize notification data body", e);
|
|
||||||
}
|
|
||||||
|
|
||||||
User userProxy = entityManager.getReference(User.class, dataBody.getUserId());
|
|
||||||
|
|
||||||
return Notification.builder()
|
|
||||||
.user(userProxy)
|
|
||||||
.type(notificationType)
|
|
||||||
.data(dataBodyJson)
|
|
||||||
.earliestTimeOfDayToSend(dataBody.getEarliestTimeOfDayToSend())
|
|
||||||
.status(NotificationStatus.PENDING)
|
|
||||||
.createdAt(Instant.now())
|
|
||||||
.failedSendAttempts(0)
|
|
||||||
.build();
|
|
||||||
}).toList();
|
|
||||||
|
|
||||||
notificationRepository.saveAll(notifications);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Schedules a notification to be sent to the specified user.
|
* Schedules a notification to be sent to the specified user.
|
||||||
* Data body needs to be serializable to JSON.
|
* Data body needs to be serializable to JSON.
|
||||||
|
|||||||
@@ -46,17 +46,26 @@ public class NotificationSender {
|
|||||||
if (token == null) {
|
if (token == null) {
|
||||||
logger.warning("No notification token found notification id: " + notification.getId());
|
logger.warning("No notification token found notification id: " + notification.getId());
|
||||||
notification.incrementFailedSendAttempts();
|
notification.incrementFailedSendAttempts();
|
||||||
notification.setLastFailureReason("No notification token found for user");
|
|
||||||
setFailedIfLimitExceeded(notification);
|
|
||||||
notificationRepository.save(notification);
|
notificationRepository.save(notification);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (token.getProvider()) {
|
switch (token.getProvider()) {
|
||||||
case FIREBASE -> sendViaFirebase(token, notification);
|
case FIREBASE -> sendViaFirebase(token, notification);
|
||||||
|
case FIREBASE_IOS -> sendViaFirebaseIos(token, notification);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void sendViaFirebaseIos(NotificationToken token, Notification notification) {
|
||||||
|
if (firebaseMessaging == null) {
|
||||||
|
logger.warning("FirebaseMessaging not configured");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Message message = firebaseMessageBuilder.generateMessageIos(notification, token.getToken());
|
||||||
|
sendAndHandleResultFirebase(message, notification);
|
||||||
|
}
|
||||||
|
|
||||||
private void sendViaFirebase(NotificationToken token, Notification notification) {
|
private void sendViaFirebase(NotificationToken token, Notification notification) {
|
||||||
if (firebaseMessaging == null) {
|
if (firebaseMessaging == null) {
|
||||||
logger.warning("FirebaseMessaging not configured");
|
logger.warning("FirebaseMessaging not configured");
|
||||||
@@ -64,7 +73,10 @@ public class NotificationSender {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken());
|
Message message = firebaseMessageBuilder.generateMessage(notification, token.getToken());
|
||||||
|
sendAndHandleResultFirebase(message, notification);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void sendAndHandleResultFirebase(Message message, Notification notification) {
|
||||||
ApiFuture<String> future = firebaseMessaging.sendAsync(message);
|
ApiFuture<String> future = firebaseMessaging.sendAsync(message);
|
||||||
ApiFutures.addCallback(future, new ApiFutureCallback<String>() {
|
ApiFutures.addCallback(future, new ApiFutureCallback<String>() {
|
||||||
@Override
|
@Override
|
||||||
@@ -79,17 +91,12 @@ public class NotificationSender {
|
|||||||
public void onFailure(Throwable t) {
|
public void onFailure(Throwable t) {
|
||||||
notification.incrementFailedSendAttempts();
|
notification.incrementFailedSendAttempts();
|
||||||
notification.setLastFailureReason(t.getMessage());
|
notification.setLastFailureReason(t.getMessage());
|
||||||
setFailedIfLimitExceeded(notification);
|
if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) {
|
||||||
|
notification.setStatus(NotificationStatus.FAILED);
|
||||||
|
}
|
||||||
notificationRepository.save(notification);
|
notificationRepository.save(notification);
|
||||||
logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage());
|
logger.severe("Failed to send notification with id:" + notification.getId() + " " + t.getMessage());
|
||||||
}
|
}
|
||||||
}, MoreExecutors.directExecutor());
|
}, MoreExecutors.directExecutor());
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private void setFailedIfLimitExceeded(Notification notification) {
|
|
||||||
if (notification.getFailedSendAttempts() >= notificationProperties.getMaxFailedSendAttempts()) {
|
|
||||||
notification.setStatus(NotificationStatus.FAILED);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import SuMoC.backend.notification.enums.NotificationProvider;
|
|||||||
import SuMoC.backend.notification.models.NotificationToken;
|
import SuMoC.backend.notification.models.NotificationToken;
|
||||||
import SuMoC.backend.notification.repositories.NotificationTokenRepository;
|
import SuMoC.backend.notification.repositories.NotificationTokenRepository;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import jakarta.transaction.Transactional;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -28,13 +27,4 @@ public class NotificationTokenService {
|
|||||||
notificationTokenRepository.save(newToken);
|
notificationTokenRepository.save(newToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void unregisterDeviceToken(User user) {
|
|
||||||
var existingToken = notificationTokenRepository.findByUserId(user.getId());
|
|
||||||
existingToken.ifPresent(token -> {
|
|
||||||
user.setNotificationToken(null);
|
|
||||||
notificationTokenRepository.delete(token);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,10 @@ import SuMoC.backend.trip.Modality;
|
|||||||
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
|
||||||
import java.time.*;
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -65,13 +68,13 @@ public class DetectedRegularTripDTO {
|
|||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
|
|
||||||
public Instant getAverageArrivalTime() {
|
public LocalTime getAverageArrivalTime() {
|
||||||
long totalSeconds = 0;
|
int totalSeconds = 0;
|
||||||
for (RegularTripDetectionDTO trip : supportingTrips) {
|
for (RegularTripDetectionDTO trip : supportingTrips) {
|
||||||
totalSeconds += trip.getEndTime().getEpochSecond();
|
totalSeconds += trip.getEndTime().atOffset(ZoneOffset.UTC).toLocalTime().toSecondOfDay();
|
||||||
}
|
}
|
||||||
long averageSeconds = totalSeconds / supportingTrips.size();
|
int averageSeconds = totalSeconds / supportingTrips.size();
|
||||||
return Instant.ofEpochSecond(averageSeconds);
|
return LocalTime.ofSecondOfDay(averageSeconds);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getAverageDurationMinutes() {
|
public int getAverageDurationMinutes() {
|
||||||
|
|||||||
@@ -28,8 +28,6 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
private LocalTime arrivalWindowStart;
|
private LocalTime arrivalWindowStart;
|
||||||
@Schema(description = "Latest arrival time among the supporting trips, in the user's local time")
|
@Schema(description = "Latest arrival time among the supporting trips, in the user's local time")
|
||||||
private LocalTime arrivalWindowEnd;
|
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 startH3Center;
|
||||||
private String endH3Center;
|
private String endH3Center;
|
||||||
|
|
||||||
@@ -43,15 +41,12 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
minimalDTO.arrivalWindowEnd = getLatestArrival(regularTrip.getSupportingTrips());
|
minimalDTO.arrivalWindowEnd = getLatestArrival(regularTrip.getSupportingTrips());
|
||||||
minimalDTO.startH3Center = regularTrip.getStartH3Center();
|
minimalDTO.startH3Center = regularTrip.getStartH3Center();
|
||||||
minimalDTO.endH3Center = regularTrip.getEndH3Center();
|
minimalDTO.endH3Center = regularTrip.getEndH3Center();
|
||||||
minimalDTO.supportingTripIds = regularTrip.getSupportingTrips().stream()
|
|
||||||
.map(RegularTripDetectionDTO::getTripId)
|
|
||||||
.toList();
|
|
||||||
return minimalDTO;
|
return minimalDTO;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getEarliestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var earliest = supportingTrips.stream()
|
var earliest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getEndTime)
|
.map(RegularTripDetectionDTO::getStartTime)
|
||||||
.min(Comparator.naturalOrder())
|
.min(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||||
@@ -59,7 +54,7 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
|
|
||||||
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getLatestArrival(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var latest = supportingTrips.stream()
|
var latest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getEndTime)
|
.map(RegularTripDetectionDTO::getStartTime)
|
||||||
.max(Comparator.naturalOrder())
|
.max(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||||
@@ -67,7 +62,7 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
|
|
||||||
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getEarliestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var earliest = supportingTrips.stream()
|
var earliest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getStartTime)
|
.map(RegularTripDetectionDTO::getEndTime)
|
||||||
.min(Comparator.naturalOrder())
|
.min(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(earliest, ZoneId.systemDefault());
|
||||||
@@ -75,7 +70,7 @@ public class MinimalDetectedRegularTripDTO {
|
|||||||
|
|
||||||
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
private static LocalTime getLatestDeparture(List<RegularTripDetectionDTO> supportingTrips) {
|
||||||
var latest = supportingTrips.stream()
|
var latest = supportingTrips.stream()
|
||||||
.map(RegularTripDetectionDTO::getStartTime)
|
.map(RegularTripDetectionDTO::getEndTime)
|
||||||
.max(Comparator.naturalOrder())
|
.max(Comparator.naturalOrder())
|
||||||
.orElseThrow();
|
.orElseThrow();
|
||||||
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
return LocalTime.ofInstant(latest, ZoneId.systemDefault());
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ public class AdHocRoutingProperties extends RoutingProperties {
|
|||||||
|
|
||||||
public AdHocRoutingProperties() {
|
public AdHocRoutingProperties() {
|
||||||
super();
|
super();
|
||||||
setAcceptableAdditionalMultiplierRegular(2.0);
|
setAcceptableAdditionalMultiplierRegular(1.30);
|
||||||
setAcceptableAdditionalMultiplierPrefersPhysical(2.0);
|
setAcceptableAdditionalMultiplierPrefersPhysical(1.6);
|
||||||
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
|
setMinimumAcceptedAdditionalSecondsRegular(5 * 60);
|
||||||
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
|
setMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity(5 * 60);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,8 +6,6 @@ import SuMoC.backend.meteo.WeatherCondition;
|
|||||||
import SuMoC.backend.routing.config.RoutingProperties;
|
import SuMoC.backend.routing.config.RoutingProperties;
|
||||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||||
import SuMoC.backend.routing.dtos.StepDTO;
|
|
||||||
import SuMoC.backend.trip.Modality;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
@@ -52,12 +50,12 @@ public class AlternativeFilterService {
|
|||||||
|
|
||||||
if (routeDTO.isPhysicalActivity() && alternativeRequestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
if (routeDTO.isPhysicalActivity() && alternativeRequestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
||||||
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()
|
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()
|
||||||
|| travelTimeDeltaSeconds < toleratedMaximumPhysical) {
|
|| (long) travelTimeDeltaSeconds < toleratedMaximumPhysical) {
|
||||||
filteredAlternatives.add(routeDTO);
|
filteredAlternatives.add(routeDTO);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsRegular()
|
if (travelTimeDeltaSeconds < routingProperties.getMinimumAcceptedAdditionalSecondsRegular()
|
||||||
|| travelTimeDeltaSeconds < toleratedMaximumRegular) {
|
|| (long) travelTimeDeltaSeconds < toleratedMaximumRegular) {
|
||||||
filteredAlternatives.add(routeDTO);
|
filteredAlternatives.add(routeDTO);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -82,16 +80,14 @@ public class AlternativeFilterService {
|
|||||||
ArrayList<RouteDTO> filteredAlternatives = new ArrayList<>();
|
ArrayList<RouteDTO> filteredAlternatives = new ArrayList<>();
|
||||||
for (RouteDTO route : alternatives) {
|
for (RouteDTO route : alternatives) {
|
||||||
if (route.isPhysicalActivity()) {
|
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());
|
var weatherConditions = forecast.getWeatherConditionsBetween(route.getStartDateTime(), route.getEndDateTime());
|
||||||
if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
|
if (route.isCyclingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableCyclingConditions())) {
|
||||||
filteredAlternatives.add(route);
|
filteredAlternatives.add(route);
|
||||||
} else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
|
} else if (route.isWalkingRoute() && allConditionsAcceptable(weatherConditions, routingProperties.getAcceptableWalkingConditions())) {
|
||||||
filteredAlternatives.add(route);
|
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 {
|
} else {
|
||||||
filteredAlternatives.add(route);
|
filteredAlternatives.add(route);
|
||||||
}
|
}
|
||||||
@@ -104,49 +100,6 @@ public class AlternativeFilterService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* This method is meant to filter out transit routes that would make no sense from the user perspective.
|
|
||||||
*
|
|
||||||
* @param alternatives
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public List<RouteDTO> filterForInefficientTransitRoutes(
|
|
||||||
List<RouteDTO> alternatives
|
|
||||||
) {
|
|
||||||
List<RouteDTO> filteredAlternatives = new ArrayList<>();
|
|
||||||
|
|
||||||
var directWalkingRoute = findDirectWalkingRoute(alternatives);
|
|
||||||
for (var alternative : alternatives) {
|
|
||||||
// Case 1: Sum of walking is greater than direct walking route
|
|
||||||
if (directWalkingRoute != null) {
|
|
||||||
double alternativeWalkingDistance = alternative.getSteps().stream()
|
|
||||||
.filter(step -> step.getModality() == Modality.WALKING)
|
|
||||||
.map(StepDTO::getDistanceMeters)
|
|
||||||
.reduce(0d, Double::sum);
|
|
||||||
double directWalkingDistance = directWalkingRoute.getSteps().stream()
|
|
||||||
.filter(step -> step.getModality() == Modality.WALKING)
|
|
||||||
.map(StepDTO::getDistanceMeters)
|
|
||||||
.reduce(0d, Double::sum);
|
|
||||||
if (directWalkingDistance < alternativeWalkingDistance) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
filteredAlternatives.add(alternative);
|
|
||||||
}
|
|
||||||
|
|
||||||
return filteredAlternatives;
|
|
||||||
}
|
|
||||||
|
|
||||||
private RouteDTO findDirectWalkingRoute(List<RouteDTO> alternatives) {
|
|
||||||
return alternatives.stream()
|
|
||||||
.filter(RouteDTO::isWalkingRoute)
|
|
||||||
.min((r1, r2) -> Long.compare(
|
|
||||||
r1.getDurationSeconds(),
|
|
||||||
r2.getDurationSeconds()
|
|
||||||
)).orElse(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean allConditionsAcceptable(List<WeatherCondition> conditions, List<WeatherCondition> acceptableConditions) {
|
private boolean allConditionsAcceptable(List<WeatherCondition> conditions, List<WeatherCondition> acceptableConditions) {
|
||||||
return new HashSet<>(acceptableConditions).containsAll(conditions);
|
return new HashSet<>(acceptableConditions).containsAll(conditions);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ public class AlternativeRoutingService {
|
|||||||
public List<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
|
public List<RouteDTO> determineAlternativeRoutesOnUserRequest(RoutingAlternativeRequestDTO requestDTO) {
|
||||||
List<RouteDTO> routes = directionsService.getPossibleAlternativeRoutes(requestDTO);
|
List<RouteDTO> routes = directionsService.getPossibleAlternativeRoutes(requestDTO);
|
||||||
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
|
routes = alternativeFilterService.filterForAdditionalTravelTime(requestDTO, routes, onCallRoutingProperties);
|
||||||
routes = alternativeFilterService.filterForInefficientTransitRoutes(routes);
|
|
||||||
|
|
||||||
return routes;
|
return routes;
|
||||||
}
|
}
|
||||||
@@ -53,7 +52,6 @@ public class AlternativeRoutingService {
|
|||||||
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||||
}
|
}
|
||||||
|
|
||||||
routes = alternativeFilterService.filterForInefficientTransitRoutes(routes);
|
|
||||||
return routes;
|
return routes;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,8 +65,6 @@ public class AlternativeRoutingService {
|
|||||||
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
routes = alternativeFilterService.filterForBadWeather(requestDTO, routes, adHocRoutingProperties);
|
||||||
}
|
}
|
||||||
|
|
||||||
routes = alternativeFilterService.filterForInefficientTransitRoutes(routes);
|
|
||||||
|
|
||||||
RouteDTO bestRoute = null;
|
RouteDTO bestRoute = null;
|
||||||
// if users wants physical activity, we pick the fastest physical activity route, if any
|
// if users wants physical activity, we pick the fastest physical activity route, if any
|
||||||
if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
if (requestDTO.getRoutingPreferencesDTO().isPreferPhysicalActivity()) {
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ public class RoutingPreferencesService {
|
|||||||
* Gets routing preferences for the current user, if user is logged in returns his preferences, if not logged in returns default preferences.
|
* Gets routing preferences for the current user, if user is logged in returns his preferences, if not logged in returns default preferences.
|
||||||
*/
|
*/
|
||||||
public RoutingPreferencesDTO getRoutingPreferencesForCurrentUser() {
|
public RoutingPreferencesDTO getRoutingPreferencesForCurrentUser() {
|
||||||
if (currentUserService.isLoggedInUser()) {
|
if (currentUserService.isAuthenticated()) {
|
||||||
var currentUser = currentUserService.get();
|
var currentUser = currentUserService.get();
|
||||||
return getUserRoutingPreferences(currentUser.getId());
|
return getUserRoutingPreferences(currentUser.getId());
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -95,11 +95,11 @@ public class SecurityConfiguration {
|
|||||||
auth.requestMatchers("/auth/user/**").permitAll();
|
auth.requestMatchers("/auth/user/**").permitAll();
|
||||||
auth.requestMatchers("/routing/directions/**").permitAll();
|
auth.requestMatchers("/routing/directions/**").permitAll();
|
||||||
auth.requestMatchers("/routing/alternative/**").permitAll();
|
auth.requestMatchers("/routing/alternative/**").permitAll();
|
||||||
auth.requestMatchers("/geocoding/**").permitAll();
|
|
||||||
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
|
auth.requestMatchers("/admin/**").hasRole("ADMIN"); //looks for "ROLE_ADMIN" //alternative: hasAuthoritiy("ADMIN")
|
||||||
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
|
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
|
||||||
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
|
auth.requestMatchers("/friendship/**").hasAnyRole("ADMIN", "USER");
|
||||||
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
|
auth.requestMatchers("/trip/**").hasAnyRole("USER", "ADMIN");
|
||||||
|
auth.requestMatchers("/geocoding/**").hasAnyRole("USER", "ADMIN");
|
||||||
auth.requestMatchers("/routing/alternative/carrousel/**").hasAnyRole("USER", "ADMIN");
|
auth.requestMatchers("/routing/alternative/carrousel/**").hasAnyRole("USER", "ADMIN");
|
||||||
auth.requestMatchers("/routing/preferences/**").hasAnyRole("USER", "ADMIN");
|
auth.requestMatchers("/routing/preferences/**").hasAnyRole("USER", "ADMIN");
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
package SuMoC.backend.security.controller;
|
package SuMoC.backend.security.controller;
|
||||||
|
|
||||||
|
|
||||||
import SuMoC.backend.security.dtos.*;
|
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||||
import SuMoC.backend.security.exceptions.InvalidTokenException;
|
import SuMoC.backend.security.dtos.RegistrationResponseDTO;
|
||||||
|
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
|
||||||
|
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||||
import SuMoC.backend.security.services.AuthenticationService;
|
import SuMoC.backend.security.services.AuthenticationService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.media.Content;
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
@@ -12,8 +14,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses;
|
|||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.mail.MailException;
|
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
|
||||||
import org.springframework.web.bind.annotation.PostMapping;
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestBody;
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
@@ -74,39 +74,4 @@ public class UserAuthenticationController {
|
|||||||
|
|
||||||
return new ResponseEntity<>(responseDTO, HttpStatus.OK);
|
return new ResponseEntity<>(responseDTO, HttpStatus.OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "OTP Code zur änderung des Passworts", 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.")
|
|
||||||
@PostMapping("/request-otp-for-password-reset")
|
|
||||||
public ResponseEntity<String> requestOtpForPasswordReset(@RequestBody OtpRequestDTO otpRequestDTO) {
|
|
||||||
|
|
||||||
try{
|
|
||||||
authenticationService.generateNewPasswordResetTokenForUser(otpRequestDTO.getEmail());
|
|
||||||
return ResponseEntity.ok("OTP erstellt");
|
|
||||||
} catch (UsernameNotFoundException e) {
|
|
||||||
return ResponseEntity.badRequest().body(e.getMessage());
|
|
||||||
} catch(MailException e){
|
|
||||||
System.out.println(" ## MAIL EXCEPTION \n" +e.getMessage());
|
|
||||||
return ResponseEntity.internalServerError().body("Fehler beim versenden der Email, versuche es später erneut");
|
|
||||||
} catch (Exception e) {
|
|
||||||
return ResponseEntity.internalServerError().body("Fehler beim erstellen des OTP");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(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.")
|
|
||||||
@PostMapping("/reset-password")
|
|
||||||
public ResponseEntity<String> resetPassword(@RequestBody PasswordResetDTO passwordResetDTO){
|
|
||||||
try {
|
|
||||||
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) {
|
|
||||||
e.printStackTrace();
|
|
||||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
package SuMoC.backend.security.dtos;
|
|
||||||
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class OtpRequestDTO {
|
|
||||||
String email;
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package SuMoC.backend.security.dtos;
|
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
|
||||||
import lombok.AllArgsConstructor;
|
|
||||||
import lombok.Getter;
|
|
||||||
import lombok.Setter;
|
|
||||||
|
|
||||||
@Getter
|
|
||||||
@Setter
|
|
||||||
@AllArgsConstructor
|
|
||||||
public class PasswordResetDTO {
|
|
||||||
@JsonAlias({"otp_code", "otpCode"})
|
|
||||||
String otpCode;
|
|
||||||
String email;
|
|
||||||
@JsonAlias({"new_password", "newPassword"})
|
|
||||||
String newPassword;
|
|
||||||
}
|
|
||||||
@@ -6,6 +6,5 @@ public enum RegistrationStatus {
|
|||||||
EMAIL_INVALID,
|
EMAIL_INVALID,
|
||||||
PUBLIC_NAME_EXISTS,
|
PUBLIC_NAME_EXISTS,
|
||||||
PUBLIC_NAME_FORBIDDEN,
|
PUBLIC_NAME_FORBIDDEN,
|
||||||
PASSWORD_INVALID,
|
|
||||||
UNKNOWN_ERROR
|
UNKNOWN_ERROR
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
package SuMoC.backend.security.exceptions;
|
|
||||||
|
|
||||||
public class InvalidTokenException extends RuntimeException {
|
|
||||||
public InvalidTokenException(String message) { super(message); }
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
package SuMoC.backend.security.models;
|
|
||||||
|
|
||||||
import jakarta.persistence.*;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
|
|
||||||
@Entity
|
|
||||||
@Table(name = "OneTimePasswordTokens")
|
|
||||||
@Getter
|
|
||||||
public class PasswordResetToken{
|
|
||||||
|
|
||||||
public static int EXPIRY_TIME_MINUTES = 30;
|
|
||||||
|
|
||||||
@Id
|
|
||||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
|
||||||
private Long id;
|
|
||||||
|
|
||||||
private String email;
|
|
||||||
private String otpCode;
|
|
||||||
private LocalDateTime expiryDate;
|
|
||||||
|
|
||||||
public PasswordResetToken(String email, String code) {
|
|
||||||
this.email = email;
|
|
||||||
this.otpCode = code;
|
|
||||||
this.expiryDate = LocalDateTime.now().plusMinutes(EXPIRY_TIME_MINUTES);
|
|
||||||
}
|
|
||||||
|
|
||||||
public PasswordResetToken() {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
package SuMoC.backend.security.repository;
|
|
||||||
|
|
||||||
import SuMoC.backend.security.models.PasswordResetToken;
|
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public interface PasswordResetTokenRepository extends JpaRepository<PasswordResetToken, Long> {
|
|
||||||
Boolean existsByEmail(String email);
|
|
||||||
|
|
||||||
Optional<PasswordResetToken> findByEmail(String email);
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
package SuMoC.backend.security.services;
|
package SuMoC.backend.security.services;
|
||||||
|
|
||||||
import SuMoC.backend.notification.services.EmailService;
|
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||||
import SuMoC.backend.security.dtos.*;
|
import SuMoC.backend.security.dtos.RegistrationResponseDTO;
|
||||||
|
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
|
||||||
|
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||||
import SuMoC.backend.security.enums.RegistrationStatus;
|
import SuMoC.backend.security.enums.RegistrationStatus;
|
||||||
import SuMoC.backend.security.exceptions.InvalidTokenException;
|
|
||||||
import SuMoC.backend.security.models.PasswordResetToken;
|
|
||||||
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
|
|
||||||
import SuMoC.backend.user.dtos.UserDTO;
|
import SuMoC.backend.user.dtos.UserDTO;
|
||||||
import SuMoC.backend.user.enums.RoleName;
|
import SuMoC.backend.user.enums.RoleName;
|
||||||
import SuMoC.backend.user.mapper.UserMapper;
|
import SuMoC.backend.user.mapper.UserMapper;
|
||||||
@@ -13,19 +12,14 @@ import SuMoC.backend.user.models.User;
|
|||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.mail.MailException;
|
|
||||||
import org.springframework.security.authentication.AuthenticationManager;
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.AuthenticationException;
|
import org.springframework.security.core.AuthenticationException;
|
||||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.security.SecureRandom;
|
|
||||||
import java.time.LocalDateTime;
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@Transactional
|
@Transactional
|
||||||
@@ -41,33 +35,21 @@ public class AuthenticationService {
|
|||||||
|
|
||||||
private UserMapper userMapper;
|
private UserMapper userMapper;
|
||||||
|
|
||||||
private PasswordResetTokenRepository passwordResetTokenRepository;
|
|
||||||
private EmailService emailService;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public AuthenticationService(UserRepository userRepository, PasswordEncoder passwordEncoder,
|
public AuthenticationService(UserRepository userRepository, PasswordEncoder passwordEncoder,
|
||||||
AuthenticationManager authenticationManager, TokenService tokenService,
|
AuthenticationManager authenticationManager, TokenService tokenService,
|
||||||
UserMapper userMapper, PasswordResetTokenRepository passwordResetTokenRepository, EmailService emailService) {
|
UserMapper userMapper) {
|
||||||
this.userRepository = userRepository;
|
this.userRepository = userRepository;
|
||||||
this.passwordEncoder = passwordEncoder;
|
this.passwordEncoder = passwordEncoder;
|
||||||
this.authenticationManager = authenticationManager;
|
this.authenticationManager = authenticationManager;
|
||||||
this.tokenService = tokenService;
|
this.tokenService = tokenService;
|
||||||
this.userMapper = userMapper;
|
this.userMapper = userMapper;
|
||||||
this.passwordResetTokenRepository = passwordResetTokenRepository;
|
|
||||||
this.emailService = emailService;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean isPasswordFormatCorrect(String password) {
|
|
||||||
//insert other check ups for passwords
|
|
||||||
if(password.length() < 8) return false;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public RegistrationResponseDTO registerUser(UserRegistrationDTO registrationDTO) {
|
public RegistrationResponseDTO registerUser(UserRegistrationDTO registrationDTO) {
|
||||||
try {
|
try {
|
||||||
// check if mail is already in use
|
// check if mail is already in use
|
||||||
if (userRepository.existsByEmail(registrationDTO.getEmail().toLowerCase())) {
|
if (userRepository.existsByEmail(registrationDTO.getEmail())) {
|
||||||
return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_EXISTS);
|
return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_EXISTS);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -78,18 +60,15 @@ public class AuthenticationService {
|
|||||||
|
|
||||||
// Validate Email
|
// Validate Email
|
||||||
String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
|
String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
|
||||||
if (!registrationDTO.getEmail().toLowerCase().matches(emailRegex)) {
|
if (!registrationDTO.getEmail().matches(emailRegex)) {
|
||||||
return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_INVALID);
|
return new RegistrationResponseDTO(null, null, RegistrationStatus.EMAIL_INVALID);
|
||||||
}
|
}
|
||||||
|
|
||||||
//validate Password
|
|
||||||
if(!isPasswordFormatCorrect(registrationDTO.getPassword())) return new RegistrationResponseDTO(null, null, RegistrationStatus.PASSWORD_INVALID);
|
|
||||||
|
|
||||||
// encode password
|
// encode password
|
||||||
String encodedPassword = passwordEncoder.encode(registrationDTO.getPassword());
|
String encodedPassword = passwordEncoder.encode(registrationDTO.getPassword());
|
||||||
|
|
||||||
// create and save user
|
// create and save user
|
||||||
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail().toLowerCase(), encodedPassword);
|
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail(), encodedPassword);
|
||||||
|
|
||||||
// Sicherheitshalber nochmal explizit setzen
|
// Sicherheitshalber nochmal explizit setzen
|
||||||
if (user.getRoles() == null || user.getRoles().isEmpty()) {
|
if (user.getRoles() == null || user.getRoles().isEmpty()) {
|
||||||
@@ -99,7 +78,7 @@ public class AuthenticationService {
|
|||||||
|
|
||||||
userRepository.save(user);
|
userRepository.save(user);
|
||||||
// We generate the login dto to get the token right after registration
|
// We generate the login dto to get the token right after registration
|
||||||
LoginResponseDTO loginResponseDTO = login(new UserAuthenticationPairDTO(registrationDTO.getEmail().toLowerCase(), registrationDTO.getPassword()));
|
LoginResponseDTO loginResponseDTO = login(new UserAuthenticationPairDTO(registrationDTO.getEmail(), registrationDTO.getPassword()));
|
||||||
// But now we return RegistrationResponseDTO for better status handling
|
// But now we return RegistrationResponseDTO for better status handling
|
||||||
return new RegistrationResponseDTO(loginResponseDTO.getUserDTO(), loginResponseDTO.getJwt(), RegistrationStatus.SUCCESS);
|
return new RegistrationResponseDTO(loginResponseDTO.getUserDTO(), loginResponseDTO.getJwt(), RegistrationStatus.SUCCESS);
|
||||||
|
|
||||||
@@ -117,10 +96,10 @@ public class AuthenticationService {
|
|||||||
try {
|
try {
|
||||||
|
|
||||||
Authentication auth = authenticationManager.authenticate(
|
Authentication auth = authenticationManager.authenticate(
|
||||||
new UsernamePasswordAuthenticationToken(authPairDTO.getEmail().toLowerCase(), authPairDTO.getPassword())
|
new UsernamePasswordAuthenticationToken(authPairDTO.getEmail(), authPairDTO.getPassword())
|
||||||
);
|
);
|
||||||
|
|
||||||
User user = userRepository.findByEmail(authPairDTO.getEmail().toLowerCase())
|
User user = userRepository.findByEmail(authPairDTO.getEmail())
|
||||||
.orElseThrow(() -> new RuntimeException("User not found"));
|
.orElseThrow(() -> new RuntimeException("User not found"));
|
||||||
|
|
||||||
UserDTO userDTO = userMapper.toUserDTO(user);
|
UserDTO userDTO = userMapper.toUserDTO(user);
|
||||||
@@ -135,60 +114,4 @@ public class AuthenticationService {
|
|||||||
return new LoginResponseDTO(null, "");
|
return new LoginResponseDTO(null, "");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @param email the account for which a OTP shall be created to reset the password
|
|
||||||
*
|
|
||||||
* NOTE: OTP Code gets hashed by passwordEncoder
|
|
||||||
*/
|
|
||||||
@Transactional
|
|
||||||
public void generateNewPasswordResetTokenForUser(String email) throws UsernameNotFoundException, MailException{
|
|
||||||
if (!userRepository.existsByEmail(email)) throw new UsernameNotFoundException("Es existiert kein Account mit dieser Email") ;
|
|
||||||
|
|
||||||
Optional<PasswordResetToken> token = passwordResetTokenRepository.findByEmail(email);
|
|
||||||
token.ifPresent(passwordResetToken -> {
|
|
||||||
System.out.println("Found token for this account...Deleting token...");
|
|
||||||
passwordResetTokenRepository.delete(passwordResetToken);
|
|
||||||
});
|
|
||||||
|
|
||||||
String otp = generate_six_digit_OTP();
|
|
||||||
passwordResetTokenRepository.save(new PasswordResetToken(email, passwordEncoder.encode(otp))); //encoded otp
|
|
||||||
emailService.sendPasswordResetEmail(email, otp);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public void resetPassword(PasswordResetDTO passwordResetDTO) throws InvalidTokenException, UsernameNotFoundException {
|
|
||||||
|
|
||||||
PasswordResetToken token = passwordResetTokenRepository.findByEmail(passwordResetDTO.getEmail())
|
|
||||||
.orElseThrow(() -> new InvalidTokenException("Token nicht gefunden"));
|
|
||||||
|
|
||||||
if (LocalDateTime.now().isAfter(token.getExpiryDate())) {
|
|
||||||
throw new InvalidTokenException("Code ist abgelaufen");
|
|
||||||
}
|
|
||||||
|
|
||||||
//use .matches() so compare raw otp to (salted!) encoded otp
|
|
||||||
if(!passwordEncoder.matches(passwordResetDTO.getOtpCode(),token.getOtpCode())){
|
|
||||||
throw new InvalidTokenException("Code ist ungültig");
|
|
||||||
}
|
|
||||||
|
|
||||||
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.getNewPassword()));
|
|
||||||
userRepository.save(user);
|
|
||||||
passwordResetTokenRepository.delete(token);
|
|
||||||
}
|
|
||||||
|
|
||||||
private String generate_six_digit_OTP(){
|
|
||||||
SecureRandom random = new SecureRandom();
|
|
||||||
// Generiert eine Zahl von 0 bis 999.999
|
|
||||||
int code = random.nextInt(1000000);
|
|
||||||
// Formatiert die Zahl auf 6 Stellen und füllt links mit 0 auf
|
|
||||||
return String.format("%06d", code);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -8,15 +8,13 @@ import jakarta.transaction.Transactional;
|
|||||||
import org.springframework.boot.CommandLineRunner;
|
import org.springframework.boot.CommandLineRunner;
|
||||||
import org.springframework.context.annotation.Profile;
|
import org.springframework.context.annotation.Profile;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.core.io.ClassPathResource;
|
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Profile("dev")
|
@Profile("dev")
|
||||||
@Order(3)
|
@Order(4)
|
||||||
public class DevChallengeSeeder implements CommandLineRunner {
|
public class DevChallengeSeeder implements CommandLineRunner {
|
||||||
|
|
||||||
private final ChallengeService challengeService;
|
private final ChallengeService challengeService;
|
||||||
@@ -33,7 +31,6 @@ public class DevChallengeSeeder implements CommandLineRunner {
|
|||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public void run(String... args) {
|
public void run(String... args) {
|
||||||
final String dummyImageBase64 = loadBase64FromClasspath("images/ChallengeDummy.png");
|
|
||||||
List<Seed> seeds = generateSeeds();
|
List<Seed> seeds = generateSeeds();
|
||||||
|
|
||||||
for (Seed seed : seeds) {
|
for (Seed seed : seeds) {
|
||||||
@@ -41,20 +38,20 @@ public class DevChallengeSeeder implements CommandLineRunner {
|
|||||||
.map(ChallengeMapper::toDTO)
|
.map(ChallengeMapper::toDTO)
|
||||||
.ifPresentOrElse(
|
.ifPresentOrElse(
|
||||||
existingChallenge -> {
|
existingChallenge -> {
|
||||||
|
// Update existing challenge
|
||||||
existingChallenge.setName(seed.name());
|
existingChallenge.setName(seed.name());
|
||||||
existingChallenge.setDescription(seed.description());
|
existingChallenge.setDescription(seed.description());
|
||||||
existingChallenge.setCriteria(seed.criteria());
|
existingChallenge.setCriteria(seed.criteria());
|
||||||
existingChallenge.setReward(seed.reward());
|
existingChallenge.setReward(seed.reward());
|
||||||
existingChallenge.setBase64image(dummyImageBase64);
|
|
||||||
challengeService.modifyChallenge(existingChallenge);
|
challengeService.modifyChallenge(existingChallenge);
|
||||||
},
|
},
|
||||||
() -> {
|
() -> {
|
||||||
|
// Create new challenge
|
||||||
ChallengeDTO newChallenge = new ChallengeDTO();
|
ChallengeDTO newChallenge = new ChallengeDTO();
|
||||||
newChallenge.setName(seed.name());
|
newChallenge.setName(seed.name());
|
||||||
newChallenge.setDescription(seed.description());
|
newChallenge.setDescription(seed.description());
|
||||||
newChallenge.setCriteria(seed.criteria());
|
newChallenge.setCriteria(seed.criteria());
|
||||||
newChallenge.setReward(seed.reward());
|
newChallenge.setReward(seed.reward());
|
||||||
newChallenge.setBase64image(dummyImageBase64);
|
|
||||||
challengeService.createChallenge(newChallenge);
|
challengeService.createChallenge(newChallenge);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -63,15 +60,6 @@ public class DevChallengeSeeder implements CommandLineRunner {
|
|||||||
challengeService.weeklyChallengeScheduler();
|
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 record Seed(String name, String description, Map<String, Integer> criteria, Integer reward) {}
|
||||||
|
|
||||||
private static Seed seed(
|
private static Seed seed(
|
||||||
@@ -89,84 +77,84 @@ public class DevChallengeSeeder implements CommandLineRunner {
|
|||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"Feierabendrunde",
|
"Feierabendrunde",
|
||||||
"Lege diese Woche 10 km mit dem Fahrrad zurück",
|
"Lege diese Woche 10 km mit dem Fahrrad zurück",
|
||||||
new HashMap<>(Map.of("KM_CYCLED", 10)),
|
Map.of("KM_CYCLED", 10),
|
||||||
80
|
80
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"Fahrrad-Fokus",
|
"Fahrrad-Fokus",
|
||||||
"Lege diese Woche 25 km mit dem Fahrrad zurück",
|
"Lege diese Woche 25 km mit dem Fahrrad zurück",
|
||||||
new HashMap<>(Map.of("KM_CYCLED", 25)),
|
Map.of("KM_CYCLED", 25),
|
||||||
150
|
150
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"Rad-Marathon",
|
"Rad-Marathon",
|
||||||
"Lege diese Woche 60 km mit dem Fahrrad zurück",
|
"Lege diese Woche 60 km mit dem Fahrrad zurück",
|
||||||
new HashMap<>(Map.of("KM_CYCLED", 60)),
|
Map.of("KM_CYCLED", 60),
|
||||||
320
|
320
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"ÖPNV-Snack",
|
"ÖPNV-Snack",
|
||||||
"Fahre diese Woche 10 km mit öffentlichen Verkehrsmitteln",
|
"Fahre diese Woche 10 km mit öffentlichen Verkehrsmitteln",
|
||||||
new HashMap<>(Map.of("KM_PUBLIC_TRANSPORT", 10)),
|
Map.of("KM_PUBLIC_TRANSPORT", 10),
|
||||||
80
|
80
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"ÖPNV-Woche",
|
"ÖPNV-Woche",
|
||||||
"Fahre diese Woche 20 km mit öffentlichen Verkehrsmitteln",
|
"Fahre diese Woche 20 km mit öffentlichen Verkehrsmitteln",
|
||||||
new HashMap<>(Map.of("KM_PUBLIC_TRANSPORT", 20)),
|
Map.of("KM_PUBLIC_TRANSPORT", 20),
|
||||||
150
|
150
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"ÖPNV-Poweruser",
|
"ÖPNV-Poweruser",
|
||||||
"Fahre diese Woche 50 km mit öffentlichen Verkehrsmitteln",
|
"Fahre diese Woche 50 km mit öffentlichen Verkehrsmitteln",
|
||||||
new HashMap<>(Map.of("KM_PUBLIC_TRANSPORT", 50)),
|
Map.of("KM_PUBLIC_TRANSPORT", 50),
|
||||||
300
|
300
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"Spaziergänger",
|
"Spaziergänger",
|
||||||
"Gehe diese Woche 5 km zu Fuß",
|
"Gehe diese Woche 5 km zu Fuß",
|
||||||
new HashMap<>(Map.of("KM_WALKED", 5)),
|
Map.of("KM_WALKED", 5),
|
||||||
60
|
60
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"Stadtläufer",
|
"Stadtläufer",
|
||||||
"Gehe diese Woche 15 km zu Fuß",
|
"Gehe diese Woche 15 km zu Fuß",
|
||||||
new HashMap<>(Map.of("KM_WALKED", 15)),
|
Map.of("KM_WALKED", 15),
|
||||||
140
|
140
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"Weitwanderer",
|
"Weitwanderer",
|
||||||
"Gehe diese Woche 30 km zu Fuß",
|
"Gehe diese Woche 30 km zu Fuß",
|
||||||
new HashMap<>(Map.of("KM_WALKED", 30)),
|
Map.of("KM_WALKED", 30),
|
||||||
280
|
280
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"XP-Booster",
|
"XP-Booster",
|
||||||
"Sammle diese Woche 250 XP",
|
"Sammle diese Woche 250 XP",
|
||||||
new HashMap<>(Map.of("XP", 250)),
|
Map.of("XP", 250),
|
||||||
200
|
200
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"XP-Grinder",
|
"XP-Grinder",
|
||||||
"Sammle diese Woche 500 XP",
|
"Sammle diese Woche 500 XP",
|
||||||
new HashMap<>(Map.of("XP", 500)),
|
Map.of("XP", 500),
|
||||||
350
|
350
|
||||||
));
|
));
|
||||||
|
|
||||||
seeds.add(seed(
|
seeds.add(seed(
|
||||||
"XP-Overkill",
|
"XP-Overkill",
|
||||||
"Sammle diese Woche 1000 XP",
|
"Sammle diese Woche 1000 XP",
|
||||||
new HashMap<>(Map.of("XP", 1000)),
|
Map.of("XP", 1000),
|
||||||
600
|
600
|
||||||
));
|
));
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
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);
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package SuMoC.backend.seed.user;
|
package SuMoC.backend.seed.user;
|
||||||
|
|
||||||
import SuMoC.backend.dev.DevProperties;
|
import SuMoC.backend.dev.DevProperties;
|
||||||
import SuMoC.backend.gamification.Timeframe;
|
|
||||||
import SuMoC.backend.notification.enums.NotificationProvider;
|
import SuMoC.backend.notification.enums.NotificationProvider;
|
||||||
import SuMoC.backend.notification.services.NotificationTokenService;
|
import SuMoC.backend.notification.services.NotificationTokenService;
|
||||||
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||||
@@ -13,10 +12,6 @@ import org.springframework.boot.CommandLineRunner;
|
|||||||
import org.springframework.context.annotation.Profile;
|
import org.springframework.context.annotation.Profile;
|
||||||
import org.springframework.core.annotation.Order;
|
import org.springframework.core.annotation.Order;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Profile("dev")
|
@Profile("dev")
|
||||||
@@ -40,53 +35,7 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
|
||||||
public void run(String... args) throws Exception {
|
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++;
|
|
||||||
}
|
|
||||||
for (var user : defaultTestUsers) {
|
|
||||||
addDummyStats(user);
|
|
||||||
positionIndex++;
|
|
||||||
}
|
|
||||||
//List<User> nTestUsers = seedNtestUsers(10);
|
|
||||||
// Now you can do more stuff with the created users if needed
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Useful for stress testing with a larger number of users. Seeds the specified number of users dummy users.
|
|
||||||
*
|
|
||||||
* @param numberOfUsers
|
|
||||||
* @return List of created User objects
|
|
||||||
*/
|
|
||||||
private List<User> seedNtestUsers(int numberOfUsers) {
|
|
||||||
List<User> createdUsers = new ArrayList<>();
|
|
||||||
for (int i = 1; i <= numberOfUsers; i++) {
|
|
||||||
UserRegistrationDTO userDto = UserRegistrationDTO.builder()
|
|
||||||
.email("testuser" + i + "@email.com")
|
|
||||||
.publicName("Test User " + i)
|
|
||||||
.privateName("Test User " + i)
|
|
||||||
.password("password" + i)
|
|
||||||
.build();
|
|
||||||
authenticationService.registerUser(userDto);
|
|
||||||
User user = userRepository.findByEmail("testuser" + i + "@email.com").orElseThrow();
|
|
||||||
notificationTokenService.registerDeviceToken(
|
|
||||||
user,
|
|
||||||
NotificationProvider.FIREBASE,
|
|
||||||
devProperties.getFcmKey()
|
|
||||||
);
|
|
||||||
createdUsers.add(user);
|
|
||||||
}
|
|
||||||
return createdUsers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<User> seedDefaultTestUsers() {
|
|
||||||
List<User> createdUsers = new ArrayList<>();
|
|
||||||
UserRegistrationDTO user1dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user1dto = UserRegistrationDTO.builder()
|
||||||
.email("user1@email.com")
|
.email("user1@email.com")
|
||||||
.publicName("Nutzer 1 Public")
|
.publicName("Nutzer 1 Public")
|
||||||
@@ -100,7 +49,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user1);
|
|
||||||
UserRegistrationDTO user2dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user2dto = UserRegistrationDTO.builder()
|
||||||
.email("user2@email.com")
|
.email("user2@email.com")
|
||||||
.publicName("Nutzer 2 Public")
|
.publicName("Nutzer 2 Public")
|
||||||
@@ -114,12 +62,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user2);
|
|
||||||
return createdUsers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<User> seedPgMembers() {
|
|
||||||
List<User> createdUsers = new ArrayList<>();
|
|
||||||
UserRegistrationDTO user3dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user3dto = UserRegistrationDTO.builder()
|
||||||
.email("david@test.com")
|
.email("david@test.com")
|
||||||
.publicName("David N. Public")
|
.publicName("David N. Public")
|
||||||
@@ -133,7 +75,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user3);
|
|
||||||
UserRegistrationDTO user4dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user4dto = UserRegistrationDTO.builder()
|
||||||
.email("davidm@test.com")
|
.email("davidm@test.com")
|
||||||
.publicName("David M Public")
|
.publicName("David M Public")
|
||||||
@@ -147,7 +88,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user4);
|
|
||||||
UserRegistrationDTO user5dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user5dto = UserRegistrationDTO.builder()
|
||||||
.email("freddie@test.com")
|
.email("freddie@test.com")
|
||||||
.publicName("Freddie Public")
|
.publicName("Freddie Public")
|
||||||
@@ -161,7 +101,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user5);
|
|
||||||
UserRegistrationDTO user6dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user6dto = UserRegistrationDTO.builder()
|
||||||
.email("elias@test.com")
|
.email("elias@test.com")
|
||||||
.publicName("Elias Public")
|
.publicName("Elias Public")
|
||||||
@@ -175,7 +114,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user6);
|
|
||||||
UserRegistrationDTO user7dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user7dto = UserRegistrationDTO.builder()
|
||||||
.email("ibrahim@test.com")
|
.email("ibrahim@test.com")
|
||||||
.publicName("Ibrahim Public")
|
.publicName("Ibrahim Public")
|
||||||
@@ -189,7 +127,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user7);
|
|
||||||
UserRegistrationDTO user8dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user8dto = UserRegistrationDTO.builder()
|
||||||
.email("lukas@test.com")
|
.email("lukas@test.com")
|
||||||
.publicName("Lukas Public")
|
.publicName("Lukas Public")
|
||||||
@@ -203,7 +140,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user8);
|
|
||||||
UserRegistrationDTO user9dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user9dto = UserRegistrationDTO.builder()
|
||||||
.email("dennis@test.com")
|
.email("dennis@test.com")
|
||||||
.publicName("Dennis Public")
|
.publicName("Dennis Public")
|
||||||
@@ -217,7 +153,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user9);
|
|
||||||
UserRegistrationDTO user10dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user10dto = UserRegistrationDTO.builder()
|
||||||
.email("daniel@test.com")
|
.email("daniel@test.com")
|
||||||
.publicName("Daniel Public")
|
.publicName("Daniel Public")
|
||||||
@@ -231,7 +166,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user10);
|
|
||||||
UserRegistrationDTO user11dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user11dto = UserRegistrationDTO.builder()
|
||||||
.email("markus@test.com")
|
.email("markus@test.com")
|
||||||
.publicName("Markus Public")
|
.publicName("Markus Public")
|
||||||
@@ -245,7 +179,6 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user11);
|
|
||||||
UserRegistrationDTO user12dto = UserRegistrationDTO.builder()
|
UserRegistrationDTO user12dto = UserRegistrationDTO.builder()
|
||||||
.email("piet@test.com")
|
.email("piet@test.com")
|
||||||
.publicName("Piet Public")
|
.publicName("Piet Public")
|
||||||
@@ -259,36 +192,5 @@ public class DevUserSeeder implements CommandLineRunner {
|
|||||||
NotificationProvider.FIREBASE,
|
NotificationProvider.FIREBASE,
|
||||||
devProperties.getFcmKey()
|
devProperties.getFcmKey()
|
||||||
);
|
);
|
||||||
createdUsers.add(user12);
|
|
||||||
return createdUsers;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void addDummyStats(User user) {
|
|
||||||
user.getStats().addToStat(
|
|
||||||
Timeframe.WEEKLY,
|
|
||||||
"XP",
|
|
||||||
0
|
|
||||||
);
|
|
||||||
user.getStats().addToStat(
|
|
||||||
Timeframe.WEEKLY,
|
|
||||||
"CO2_SAVED",
|
|
||||||
0
|
|
||||||
);
|
|
||||||
user.getStats().addToStat(
|
|
||||||
Timeframe.WEEKLY,
|
|
||||||
"KM_CYCLED",
|
|
||||||
0
|
|
||||||
);
|
|
||||||
user.getStats().addToStat(
|
|
||||||
Timeframe.WEEKLY,
|
|
||||||
"KM_WALKED",
|
|
||||||
0
|
|
||||||
);
|
|
||||||
user.getStats().addToStat(
|
|
||||||
Timeframe.WEEKLY,
|
|
||||||
"KM_PUBLIC_TRANSPORT",
|
|
||||||
0
|
|
||||||
);
|
|
||||||
userRepository.save(user);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,11 +14,4 @@ public class RegularTripSuggestionProperties {
|
|||||||
* We keep it relatively short since regular trips have a time window.
|
* We keep it relatively short since regular trips have a time window.
|
||||||
*/
|
*/
|
||||||
private Integer notifyBeforeMinutes = 15;
|
private Integer notifyBeforeMinutes = 15;
|
||||||
|
|
||||||
/**
|
|
||||||
* Number of parallel threads to use for processing users concurrently when checking
|
|
||||||
* for regular trip alternatives. Higher values increase throughput but consume more
|
|
||||||
* resources (database connections, API rate limits, memory).
|
|
||||||
*/
|
|
||||||
private Integer parallelism = 10;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,44 +0,0 @@
|
|||||||
package SuMoC.backend.suggestion.dtos;
|
|
||||||
|
|
||||||
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
|
|
||||||
import SuMoC.backend.routing.dtos.RouteDTO;
|
|
||||||
import lombok.Getter;
|
|
||||||
|
|
||||||
import java.time.LocalTime;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This DTO extends RouteDTO and implements Notifieable to be used as the data body for notifications about route suggestions.
|
|
||||||
* This allows us to use the saveAll method in NotificationSchedulerService for better performance when scheduling multiple notifications at once.
|
|
||||||
*/
|
|
||||||
public class RouteDTOtoBeNotified extends RouteDTO implements NotifieableWithTime {
|
|
||||||
private Long userId;
|
|
||||||
@Getter
|
|
||||||
private LocalTime earliestTimeOfDayToSend;
|
|
||||||
|
|
||||||
public RouteDTOtoBeNotified(RouteDTO routeDTO, Long userId, LocalTime earliestTimeOfDayToSend) {
|
|
||||||
super(
|
|
||||||
routeDTO.getStartAddress(),
|
|
||||||
routeDTO.getFirstStopName(),
|
|
||||||
routeDTO.getStartLat(),
|
|
||||||
routeDTO.getStartLon(),
|
|
||||||
routeDTO.getEndAddress(),
|
|
||||||
routeDTO.getLastStopName(),
|
|
||||||
routeDTO.getEndLat(),
|
|
||||||
routeDTO.getEndLon(),
|
|
||||||
routeDTO.getStartDateTime(),
|
|
||||||
routeDTO.getEndDateTime(),
|
|
||||||
routeDTO.getSteps(),
|
|
||||||
routeDTO.getCo2Savings(),
|
|
||||||
routeDTO.getTimeDifferenceSeconds(),
|
|
||||||
routeDTO.getCo2Emissions()
|
|
||||||
);
|
|
||||||
this.userId = userId;
|
|
||||||
this.earliestTimeOfDayToSend = earliestTimeOfDayToSend;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Long getUserId() {
|
|
||||||
return this.userId;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
package SuMoC.backend.suggestion.services;
|
package SuMoC.backend.suggestion.services;
|
||||||
|
|
||||||
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
|
||||||
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
|
||||||
import SuMoC.backend.carrousel.service.CarrouselService;
|
import SuMoC.backend.carrousel.service.CarrouselService;
|
||||||
import SuMoC.backend.h3.H3Service;
|
import SuMoC.backend.h3.H3Service;
|
||||||
import SuMoC.backend.notification.enums.NotificationType;
|
import SuMoC.backend.notification.enums.NotificationType;
|
||||||
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
|
|
||||||
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||||
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||||
import SuMoC.backend.regulartrip.services.RegularTripDetectionService;
|
import SuMoC.backend.regulartrip.services.RegularTripDetectionService;
|
||||||
@@ -14,31 +11,21 @@ import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
|||||||
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
||||||
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||||
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
|
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
|
||||||
import SuMoC.backend.suggestion.dtos.RouteDTOtoBeNotified;
|
|
||||||
import com.uber.h3core.util.LatLng;
|
import com.uber.h3core.util.LatLng;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.springframework.beans.factory.annotation.Qualifier;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.time.DayOfWeek;
|
import java.time.DayOfWeek;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.LocalDateTime;
|
import java.time.LocalDateTime;
|
||||||
import java.time.LocalTime;
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.concurrent.CompletableFuture;
|
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
|
||||||
import java.util.concurrent.Executor;
|
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class RegularTripSuggestionService {
|
public class RegularTripSuggestionService {
|
||||||
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(RegularTripSuggestionService.class);
|
|
||||||
|
|
||||||
private final AlternativeRoutingService alternativeRoutingService;
|
private final AlternativeRoutingService alternativeRoutingService;
|
||||||
|
|
||||||
private final RoutingPreferencesService routingPreferencesService;
|
private final RoutingPreferencesService routingPreferencesService;
|
||||||
@@ -53,11 +40,6 @@ public class RegularTripSuggestionService {
|
|||||||
|
|
||||||
private final CarrouselService carrouselService;
|
private final CarrouselService carrouselService;
|
||||||
|
|
||||||
private final CarrouselCandidateRepository carrouselCandidateRepository;
|
|
||||||
|
|
||||||
@Qualifier("regularTripSuggestionExecutor")
|
|
||||||
private final Executor executor;
|
|
||||||
|
|
||||||
public void detectAndNotifyRegularTripsForTodaysDayOfWeek() {
|
public void detectAndNotifyRegularTripsForTodaysDayOfWeek() {
|
||||||
// detect
|
// detect
|
||||||
DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
|
DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
|
||||||
@@ -68,73 +50,40 @@ public class RegularTripSuggestionService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void checkAlternativesAndNotify(HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser) {
|
public void checkAlternativesAndNotify(HashMap<Long, List<DetectedRegularTripDTO>> detectedRegularTripsByUser) {
|
||||||
logger.info("Processing {} users for regular trip alternatives in parallel", detectedRegularTripsByUser.size());
|
|
||||||
|
|
||||||
// Use thread-safe collections for parallel processing
|
|
||||||
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist = new ConcurrentLinkedQueue<>();
|
|
||||||
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify = new ConcurrentLinkedQueue<>();
|
|
||||||
|
|
||||||
// Create a CompletableFuture for each user to process in parallel
|
|
||||||
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
|
||||||
|
|
||||||
for (Long userId : detectedRegularTripsByUser.keySet()) {
|
for (Long userId : detectedRegularTripsByUser.keySet()) {
|
||||||
var detectedRegularTrips = detectedRegularTripsByUser.get(userId);
|
var detectedRegularTrips = detectedRegularTripsByUser.get(userId);
|
||||||
|
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
|
||||||
|
|
||||||
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
|
// For each detected regular trip, determine alternatives and notify the user if applicable
|
||||||
try {
|
for (var detectedRegularTrip : detectedRegularTrips) {
|
||||||
processUserTrips(userId, detectedRegularTrips, candidatesToPersist, alternativesToNotify);
|
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
|
||||||
} catch (Exception e) {
|
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
|
||||||
logger.error("Error processing regular trips for user {}: {}", userId, e.getMessage(), e);
|
|
||||||
|
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
|
||||||
|
// if present, schedule notification
|
||||||
|
if (bestAlternative != null) {
|
||||||
|
// save the alternative in the carrousel candidates so that it can be shown in the carrousel as well
|
||||||
|
carrouselService.addRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative));
|
||||||
|
|
||||||
|
notificationSchedulerService.schedule(
|
||||||
|
userId,
|
||||||
|
bestAlternative,
|
||||||
|
NotificationType.REGULAR_TRIP_ALTERNATIVE,
|
||||||
|
detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes())
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}, executor);
|
|
||||||
|
|
||||||
futures.add(future);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for all user processing tasks to complete
|
|
||||||
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
|
|
||||||
allFutures.join();
|
|
||||||
|
|
||||||
logger.info("Parallel processing completed. Persisting {} carrousel candidates and scheduling {} notifications",
|
|
||||||
candidatesToPersist.size(), alternativesToNotify.size());
|
|
||||||
|
|
||||||
// Batch save all results
|
|
||||||
carrouselCandidateRepository.saveAll(candidatesToPersist);
|
|
||||||
notificationSchedulerService.scheduleAll(new ArrayList<>(alternativesToNotify), NotificationType.REGULAR_TRIP_ALTERNATIVE);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Process all detected regular trips for a single user.
|
|
||||||
* This method is designed to be called in parallel for multiple users.
|
|
||||||
*/
|
|
||||||
private void processUserTrips(Long userId, List<DetectedRegularTripDTO> detectedRegularTrips,
|
|
||||||
ConcurrentLinkedQueue<CarrouselCandidate> candidatesToPersist,
|
|
||||||
ConcurrentLinkedQueue<NotifieableWithTime> alternativesToNotify) {
|
|
||||||
RoutingPreferencesDTO preferencesDTO = routingPreferencesService.getUserRoutingPreferences(userId);
|
|
||||||
|
|
||||||
// For each detected regular trip, determine alternatives and notify the user if applicable
|
|
||||||
for (var detectedRegularTrip : detectedRegularTrips) {
|
|
||||||
var alternativeRequest = createAlternativeRequest(detectedRegularTrip);
|
|
||||||
alternativeRequest.setRoutingPreferencesDTO(preferencesDTO);
|
|
||||||
|
|
||||||
var bestAlternative = alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(alternativeRequest);
|
|
||||||
// if present, schedule notification
|
|
||||||
if (bestAlternative != null) {
|
|
||||||
// save the alternative in the carrousel candidates so that it can be shown in the carrousel as well
|
|
||||||
candidatesToPersist.addAll(carrouselService.getRegularTripCandidates(userId, detectedRegularTrip, List.of(bestAlternative)));
|
|
||||||
|
|
||||||
LocalTime earliestTimeToSend = detectedRegularTrip.getDepartureWindowStart().minusMinutes(properties.getNotifyBeforeMinutes());
|
|
||||||
alternativesToNotify.add(new RouteDTOtoBeNotified(bestAlternative, userId, earliestTimeToSend));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) {
|
private RoutingAlternativeRequestDTO createAlternativeRequest(DetectedRegularTripDTO trip) {
|
||||||
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
|
LatLng origin = h3Service.cellToLatLng(trip.getStartH3Center());
|
||||||
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
|
LatLng destination = h3Service.cellToLatLng(trip.getEndH3Center());
|
||||||
// we plan the trip to arrive at the average arrival time of the regular trip
|
// we plan the trip to arrive at the average arrival time of the regular trip
|
||||||
Instant arrivalTime = trip.getAverageArrivalTime();
|
Instant arrivalTime = LocalDateTime.now()
|
||||||
|
.with(trip.getAverageArrivalTime())
|
||||||
|
.atZone(ZoneId.systemDefault())
|
||||||
|
.toInstant();
|
||||||
Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L);
|
Instant departureTime = arrivalTime.minusSeconds(trip.getAverageDurationMinutes() * 60L);
|
||||||
|
|
||||||
return RoutingAlternativeRequestDTO.builder()
|
return RoutingAlternativeRequestDTO.builder()
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package SuMoC.backend.trend;
|
|||||||
|
|
||||||
import SuMoC.backend.trend.models.WeeklyMobilityStats;
|
import SuMoC.backend.trend.models.WeeklyMobilityStats;
|
||||||
import SuMoC.backend.trend.models.WeeklyMobilityStatsId;
|
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.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.Query;
|
import org.springframework.data.jpa.repository.Query;
|
||||||
import org.springframework.data.repository.query.Param;
|
import org.springframework.data.repository.query.Param;
|
||||||
@@ -14,6 +13,4 @@ public interface WeeklyMobilityStatsRepository extends JpaRepository<WeeklyMobil
|
|||||||
@Query("SELECT wms FROM WeeklyMobilityStats wms JOIN FETCH wms.user WHERE wms.year = :year AND wms.weekNumber = :weekNumber")
|
@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);
|
List<WeeklyMobilityStats> findAllByYearAndWeekNumberWithUser(@Param("year") Integer year, @Param("weekNumber") Integer weekNumber);
|
||||||
|
|
||||||
void deleteAllByUser(User user);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,12 +6,14 @@ import SuMoC.backend.trip.dtos.NewTripDTO;
|
|||||||
import SuMoC.backend.trip.dtos.TripDTO;
|
import SuMoC.backend.trip.dtos.TripDTO;
|
||||||
import SuMoC.backend.trip.models.Trip;
|
import SuMoC.backend.trip.models.Trip;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import SuMoC.backend.user.service.CurrentUserService;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import jakarta.validation.Valid;
|
import jakarta.validation.Valid;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -23,14 +25,20 @@ public class TripController {
|
|||||||
|
|
||||||
private final TripService tripService;
|
private final TripService tripService;
|
||||||
|
|
||||||
private final CurrentUserService currentUser;
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
private final AdHocSuggestionService adHocSuggestionService;
|
private final AdHocSuggestionService adHocSuggestionService;
|
||||||
|
|
||||||
|
// TODO extend security context with user id to avoid unnecessary db query
|
||||||
|
private User getAuthenticatedUser() {
|
||||||
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
return userRepository.findByEmail(authentication.getName()).orElseThrow(() -> new RuntimeException("User not found"));
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "User uploads a new trip from the App.")
|
@Operation(summary = "User uploads a new trip from the App.")
|
||||||
@PostMapping("/uploadTrip")
|
@PostMapping("/uploadTrip")
|
||||||
public ResponseEntity<Long> uploadTrip(@Valid @RequestBody NewTripDTO newTripDTO) {
|
public ResponseEntity<Long> uploadTrip(@Valid @RequestBody NewTripDTO newTripDTO) {
|
||||||
User user = currentUser.get();
|
User user = getAuthenticatedUser();
|
||||||
Trip savedTrip = tripService.addTrip(user, newTripDTO);
|
Trip savedTrip = tripService.addTrip(user, newTripDTO);
|
||||||
|
|
||||||
// let the ad hoc service suggest an alternative more ecofriendly route if appropriate
|
// let the ad hoc service suggest an alternative more ecofriendly route if appropriate
|
||||||
@@ -42,7 +50,7 @@ public class TripController {
|
|||||||
@Operation(summary = "Retrieve all trips of the authenticated user.")
|
@Operation(summary = "Retrieve all trips of the authenticated user.")
|
||||||
@GetMapping("/getAllUserTrips")
|
@GetMapping("/getAllUserTrips")
|
||||||
public ResponseEntity<List<TripDTO>> getAllUserTrips() {
|
public ResponseEntity<List<TripDTO>> getAllUserTrips() {
|
||||||
User user = currentUser.get();
|
User user = getAuthenticatedUser();
|
||||||
|
|
||||||
List<TripDTO> userTrips = tripService.getAllTripsOfUser(user);
|
List<TripDTO> userTrips = tripService.getAllTripsOfUser(user);
|
||||||
return ResponseEntity.ok(userTrips);
|
return ResponseEntity.ok(userTrips);
|
||||||
@@ -51,7 +59,7 @@ public class TripController {
|
|||||||
@Operation(summary = "Validate a trip for the authenticated user.")
|
@Operation(summary = "Validate a trip for the authenticated user.")
|
||||||
@PutMapping("/validateTrip/{tripId}")
|
@PutMapping("/validateTrip/{tripId}")
|
||||||
public ResponseEntity<Void> validateTrip(@PathVariable Long tripId) {
|
public ResponseEntity<Void> validateTrip(@PathVariable Long tripId) {
|
||||||
User user = currentUser.get();
|
User user = getAuthenticatedUser();
|
||||||
|
|
||||||
tripService.validateTrip(user, tripId);
|
tripService.validateTrip(user, tripId);
|
||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
@@ -60,28 +68,10 @@ public class TripController {
|
|||||||
@Operation(summary = "Invalidate a trip for the authenticated user.")
|
@Operation(summary = "Invalidate a trip for the authenticated user.")
|
||||||
@PutMapping("/invalidateTrip/{tripId}")
|
@PutMapping("/invalidateTrip/{tripId}")
|
||||||
public ResponseEntity<Void> invalidateTrip(@PathVariable Long tripId) {
|
public ResponseEntity<Void> invalidateTrip(@PathVariable Long tripId) {
|
||||||
User user = currentUser.get();
|
User user = getAuthenticatedUser();
|
||||||
|
|
||||||
tripService.invalidateTrip(user, tripId);
|
tripService.invalidateTrip(user, tripId);
|
||||||
return ResponseEntity.ok().build();
|
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,8 +17,6 @@ public interface TripRepository extends JpaRepository<Trip, Long> {
|
|||||||
|
|
||||||
Optional<List<Trip>> findAllByUser(User user);
|
Optional<List<Trip>> findAllByUser(User user);
|
||||||
|
|
||||||
void deleteAllByUser(User user);
|
|
||||||
|
|
||||||
@Query("SELECT trip FROM Trip trip " +
|
@Query("SELECT trip FROM Trip trip " +
|
||||||
"JOIN FETCH trip.user " +
|
"JOIN FETCH trip.user " +
|
||||||
"JOIN FETCH trip.tripSegments " +
|
"JOIN FETCH trip.tripSegments " +
|
||||||
|
|||||||
@@ -7,9 +7,7 @@ import SuMoC.backend.trip.models.Trip;
|
|||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -28,20 +26,18 @@ public class TripService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void invalidateTrip(User user, Long tripId) {
|
public void invalidateTrip(User user, Long tripId) {
|
||||||
Trip trip = tripRepository.findById(tripId)
|
Trip trip = tripRepository.findById(tripId).orElseThrow();
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
|
||||||
if (!trip.getUser().equals(user)) {
|
if (!trip.getUser().equals(user)) {
|
||||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
throw new RuntimeException("Trip does not belong to user");
|
||||||
}
|
}
|
||||||
trip.setInvalidated(true);
|
trip.setInvalidated(true);
|
||||||
tripRepository.save(trip);
|
tripRepository.save(trip);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void validateTrip(User user, Long tripId) {
|
public void validateTrip(User user, Long tripId) {
|
||||||
Trip trip = tripRepository.findById(tripId)
|
Trip trip = tripRepository.findById(tripId).orElseThrow();
|
||||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Trip not found"));
|
|
||||||
if (!trip.getUser().equals(user)) {
|
if (!trip.getUser().equals(user)) {
|
||||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Trip does not belong to user");
|
throw new RuntimeException("Trip does not belong to user");
|
||||||
}
|
}
|
||||||
trip.setInvalidated(false);
|
trip.setInvalidated(false);
|
||||||
tripRepository.save(trip);
|
tripRepository.save(trip);
|
||||||
@@ -59,17 +55,4 @@ public class TripService {
|
|||||||
List<Trip> trips = tripRepository.findAllByUser(user).orElseThrow();
|
List<Trip> trips = tripRepository.findAllByUser(user).orElseThrow();
|
||||||
return tripMapper.toTripDTOs(trips);
|
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ package SuMoC.backend.trip.models;
|
|||||||
|
|
||||||
import SuMoC.backend.trip.Modality;
|
import SuMoC.backend.trip.Modality;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
|
||||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.AllArgsConstructor;
|
import lombok.AllArgsConstructor;
|
||||||
@@ -29,7 +27,6 @@ public class Trip {
|
|||||||
|
|
||||||
@ManyToOne
|
@ManyToOne
|
||||||
@JoinColumn(name = "user_id", nullable = false)
|
@JoinColumn(name = "user_id", nullable = false)
|
||||||
@JsonBackReference("user-trips")
|
|
||||||
private User user;
|
private User user;
|
||||||
|
|
||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
@@ -83,6 +80,5 @@ public class Trip {
|
|||||||
private Modality mainModality;
|
private Modality mainModality;
|
||||||
|
|
||||||
@OneToMany(mappedBy = "trip", cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToMany(mappedBy = "trip", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
@JsonManagedReference("trip-segments")
|
|
||||||
private Set<TripSegment> tripSegments = new HashSet<>();
|
private Set<TripSegment> tripSegments = new HashSet<>();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ package SuMoC.backend.trip.models;
|
|||||||
|
|
||||||
|
|
||||||
import SuMoC.backend.trip.Modality;
|
import SuMoC.backend.trip.Modality;
|
||||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
@@ -20,7 +19,6 @@ public class TripSegment {
|
|||||||
|
|
||||||
@ManyToOne
|
@ManyToOne
|
||||||
@JoinColumn(name = "trip_id", nullable = false)
|
@JoinColumn(name = "trip_id", nullable = false)
|
||||||
@JsonBackReference("trip-segments")
|
|
||||||
private Trip trip;
|
private Trip trip;
|
||||||
|
|
||||||
@Enumerated(EnumType.STRING)
|
@Enumerated(EnumType.STRING)
|
||||||
|
|||||||
@@ -73,7 +73,9 @@ public class FriendshipController {
|
|||||||
@PostMapping("/request/by-friendcode/{friendCode}")
|
@PostMapping("/request/by-friendcode/{friendCode}")
|
||||||
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
|
public ResponseEntity<Void> requestFriendshipByFriendcode(@PathVariable String friendCode) {
|
||||||
User user = currentUserService.get();
|
User user = currentUserService.get();
|
||||||
friendshipService.requestFriendshipByFriendcode(user, friendCode);
|
User requestedFriend = userRepository.findByFriendCode(friendCode).orElseThrow();
|
||||||
|
checkSelfAction(user.getId(), requestedFriend.getId());
|
||||||
|
friendshipService.requestFriendship(user, requestedFriend.getId());
|
||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,7 @@ package SuMoC.backend.user.controller;
|
|||||||
|
|
||||||
import SuMoC.backend.images.ImageRequestDTO;
|
import SuMoC.backend.images.ImageRequestDTO;
|
||||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||||
import SuMoC.backend.user.dtos.AddStatRequestDTO;
|
import SuMoC.backend.user.dtos.*;
|
||||||
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.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.service.UserService;
|
import SuMoC.backend.user.service.UserService;
|
||||||
import SuMoC.backend.user.stats.StatsList;
|
import SuMoC.backend.user.stats.StatsList;
|
||||||
@@ -26,7 +23,6 @@ import org.springframework.http.MediaType;
|
|||||||
import org.springframework.http.ResponseEntity;
|
import org.springframework.http.ResponseEntity;
|
||||||
import org.springframework.validation.annotation.Validated;
|
import org.springframework.validation.annotation.Validated;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
import java.util.concurrent.TimeUnit;
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
@Validated
|
@Validated
|
||||||
@@ -105,7 +101,7 @@ public class UserController {
|
|||||||
})
|
})
|
||||||
@PutMapping("/setPrivateName/{id}")
|
@PutMapping("/setPrivateName/{id}")
|
||||||
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
public ResponseEntity<Void> setPrivateName(@PathVariable @NotNull Long id,
|
||||||
@RequestParam @NotBlank String newPrivateName) {
|
@RequestParam @NotBlank String newPrivateName) {
|
||||||
this.userService.setPrivateName(id, newPrivateName);
|
this.userService.setPrivateName(id, newPrivateName);
|
||||||
return ResponseEntity.ok().build();
|
return ResponseEntity.ok().build();
|
||||||
}
|
}
|
||||||
@@ -123,7 +119,7 @@ public class UserController {
|
|||||||
})
|
})
|
||||||
@PutMapping("/setPassword/{id}")
|
@PutMapping("/setPassword/{id}")
|
||||||
public ResponseEntity<LoginResponseDTO> setPassword(@PathVariable @NotNull Long 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);
|
return new ResponseEntity<>(this.userService.setPassword(id, newPassword), HttpStatus.OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,7 +138,7 @@ public class UserController {
|
|||||||
})
|
})
|
||||||
@PutMapping("/setEmail/{id}")
|
@PutMapping("/setEmail/{id}")
|
||||||
public ResponseEntity<LoginResponseDTO> setEmail(@PathVariable @NotNull Long 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);
|
return new ResponseEntity<>(this.userService.setEmail(id, newEmail), HttpStatus.OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +191,7 @@ public class UserController {
|
|||||||
description = "Returns all stats of a user")
|
description = "Returns all stats of a user")
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(responseCode = "200", description = "Stats were found",
|
@ApiResponse(responseCode = "200", description = "Stats were found",
|
||||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = StatsList.class))),
|
content = @Content(mediaType = "application/json")),
|
||||||
@ApiResponse(responseCode = "403", description = "Not authorized",
|
@ApiResponse(responseCode = "403", description = "Not authorized",
|
||||||
content = @Content(mediaType = "application/json"))
|
content = @Content(mediaType = "application/json"))
|
||||||
})
|
})
|
||||||
@@ -228,24 +224,25 @@ public class UserController {
|
|||||||
@Operation(summary = "Get the profile Picture of the user.", description = "A user can get their displayed profile picture.")
|
@Operation(summary = "Get the profile Picture of the user.", description = "A user can get their displayed profile picture.")
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(responseCode = "200", description = "Profile picture successfully retrieved",
|
@ApiResponse(responseCode = "200", description = "Profile picture successfully retrieved",
|
||||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = ImageRequestDTO.class))),
|
content = @Content(mediaType = "application/json")),
|
||||||
@ApiResponse(responseCode = "304", description = "Profile picture not modified since last request"),
|
@ApiResponse(responseCode = "304", description = "Profile picture not modified since last request"),
|
||||||
@ApiResponse(responseCode = "403", description = "Only authorized persons may see the profiles picture"),
|
@ApiResponse(responseCode = "403", description = "Only authorized persons may see the profiles picture"),
|
||||||
@ApiResponse(responseCode = "404", description = "The user does not exist")
|
@ApiResponse(responseCode = "404", description = "The user does not exist")
|
||||||
})
|
})
|
||||||
@GetMapping(value = "/getProfilePicture/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
|
@GetMapping("/getProfilePicture/{id}")
|
||||||
public ResponseEntity<ImageRequestDTO> getProfilePicture(@PathVariable @NotNull Long id) {
|
public ResponseEntity<ImageRequestDTO> getProfilePicture(@PathVariable @NotNull Long id) {
|
||||||
ImageRequestDTO imageData = userService.getProfilePicture(id);
|
ImageRequestDTO imageData = userService.getProfilePicture(id);
|
||||||
|
|
||||||
return ResponseEntity.ok()
|
return ResponseEntity.ok()
|
||||||
.contentType(MediaType.APPLICATION_JSON)
|
.contentType(MediaType.IMAGE_JPEG)
|
||||||
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
|
.cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS))
|
||||||
.body(imageData);
|
.body(imageData);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "Get the users own xp", description = "A user can get their own xp.")
|
@Operation(summary = "Get the users own xp", description = "A user can get their own xp.")
|
||||||
@ApiResponses(value = {
|
@ApiResponses(value = {
|
||||||
@ApiResponse(responseCode = "200", description = "XP successfully retrieved",
|
@ApiResponse(responseCode = "200", description = "XP successfully retrieved",
|
||||||
content = @Content(mediaType = "application/json", schema = @Schema(implementation = Long.class))),
|
content = @Content(mediaType = "application/json")),
|
||||||
@ApiResponse(responseCode = "403", description = "Not authorized",
|
@ApiResponse(responseCode = "403", description = "Not authorized",
|
||||||
content = @Content(mediaType = "application/json")),
|
content = @Content(mediaType = "application/json")),
|
||||||
@ApiResponse(responseCode = "404", description = "The user does not exist",
|
@ApiResponse(responseCode = "404", description = "The user does not exist",
|
||||||
@@ -256,17 +253,4 @@ public class UserController {
|
|||||||
Long xp = userService.getTotalXP();
|
Long xp = userService.getTotalXP();
|
||||||
return ResponseEntity.ok().body(xp);
|
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,16 +15,7 @@ public interface UserMapper {
|
|||||||
User toUser(UserDTO userDTO);
|
User toUser(UserDTO userDTO);
|
||||||
|
|
||||||
static MaximalUserDTO toMaximalUserDTO(User user) {
|
static MaximalUserDTO toMaximalUserDTO(User user) {
|
||||||
// Force-initialize lazy collections while session is still open
|
MaximalUserDTO maximalUserDTO = new MaximalUserDTO(
|
||||||
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.getId(),
|
||||||
user.getPublicName(),
|
user.getPublicName(),
|
||||||
user.getPrivateName(),
|
user.getPrivateName(),
|
||||||
@@ -33,8 +24,9 @@ public interface UserMapper {
|
|||||||
user.getTrips(),
|
user.getTrips(),
|
||||||
user.getFriendships(),
|
user.getFriendships(),
|
||||||
user.getFriendCode(),
|
user.getFriendCode(),
|
||||||
base64Image
|
ImageBase64Util.encode(user.getProfileImage().getImageData())
|
||||||
);
|
);
|
||||||
|
return maximalUserDTO;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package SuMoC.backend.user.models;
|
package SuMoC.backend.user.models;
|
||||||
|
|
||||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||||
import com.fasterxml.jackson.annotation.JsonBackReference;
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.*;
|
import lombok.*;
|
||||||
|
|
||||||
@@ -27,12 +26,10 @@ public class Friendship {
|
|||||||
|
|
||||||
@ManyToOne
|
@ManyToOne
|
||||||
@JoinColumn(name = "user_id", nullable = false)
|
@JoinColumn(name = "user_id", nullable = false)
|
||||||
@JsonBackReference("user-friendships")
|
|
||||||
private User user;
|
private User user;
|
||||||
|
|
||||||
@ManyToOne
|
@ManyToOne
|
||||||
@JoinColumn(name = "friend_id", nullable = false)
|
@JoinColumn(name = "friend_id", nullable = false)
|
||||||
@JsonBackReference("friend-friendships")
|
|
||||||
private User friend;
|
private User friend;
|
||||||
|
|
||||||
@Enumerated(EnumType.STRING)
|
@Enumerated(EnumType.STRING)
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import SuMoC.backend.trip.models.Trip;
|
|||||||
import SuMoC.backend.user.enums.RoleName;
|
import SuMoC.backend.user.enums.RoleName;
|
||||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.stats.StatsList;
|
import SuMoC.backend.user.stats.StatsList;
|
||||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
@@ -44,11 +43,10 @@ public class User {
|
|||||||
@Column(nullable = false)
|
@Column(nullable = false)
|
||||||
private VisibilityPrivacy visibilityPrivacy;
|
private VisibilityPrivacy visibilityPrivacy;
|
||||||
|
|
||||||
@Column(nullable = false, unique = true, length = 24)
|
@Column(nullable = false, unique = true, length = 36)
|
||||||
private String friendCode;
|
private String friendCode;
|
||||||
|
|
||||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
@JsonManagedReference("user-trips")
|
|
||||||
private Set<Trip> trips = new HashSet<>();
|
private Set<Trip> trips = new HashSet<>();
|
||||||
|
|
||||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
@@ -61,25 +59,24 @@ public class User {
|
|||||||
@Column(name = "role")
|
@Column(name = "role")
|
||||||
private Set<RoleName> roles = new HashSet<>();
|
private Set<RoleName> roles = new HashSet<>();
|
||||||
|
|
||||||
@OneToOne(cascade = CascadeType.REMOVE, orphanRemoval = true)
|
@OneToOne
|
||||||
@JoinColumn(name = "id", referencedColumnName = "user_id")
|
@JoinColumn(name = "id", referencedColumnName = "user_id")
|
||||||
private NotificationToken notificationToken;
|
private NotificationToken notificationToken;
|
||||||
|
|
||||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
|
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
|
||||||
private Set<UserBadge> badges = new HashSet<>();
|
private Set<UserBadge> badges = new HashSet<>();
|
||||||
|
|
||||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
private StatsList statsList;
|
private StatsList statsList;
|
||||||
|
|
||||||
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
@JoinColumn(name = "routing_preferences_id", unique = true)
|
@JoinColumn(name = "routing_preferences_id", unique = true)
|
||||||
private RoutingPreferences routingPreferences;
|
private RoutingPreferences routingPreferences;
|
||||||
|
|
||||||
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
@OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||||
private ProfileImageEntity profileImage;
|
private ProfileImageEntity profileImage;
|
||||||
|
|
||||||
public 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) {
|
// 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.id = id;
|
||||||
@@ -100,19 +97,18 @@ public class User {
|
|||||||
this.email = email;
|
this.email = email;
|
||||||
this.password = password;
|
this.password = password;
|
||||||
this.visibilityPrivacy = VisibilityPrivacy.NONE;
|
this.visibilityPrivacy = VisibilityPrivacy.NONE;
|
||||||
this.friendCode = generateFriendCode(); // generate unique friend code
|
this.friendCode = java.util.UUID.randomUUID().toString(); // generate unique friend code
|
||||||
this.routingPreferences = RoutingPreferences.getDefaultPreferences(); // Init with default routing preferences
|
this.routingPreferences = RoutingPreferences.getDefaultPreferences(); // Init with default routing preferences
|
||||||
this.roles.add(RoleName.USER);
|
this.roles.add(RoleName.USER);
|
||||||
this.statsList = new StatsList(this);
|
this.statsList = new StatsList(this);
|
||||||
|
|
||||||
this.profileImage = new ProfileImageEntity();
|
this.profileImage = new ProfileImageEntity();
|
||||||
this.profileImage.setUser(this);
|
this.profileImage.setUser(this); }
|
||||||
}
|
|
||||||
|
|
||||||
@PrePersist
|
@PrePersist
|
||||||
private void ensureFriendCode() {
|
private void ensureFriendCode() {
|
||||||
if (this.friendCode == null) {
|
if (this.friendCode == null) {
|
||||||
this.friendCode = generateFriendCode();
|
this.friendCode = UUID.randomUUID().toString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,25 +227,4 @@ public class User {
|
|||||||
public void setProfileImage(ProfileImageEntity profileImage) {
|
public void setProfileImage(ProfileImageEntity profileImage) {
|
||||||
this.profileImage = profileImage;
|
this.profileImage = profileImage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Friendcode generator
|
|
||||||
private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
|
||||||
private static final java.security.SecureRandom RANDOM = new java.security.SecureRandom();
|
|
||||||
|
|
||||||
private String generateFriendCode() {
|
|
||||||
StringBuilder sb = new StringBuilder();
|
|
||||||
|
|
||||||
for (int group = 0; group < 5; group++) {
|
|
||||||
for (int i = 0; i < 4; i++) {
|
|
||||||
sb.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
|
|
||||||
}
|
|
||||||
if (group < 4) {
|
|
||||||
sb.append("-");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return sb.toString();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,16 +2,13 @@ package SuMoC.backend.user.service;
|
|||||||
|
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import jakarta.transaction.Transactional;
|
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
|
||||||
import org.springframework.security.core.Authentication;
|
import org.springframework.security.core.Authentication;
|
||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
@Component
|
@Component
|
||||||
@Transactional
|
|
||||||
public class CurrentUserService {
|
public class CurrentUserService {
|
||||||
|
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
@@ -35,9 +32,9 @@ public class CurrentUserService {
|
|||||||
"Der Nutzer existiert nicht"));
|
"Der Nutzer existiert nicht"));
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isLoggedInUser() {
|
public boolean isAuthenticated() {
|
||||||
|
// TODO request with auth no auth really result in not authenticated?
|
||||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||||
return auth != null && auth.isAuthenticated() && !(auth instanceof AnonymousAuthenticationToken);
|
return auth != null && auth.isAuthenticated();
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -11,9 +11,7 @@ import SuMoC.backend.user.repository.UserRepository;
|
|||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import org.jspecify.annotations.NonNull;
|
import org.jspecify.annotations.NonNull;
|
||||||
import org.springframework.http.HttpStatus;
|
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -346,17 +344,6 @@ public class FriendshipService {
|
|||||||
return friends;
|
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(
|
public record NameWithFriendship(
|
||||||
Long id,
|
Long id,
|
||||||
String name,
|
String name,
|
||||||
|
|||||||
@@ -1,18 +1,16 @@
|
|||||||
package SuMoC.backend.user.service;
|
package SuMoC.backend.user.service;
|
||||||
|
|
||||||
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
|
||||||
import SuMoC.backend.gamification.Timeframe;
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
import SuMoC.backend.images.ImageBase64Util;
|
import SuMoC.backend.images.ImageBase64Util;
|
||||||
import SuMoC.backend.images.ImageRequestDTO;
|
import SuMoC.backend.images.ImageRequestDTO;
|
||||||
import SuMoC.backend.notification.repositories.NotificationRepository;
|
|
||||||
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||||
import SuMoC.backend.security.services.TokenService;
|
import SuMoC.backend.security.services.TokenService;
|
||||||
import SuMoC.backend.trend.WeeklyMobilityStatsRepository;
|
import SuMoC.backend.trip.TripMapper;
|
||||||
import SuMoC.backend.trip.TripService;
|
|
||||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||||
import SuMoC.backend.user.enums.RoleName;
|
import SuMoC.backend.user.enums.RoleName;
|
||||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
|
import SuMoC.backend.user.mapper.FriendshipMapper;
|
||||||
import SuMoC.backend.user.mapper.UserMapper;
|
import SuMoC.backend.user.mapper.UserMapper;
|
||||||
import SuMoC.backend.user.models.ProfileImageEntity;
|
import SuMoC.backend.user.models.ProfileImageEntity;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
@@ -24,6 +22,7 @@ import org.springframework.security.core.Authentication;
|
|||||||
import org.springframework.security.core.context.SecurityContextHolder;
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.multipart.MultipartFile;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
|
||||||
@@ -34,18 +33,15 @@ public class UserService {
|
|||||||
private final CurrentUserService currentUser;
|
private final CurrentUserService currentUser;
|
||||||
private final UserRepository userRepository;
|
private final UserRepository userRepository;
|
||||||
private final PasswordEncoder passwordEncoder;
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
private final UserMapper userMapper;
|
private final UserMapper userMapper;
|
||||||
private final TokenService tokenService;
|
|
||||||
;
|
private final TokenService tokenService;;
|
||||||
private final PrivacyService privacyService;
|
private final PrivacyService privacyService;
|
||||||
private final FriendshipService friendshipService;
|
private final FriendshipService friendshipService;
|
||||||
private final TripService tripService;
|
|
||||||
private final NotificationRepository notificationRepository;
|
|
||||||
private final WeeklyMobilityStatsRepository weeklyMobilityStatsRepository;
|
|
||||||
private final CarrouselCandidateRepository carrouselCandidateRepository;
|
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService, TripService tripService, NotificationRepository notificationRepository, WeeklyMobilityStatsRepository weeklyMobilityStatsRepository, CarrouselCandidateRepository carrouselCandidateRepository) {
|
public UserService(CurrentUserService currentUser, UserRepository userRepository, PasswordEncoder passwordEncoder, UserMapper userMapper, TokenService tokenService, PrivacyService privacyService, FriendshipService friendshipService) {
|
||||||
this.currentUser = currentUser;
|
this.currentUser = currentUser;
|
||||||
this.userRepository = userRepository;
|
this.userRepository = userRepository;
|
||||||
this.passwordEncoder = passwordEncoder;
|
this.passwordEncoder = passwordEncoder;
|
||||||
@@ -53,10 +49,6 @@ public class UserService {
|
|||||||
this.tokenService = tokenService;
|
this.tokenService = tokenService;
|
||||||
this.privacyService = privacyService;
|
this.privacyService = privacyService;
|
||||||
this.friendshipService = friendshipService;
|
this.friendshipService = friendshipService;
|
||||||
this.tripService = tripService;
|
|
||||||
this.notificationRepository = notificationRepository;
|
|
||||||
this.weeklyMobilityStatsRepository = weeklyMobilityStatsRepository;
|
|
||||||
this.carrouselCandidateRepository = carrouselCandidateRepository;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -68,7 +60,7 @@ public class UserService {
|
|||||||
));
|
));
|
||||||
// TODO: Check tomorrow if this makes sense
|
// TODO: Check tomorrow if this makes sense
|
||||||
// TODO: Can Users see the minimalDTO if they are blocked?
|
// 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(
|
throw new ResponseStatusException(
|
||||||
HttpStatus.FORBIDDEN,
|
HttpStatus.FORBIDDEN,
|
||||||
"Der Nutzer hat dich blockiert."
|
"Der Nutzer hat dich blockiert."
|
||||||
@@ -105,13 +97,7 @@ public class UserService {
|
|||||||
userRepository.deleteById(id);
|
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) {
|
public LoginResponseDTO setPassword(Long id, String newPassword) {
|
||||||
@@ -155,8 +141,6 @@ public class UserService {
|
|||||||
User sender = currentUser.get();
|
User sender = currentUser.get();
|
||||||
System.out.println(sender.getId());
|
System.out.println(sender.getId());
|
||||||
|
|
||||||
newEmail = newEmail.toLowerCase();
|
|
||||||
|
|
||||||
if (!sender.getId().equals(id)) {
|
if (!sender.getId().equals(id)) {
|
||||||
throw new ResponseStatusException(
|
throw new ResponseStatusException(
|
||||||
HttpStatus.FORBIDDEN,
|
HttpStatus.FORBIDDEN,
|
||||||
@@ -192,7 +176,7 @@ public class UserService {
|
|||||||
));
|
));
|
||||||
System.out.println("################# Returning LoginResponse ################");
|
System.out.println("################# Returning LoginResponse ################");
|
||||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedUser),
|
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) {
|
public void setVisibilityPrivacy(VisibilityPrivacy visibilityPrivacy) {
|
||||||
@@ -210,15 +194,15 @@ public class UserService {
|
|||||||
}
|
}
|
||||||
User userToChange = userRepository.findById(id)
|
User userToChange = userRepository.findById(id)
|
||||||
.orElseThrow(() -> new ResponseStatusException(
|
.orElseThrow(() -> new ResponseStatusException(
|
||||||
HttpStatus.NOT_FOUND,
|
HttpStatus.NOT_FOUND,
|
||||||
"Der Nutzer Existitert nicht."));
|
"Der Nutzer Existitert nicht."));
|
||||||
|
|
||||||
// TODO: Add String Validator
|
// TODO: Add String Validator
|
||||||
userToChange.setPrivateName(newPrivateName);
|
userToChange.setPrivateName(newPrivateName);
|
||||||
userRepository.save(userToChange);
|
userRepository.save(userToChange);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
|
||||||
public MaximalUserDTO getSelf() {
|
public MaximalUserDTO getSelf() {
|
||||||
User sender = currentUser.get();
|
User sender = currentUser.get();
|
||||||
return UserMapper.toMaximalUserDTO(sender);
|
return UserMapper.toMaximalUserDTO(sender);
|
||||||
@@ -272,7 +256,7 @@ public class UserService {
|
|||||||
|
|
||||||
public Long getTotalXP() {
|
public Long getTotalXP() {
|
||||||
User sender = currentUser.get();
|
User sender = currentUser.get();
|
||||||
return sender.getStats().getStatValue(Timeframe.TOTAL, "XP");
|
return sender.getStats().getStatValue(Timeframe.TOTAL,"XP");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,7 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/sumoc
|
|||||||
spring.datasource.username=postgres
|
spring.datasource.username=postgres
|
||||||
spring.datasource.password=admin
|
spring.datasource.password=admin
|
||||||
spring.datasource.driver-class-name=org.postgresql.Driver
|
spring.datasource.driver-class-name=org.postgresql.Driver
|
||||||
spring.flyway.enabled=true
|
spring.jpa.hibernate.ddl-auto=create
|
||||||
spring.jpa.hibernate.ddl-auto=validate
|
|
||||||
spring.flyway.baseline-on-migrate=true
|
|
||||||
spring.flyway.baseline-version=0
|
|
||||||
spring.jpa.show-sql=true
|
spring.jpa.show-sql=true
|
||||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||||
logging.level.org.springframework.security=Trace
|
logging.level.org.springframework.security=Trace
|
||||||
@@ -14,21 +11,11 @@ springdoc.api-docs.path=/v3/api-docs
|
|||||||
springdoc.swagger-ui.path=/swagger-ui.html
|
springdoc.swagger-ui.path=/swagger-ui.html
|
||||||
spring.profiles.active=dev
|
spring.profiles.active=dev
|
||||||
spring.jackson.serialization.write-dates-as-timestamps=false
|
spring.jackson.serialization.write-dates-as-timestamps=false
|
||||||
#mail provider
|
|
||||||
spring.mail.host=smtp-relay.brevo.com
|
|
||||||
spring.mail.port=587
|
|
||||||
spring.mail.username=a2b594001@smtp-brevo.com
|
|
||||||
spring.mail.password=rWz3ZdwGT8tNY9Dx
|
|
||||||
spring.mail.properties.mail.smtp.auth=true
|
|
||||||
spring.mail.properties.mail.smtp.starttls.enable=true
|
|
||||||
# Rhythm settings for scheduled tasks
|
# Rhythm settings for scheduled tasks
|
||||||
sumoc.scheduling.run-notification-worker=*/15 * * * * *
|
sumoc.scheduling.run-notification-worker=*/15 * * * * *
|
||||||
sumoc.scheduling.notify-weekly-mobility-stats=1 30 0 * * 1
|
sumoc.scheduling.notify-weekly-mobility-stats=1 30 0 * * 1
|
||||||
sumoc.scheduling.clean-up-old-notifications=0 0 3 * * *
|
sumoc.scheduling.clean-up-old-notifications=0 0 3 * * *
|
||||||
sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * *
|
sumoc.scheduling.notify-regular-route-alternatives=0 0 4 * * *
|
||||||
# Regular trip suggestion settings
|
|
||||||
sumoc.regulartripsuggestion.parallelism=5
|
|
||||||
sumoc.regulartripsuggestion.notify-before-minutes=15
|
|
||||||
# Trend detection settings
|
# Trend detection settings
|
||||||
sumoc.trenddetection.positive-threshold=-25.0
|
sumoc.trenddetection.positive-threshold=-25.0
|
||||||
sumoc.trenddetection.negative-threshold=-25.0
|
sumoc.trenddetection.negative-threshold=-25.0
|
||||||
@@ -49,6 +36,7 @@ geocoding.carta.base-url=https://mobydex.locoslab.com/carta
|
|||||||
meteo.base-url=https://api.open-meteo.com/v1
|
meteo.base-url=https://api.open-meteo.com/v1
|
||||||
# Dev debug settings
|
# Dev debug settings
|
||||||
sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk
|
sumoc.dev.fcm-key=dmydW4a_RjKCDjcBLZ9Kl8:APA91bFjBIjw8NcjeMIsNkfPuW9jhMlK3n_LHoG5UBW0E_76nTp1yV6jkdiBIvle7Txj_mLY3W9e9gy_op6YWyxJksqZrJFgapruCdBdg9ACYDJAANGTWJk
|
||||||
|
|
||||||
# RSA key paths (file paths, not directories)
|
# RSA key paths (file paths, not directories)
|
||||||
security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem}
|
security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem}
|
||||||
security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem}
|
security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem}
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
ALTER TABLE image_entity
|
|
||||||
ALTER COLUMN image_data TYPE bytea
|
|
||||||
USING lo_get(image_data);
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 2.4 MiB |
@@ -1,8 +1,9 @@
|
|||||||
package SuMoC.backend.routing.services;
|
package SuMoC.backend.routing.services;
|
||||||
|
|
||||||
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
||||||
import SuMoC.backend.routing.dtos.*;
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
import SuMoC.backend.trip.Modality;
|
import SuMoC.backend.routing.dtos.RoutingAlternativeRequestDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
@@ -11,7 +12,6 @@ import org.mockito.Mock;
|
|||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
@@ -109,55 +109,4 @@ public class AlternativeFilterServiceTest {
|
|||||||
route.setEndDateTime(Instant.parse("2023-01-01T10:00:00Z").plusSeconds(durationSeconds));
|
route.setEndDateTime(Instant.parse("2023-01-01T10:00:00Z").plusSeconds(durationSeconds));
|
||||||
return route;
|
return route;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
|
||||||
void testFilterForInefficientTransitRoutes_FilterOutTransitWithMoreWalking() {
|
|
||||||
// Create a direct walking route (500 meters total)
|
|
||||||
RouteDTO walkingRoute = createRouteWithSteps(List.of(
|
|
||||||
new StepDTO(Modality.WALKING, 500.0)
|
|
||||||
));
|
|
||||||
|
|
||||||
// Create a transit route with more total walking distance (600 meters walking)
|
|
||||||
RouteDTO transitRoute = createRouteWithSteps(List.of(
|
|
||||||
new StepDTO(Modality.WALKING, 300.0),
|
|
||||||
new TransitStepDTO(Modality.BUS, 2000.0, "101", "City Center", "Main St", "5th Ave"),
|
|
||||||
new StepDTO(Modality.WALKING, 300.0)
|
|
||||||
));
|
|
||||||
|
|
||||||
List<RouteDTO> alternatives = List.of(walkingRoute, transitRoute);
|
|
||||||
|
|
||||||
List<RouteDTO> result = alternativeFilterService.filterForInefficientTransitRoutes(alternatives);
|
|
||||||
|
|
||||||
// Transit route should be filtered out because walking distance (600m) > direct walking route (500m)
|
|
||||||
assertEquals(1, result.size());
|
|
||||||
assertEquals(walkingRoute, result.get(0));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testFilterForInefficientTransitRoutes_KeepTransitWithLessWalking() {
|
|
||||||
// Create a direct walking route (1000 meters total)
|
|
||||||
RouteDTO walkingRoute = createRouteWithSteps(List.of(
|
|
||||||
new StepDTO(Modality.WALKING, 1000.0)
|
|
||||||
));
|
|
||||||
|
|
||||||
// Create a transit route with less total walking distance (400 meters walking)
|
|
||||||
RouteDTO transitRoute = createRouteWithSteps(List.of(
|
|
||||||
new StepDTO(Modality.WALKING, 200.0),
|
|
||||||
new TransitStepDTO(Modality.BUS, 3000.0, "102", "Downtown", "Park Ave", "Central Station"),
|
|
||||||
new StepDTO(Modality.WALKING, 200.0)
|
|
||||||
));
|
|
||||||
|
|
||||||
List<RouteDTO> alternatives = List.of(walkingRoute, transitRoute);
|
|
||||||
|
|
||||||
List<RouteDTO> result = alternativeFilterService.filterForInefficientTransitRoutes(alternatives);
|
|
||||||
|
|
||||||
// Both routes should be kept because transit walking (400m) < direct walking route (1000m)
|
|
||||||
assertEquals(2, result.size());
|
|
||||||
}
|
|
||||||
|
|
||||||
private RouteDTO createRouteWithSteps(List<StepDTO> steps) {
|
|
||||||
RouteDTO route = RouteDTO.getMockRouteDTO();
|
|
||||||
route.setSteps(new ArrayList<>(steps));
|
|
||||||
return route;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +1,32 @@
|
|||||||
package SuMoC.backend.security;
|
package SuMoC.backend.security;
|
||||||
|
|
||||||
import SuMoC.backend.notification.services.EmailService;
|
import SuMoC.backend.security.dtos.LoginResponseDTO;
|
||||||
import SuMoC.backend.security.dtos.*;
|
import SuMoC.backend.security.dtos.RegistrationResponseDTO;
|
||||||
|
import SuMoC.backend.security.dtos.UserAuthenticationPairDTO;
|
||||||
|
import SuMoC.backend.security.dtos.UserRegistrationDTO;
|
||||||
import SuMoC.backend.security.enums.RegistrationStatus;
|
import SuMoC.backend.security.enums.RegistrationStatus;
|
||||||
import SuMoC.backend.security.exceptions.InvalidTokenException;
|
|
||||||
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
|
|
||||||
import SuMoC.backend.security.services.AuthenticationService;
|
import SuMoC.backend.security.services.AuthenticationService;
|
||||||
|
|
||||||
import SuMoC.backend.user.dtos.UserDTO;
|
import SuMoC.backend.user.dtos.UserDTO;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import jakarta.persistence.EntityManager;
|
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
|
||||||
import org.mockito.ArgumentCaptor;
|
|
||||||
import org.mockito.InjectMocks;
|
|
||||||
import org.mockito.Mock;
|
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
|
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
|
||||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.mail.javamail.JavaMailSender;
|
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static SuMoC.backend.Factories.UserTestFactory.*;
|
import static SuMoC.backend.Factories.UserTestFactory.*;
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
|
||||||
import static org.mockito.Mockito.times;
|
|
||||||
import static org.mockito.Mockito.verify;
|
|
||||||
|
|
||||||
|
|
||||||
@SpringBootTest
|
@SpringBootTest
|
||||||
@ActiveProfiles("test")
|
@ActiveProfiles("test")
|
||||||
@Transactional
|
@Transactional
|
||||||
@ExtendWith(MockitoExtension.class)
|
|
||||||
public class AuthentificationServiceTest {
|
public class AuthentificationServiceTest {
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -48,114 +35,6 @@ public class AuthentificationServiceTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository userRepository;
|
private UserRepository userRepository;
|
||||||
|
|
||||||
@Autowired PasswordResetTokenRepository passwordResetTokenRepository;
|
|
||||||
|
|
||||||
@MockitoBean
|
|
||||||
private EmailService emailService;
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private EntityManager entityManager;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testPasswordResetFullFlow() {
|
|
||||||
// Registriere einen echten User
|
|
||||||
User user = validUser();
|
|
||||||
authenticationService.registerUser(getUserRegistrationDTO(user));
|
|
||||||
String email = user.getEmail();
|
|
||||||
String oldPassword = user.getPassword();
|
|
||||||
assertTrue(userRepository.findByEmail(email).isPresent());
|
|
||||||
|
|
||||||
// OTP anfordern
|
|
||||||
authenticationService.generateNewPasswordResetTokenForUser(email);
|
|
||||||
|
|
||||||
// Verifizieren, dass der EmailService aufgerufen wurde
|
|
||||||
// Captor, um den generierten Code abzufangen
|
|
||||||
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
|
|
||||||
verify(emailService, times(1)).sendPasswordResetEmail(eq(email), otpCaptor.capture());
|
|
||||||
String sentOtp = otpCaptor.getValue();
|
|
||||||
|
|
||||||
// Passwort mit dem gefangenen OTP zurücksetzen
|
|
||||||
String newPassword = "MyNewSecurePassword2026";
|
|
||||||
PasswordResetDTO resetDTO = new PasswordResetDTO(sentOtp, email, newPassword);
|
|
||||||
|
|
||||||
|
|
||||||
assertDoesNotThrow(() -> authenticationService.resetPassword(resetDTO));
|
|
||||||
|
|
||||||
// Verifizieren, dass der Login mit dem NEUEN Passwort klappt und mit ALTEM nicht klappt
|
|
||||||
LoginResponseDTO loginResponseTrue = authenticationService.login(new UserAuthenticationPairDTO(email, newPassword));
|
|
||||||
assertNotNull(loginResponseTrue.getUserDTO());
|
|
||||||
assertFalse(loginResponseTrue.getJwt().isEmpty());
|
|
||||||
|
|
||||||
LoginResponseDTO loginResponseFalse = authenticationService.login(new UserAuthenticationPairDTO(email, oldPassword));
|
|
||||||
assertNull(loginResponseFalse.getUserDTO());
|
|
||||||
assertTrue(loginResponseFalse.getJwt().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testPasswordResetWithWrongOTP() {
|
|
||||||
|
|
||||||
User user = validUser();
|
|
||||||
authenticationService.registerUser(getUserRegistrationDTO(user));
|
|
||||||
String email = user.getEmail();
|
|
||||||
String oldPassword = user.getPassword();
|
|
||||||
assertTrue(userRepository.findByEmail(email).isPresent());
|
|
||||||
|
|
||||||
|
|
||||||
authenticationService.generateNewPasswordResetTokenForUser(user.getEmail());
|
|
||||||
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
|
|
||||||
verify(emailService, times(1)).sendPasswordResetEmail(eq(email), otpCaptor.capture());
|
|
||||||
String sentOtp = otpCaptor.getValue();
|
|
||||||
|
|
||||||
String wrongOtpCode = Objects.equals(sentOtp, "000000") ? "100000" : "00000";
|
|
||||||
|
|
||||||
PasswordResetDTO wrongDto = new PasswordResetDTO(wrongOtpCode, user.getEmail(), "PWPWPWPW");
|
|
||||||
|
|
||||||
assertThrows(InvalidTokenException.class, () -> {
|
|
||||||
authenticationService.resetPassword(wrongDto);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testPasswordResetWithWrongEmail() {
|
|
||||||
// Registriere einen echten User
|
|
||||||
User user = validUser();
|
|
||||||
authenticationService.registerUser(getUserRegistrationDTO(user));
|
|
||||||
String email = user.getEmail();
|
|
||||||
assertTrue(userRepository.findByEmail(email).isPresent());
|
|
||||||
|
|
||||||
// User existiert und hat Token angefordert
|
|
||||||
authenticationService.generateNewPasswordResetTokenForUser(user.getEmail());
|
|
||||||
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
|
|
||||||
verify(emailService, times(1)).sendPasswordResetEmail(eq(email), otpCaptor.capture());
|
|
||||||
String sentOtp = otpCaptor.getValue();
|
|
||||||
|
|
||||||
PasswordResetDTO wrongDto = new PasswordResetDTO(sentOtp, "wrongEmail@test.de", "PWPWPWPW");
|
|
||||||
|
|
||||||
assertThrows(InvalidTokenException.class, () -> {
|
|
||||||
authenticationService.resetPassword(wrongDto);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testPasswordResetWithWrongPasswordFormat() {
|
|
||||||
// Registriere einen echten User
|
|
||||||
User user = validUser();
|
|
||||||
authenticationService.registerUser(getUserRegistrationDTO(user));
|
|
||||||
String email = user.getEmail();
|
|
||||||
assertTrue(userRepository.findByEmail(email).isPresent());
|
|
||||||
|
|
||||||
// User existiert und hat Token angefordert
|
|
||||||
authenticationService.generateNewPasswordResetTokenForUser(user.getEmail());
|
|
||||||
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
|
|
||||||
verify(emailService, times(1)).sendPasswordResetEmail(eq(email), otpCaptor.capture());
|
|
||||||
String sentOtp = otpCaptor.getValue();
|
|
||||||
|
|
||||||
PasswordResetDTO wrongDto = new PasswordResetDTO(sentOtp, user.getEmail(), "newPw");
|
|
||||||
|
|
||||||
assertThrows(InvalidTokenException.class, () -> {
|
|
||||||
authenticationService.resetPassword(wrongDto);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testRegistrationSuccessful() {
|
public void testRegistrationSuccessful() {
|
||||||
|
|||||||
@@ -26,9 +26,6 @@ geocoding.carta.base-url=https://www.innamoruhr.de/c2
|
|||||||
geocoding.nominatim.base-url=http://localhost:6666
|
geocoding.nominatim.base-url=http://localhost:6666
|
||||||
meteo.base-url=https://api.open-meteo.com/v1
|
meteo.base-url=https://api.open-meteo.com/v1
|
||||||
|
|
||||||
spring.mail.host=localhost
|
|
||||||
spring.mail.port=25
|
|
||||||
|
|
||||||
# RSA key paths for tests
|
# RSA key paths for tests
|
||||||
security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem}
|
security.rsa.private-key-path=${RSA_PRIVATE_KEY_PATH:${user.home}/.sumoc/keys/jwt-private.pem}
|
||||||
security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem}
|
security.rsa.public-key-path=${RSA_PUBLIC_KEY_PATH:${user.home}/.sumoc/keys/jwt-public.pem}
|
||||||
Reference in New Issue
Block a user