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