Restrict web-socket connections to the initiating user
This commit is contained in:
committed by
Aditya Chandel
parent
3ab52de171
commit
628a6c7bcf
@@ -21,9 +21,10 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry config) {
|
||||
config.enableSimpleBroker("/topic");
|
||||
config.setApplicationDestinationPrefixes("/app");
|
||||
public void configureMessageBroker(MessageBrokerRegistry registry) {
|
||||
registry.enableSimpleBroker("/queue", "/topic");
|
||||
registry.setApplicationDestinationPrefixes("/app");
|
||||
registry.setUserDestinationPrefix("/user");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
package com.adityachandel.booklore.model.websocket;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum Topic {
|
||||
BOOK_ADD("/topic/book-add"),
|
||||
BOOKS_REMOVE("/topic/books-remove"),
|
||||
BOOK_METADATA_UPDATE("/topic/book-metadata-update"),
|
||||
BOOK_METADATA_BATCH_UPDATE("/topic/book-metadata-batch-update"),
|
||||
BOOK_METADATA_BATCH_PROGRESS("/topic/book-metadata-batch-progress"),
|
||||
BOOKDROP_FILE("/topic/bookdrop-file"),
|
||||
TASK("/topic/task"),
|
||||
LOG("/topic/log");
|
||||
BOOK_ADD("/queue/book-add"),
|
||||
BOOKS_REMOVE("/queue/books-remove"),
|
||||
BOOK_METADATA_UPDATE("/queue/book-metadata-update"),
|
||||
BOOK_METADATA_BATCH_UPDATE("/queue/book-metadata-batch-update"),
|
||||
BOOK_METADATA_BATCH_PROGRESS("/queue/book-metadata-batch-progress"),
|
||||
BOOKDROP_FILE("/queue/bookdrop-file"),
|
||||
TASK("/queue/task"),
|
||||
LOG("/queue/log");
|
||||
|
||||
private final String path;
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package com.adityachandel.booklore.quartz;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.exception.ApiError;
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -20,6 +22,7 @@ import java.util.concurrent.LinkedBlockingQueue;
|
||||
public class JobSchedulerService {
|
||||
|
||||
private final Scheduler scheduler;
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
private final BlockingQueue<RefreshJobWrapper> jobQueue = new LinkedBlockingQueue<>();
|
||||
private final Map<String, String> runningJobs = new ConcurrentHashMap<>();
|
||||
@@ -88,10 +91,13 @@ public class JobSchedulerService {
|
||||
|
||||
private void scheduleJob(MetadataRefreshRequest request, Long userId, String jobId) {
|
||||
try {
|
||||
BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser();
|
||||
|
||||
JobDataMap jobDataMap = new JobDataMap();
|
||||
jobDataMap.put("request", request);
|
||||
jobDataMap.put("userId", userId);
|
||||
jobDataMap.put("jobId", jobId);
|
||||
jobDataMap.put("user", authenticatedUser);
|
||||
|
||||
JobDetail jobDetail = JobBuilder.newJob(RefreshMetadataJob.class)
|
||||
.withIdentity(jobId, "metadataRefreshJobGroup")
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package com.adityachandel.booklore.quartz;
|
||||
|
||||
import com.adityachandel.booklore.model.dto.BookLoreUser;
|
||||
import com.adityachandel.booklore.model.dto.request.MetadataRefreshRequest;
|
||||
import com.adityachandel.booklore.service.metadata.MetadataRefreshService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.quartz.*;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@@ -22,7 +25,12 @@ public class RefreshMetadataJob implements InterruptableJob {
|
||||
try {
|
||||
MetadataRefreshRequest request = (MetadataRefreshRequest) context.getMergedJobDataMap().get("request");
|
||||
Long userId = (Long) context.getMergedJobDataMap().get("userId");
|
||||
BookLoreUser user = (BookLoreUser) context.getMergedJobDataMap().get("user");
|
||||
String jobId = (String) context.getMergedJobDataMap().get("jobId");
|
||||
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
|
||||
log.info("Starting metadata refresh job with ID: {}", jobId);
|
||||
metadataRefreshService.refreshMetadata(request, userId, jobId);
|
||||
log.info("Completed metadata refresh job with ID: {}", jobId);
|
||||
@@ -41,6 +49,7 @@ public class RefreshMetadataJob implements InterruptableJob {
|
||||
}
|
||||
throw new JobExecutionException("Error occurred while executing metadata refresh job", e);
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
executionThread = null;
|
||||
}
|
||||
}
|
||||
|
||||
+18
-6
@@ -1,19 +1,31 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import com.adityachandel.booklore.config.security.AuthenticationService;
|
||||
import com.adityachandel.booklore.model.websocket.Topic;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@AllArgsConstructor
|
||||
public class NotificationService {
|
||||
|
||||
private final SimpMessagingTemplate messagingTemplate;
|
||||
|
||||
public NotificationService(SimpMessagingTemplate messagingTemplate) {
|
||||
this.messagingTemplate = messagingTemplate;
|
||||
}
|
||||
private final AuthenticationService authenticationService;
|
||||
|
||||
public void sendMessage(Topic topic, Object message) {
|
||||
messagingTemplate.convertAndSend(String.valueOf(topic), message);
|
||||
try {
|
||||
var user = authenticationService.getAuthenticatedUser();
|
||||
if (user == null) {
|
||||
log.warn("No authenticated user found. Message not sent: {}", topic);
|
||||
return;
|
||||
}
|
||||
String username = user.getUsername();
|
||||
messagingTemplate.convertAndSendToUser(username, topic.getPath(), message);
|
||||
} catch (Exception e) {
|
||||
log.error("Error sending message to topic {}: {}", topic, e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -26,6 +26,9 @@ import jakarta.transaction.Transactional;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.dao.InvalidDataAccessApiUsageException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@@ -173,13 +176,19 @@ public class LibraryService {
|
||||
|
||||
public void rescanLibrary(long libraryId) {
|
||||
libraryRepository.findById(libraryId).orElseThrow(() -> ApiError.LIBRARY_NOT_FOUND.createException(libraryId));
|
||||
Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
|
||||
Thread.startVirtualThread(() -> {
|
||||
try {
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(currentAuth);
|
||||
SecurityContextHolder.setContext(context);
|
||||
libraryProcessingService.rescanLibrary(libraryId);
|
||||
} catch (InvalidDataAccessApiUsageException e) {
|
||||
log.debug("InvalidDataAccessApiUsageException - Library id: {}", libraryId);
|
||||
} catch (IOException e) {
|
||||
log.error("Error while parsing library books", e);
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
log.info("Parsing task completed!");
|
||||
});
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import {Component, inject, OnInit} from '@angular/core';
|
||||
import {RxStompService} from './shared/websocket/rx-stomp.service';
|
||||
import {Message} from '@stomp/stompjs';
|
||||
import {BookService} from './book/service/book.service';
|
||||
import {NotificationEventService} from './shared/websocket/notification-event.service';
|
||||
import {parseLogNotification, parseTaskMessage, TaskMessage} from './shared/websocket/model/log-notification.model';
|
||||
import {parseLogNotification, parseTaskMessage} from './shared/websocket/model/log-notification.model';
|
||||
import {ConfirmDialog} from 'primeng/confirmdialog';
|
||||
import {Toast} from 'primeng/toast';
|
||||
import {RouterOutlet} from '@angular/router';
|
||||
@@ -11,7 +10,7 @@ import {AuthInitializationService} from './auth-initialization-service';
|
||||
import {AppConfigService} from './core/service/app-config.service';
|
||||
import {MetadataBatchProgressNotification} from './core/model/metadata-batch-progress.model';
|
||||
import {MetadataProgressService} from './core/service/metadata-progress-service';
|
||||
import {BookdropFileService, BookdropFileNotification} from './bookdrop/bookdrop-file.service';
|
||||
import {BookdropFileNotification, BookdropFileService} from './bookdrop/bookdrop-file.service';
|
||||
import {TaskEventService} from './shared/websocket/task-event.service';
|
||||
|
||||
@Component({
|
||||
@@ -34,45 +33,33 @@ export class AppComponent implements OnInit {
|
||||
private appConfigService = inject(AppConfigService);
|
||||
|
||||
ngOnInit(): void {
|
||||
|
||||
this.authInit.initialized$.subscribe(ready => {
|
||||
this.loading = !ready;
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/book-add').subscribe((message: Message) => {
|
||||
this.bookService.handleNewlyCreatedBook(JSON.parse(message.body));
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/books-remove').subscribe((message: Message) => {
|
||||
this.bookService.handleRemovedBookIds(JSON.parse(message.body));
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/book-metadata-update').subscribe((message: Message) => {
|
||||
this.bookService.handleBookUpdate(JSON.parse(message.body));
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/book-metadata-batch-update').subscribe((message: Message) => {
|
||||
const updatedBooks = JSON.parse(message.body);
|
||||
this.bookService.handleMultipleBookUpdates(updatedBooks);
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/book-metadata-batch-progress').subscribe((message: Message) => {
|
||||
const progress = JSON.parse(message.body) as MetadataBatchProgressNotification;
|
||||
this.metadataProgressService.handleIncomingProgress(progress);
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/log').subscribe((message: Message) => {
|
||||
const logNotification = parseLogNotification(message.body);
|
||||
this.rxStompService.watch('/user/queue/book-add').subscribe(msg =>
|
||||
this.bookService.handleNewlyCreatedBook(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/books-remove').subscribe(msg =>
|
||||
this.bookService.handleRemovedBookIds(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/book-metadata-update').subscribe(msg =>
|
||||
this.bookService.handleBookUpdate(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-update').subscribe(msg =>
|
||||
this.bookService.handleMultipleBookUpdates(JSON.parse(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/book-metadata-batch-progress').subscribe(msg =>
|
||||
this.metadataProgressService.handleIncomingProgress(JSON.parse(msg.body) as MetadataBatchProgressNotification)
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/log').subscribe(msg => {
|
||||
const logNotification = parseLogNotification(msg.body);
|
||||
this.notificationEventService.handleNewNotification(logNotification);
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/task').subscribe((message: Message) => {
|
||||
const taskMessage: TaskMessage = parseTaskMessage(message.body);
|
||||
this.taskEventService.handleTaskMessage(taskMessage);
|
||||
});
|
||||
|
||||
this.rxStompService.watch('/topic/bookdrop-file').subscribe((message: Message) => {
|
||||
const notification = JSON.parse(message.body) as BookdropFileNotification;
|
||||
this.rxStompService.watch('/user/queue/task').subscribe(msg =>
|
||||
this.taskEventService.handleTaskMessage(parseTaskMessage(msg.body))
|
||||
);
|
||||
this.rxStompService.watch('/user/queue/bookdrop-file').subscribe(msg => {
|
||||
const notification = JSON.parse(msg.body) as BookdropFileNotification;
|
||||
this.bookdropFileService.handleIncomingFile(notification);
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user