Make WS work with Auth

This commit is contained in:
aditya.chandel
2025-02-16 00:32:50 -07:00
parent d3627a2d3f
commit 4354a43af7
24 changed files with 243 additions and 89 deletions
@@ -1,15 +1,25 @@
package com.adityachandel.booklore.config; package com.adityachandel.booklore.config;
import com.adityachandel.booklore.config.security.WebSocketAuthInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Slf4j
@Configuration @Configuration
@EnableWebSocketMessageBroker @EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor) {
this.webSocketAuthInterceptor = webSocketAuthInterceptor;
}
@Override @Override
public void configureMessageBroker(MessageBrokerRegistry config) { public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic"); config.enableSimpleBroker("/topic");
@@ -19,6 +29,11 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override @Override
public void registerStompEndpoints(StompEndpointRegistry registry) { public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").setAllowedOrigins("*"); registry.addEndpoint("/ws").setAllowedOrigins("*");
System.out.println("WebSocket endpoint registered at /ws"); log.info("WebSocket endpoint registered at /ws");
}
@Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.interceptors(webSocketAuthInterceptor);
} }
} }
@@ -28,8 +28,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final UserRepository userRepository; private final UserRepository userRepository;
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) protected boolean shouldNotFilter(HttpServletRequest request) {
throws ServletException, IOException { return "websocket".equalsIgnoreCase(request.getHeader("Upgrade"));
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
String token = getJwtFromRequest(request); String token = getJwtFromRequest(request);
@@ -34,6 +34,7 @@ public class SecurityConfig {
.csrf(AbstractHttpConfigurer::disable) .csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/login").permitAll() .requestMatchers("/api/v1/auth/register", "/api/v1/auth/login").permitAll()
.requestMatchers("/ws/**").permitAll()
.anyRequest().authenticated() .anyRequest().authenticated()
) )
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
@@ -0,0 +1,65 @@
package com.adityachandel.booklore.config.security;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;
@AllArgsConstructor
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 99)
public class WebSocketAuthInterceptor implements ChannelInterceptor {
private final JwtUtils jwtUtils;
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) {
List<String> authHeaders = accessor.getNativeHeader("Authorization");
if (authHeaders == null || authHeaders.isEmpty()) {
log.warn("WebSocket connection rejected: No Authorization header");
throw new IllegalArgumentException("Missing Authorization header");
}
String token = authHeaders.get(0).replace("Bearer ", "");
Authentication auth = authenticateToken(token);
if (auth == null) {
log.warn("WebSocket connection rejected: Invalid token");
throw new IllegalArgumentException("Invalid Authorization token");
}
accessor.setUser(auth);
log.info("WebSocket authentication successful for user: {}", auth.getName());
}
return message;
}
private Authentication authenticateToken(String token) {
if (!jwtUtils.validateToken(token)) {
return null;
}
String username = jwtUtils.extractUsername(token);
List<SimpleGrantedAuthority> authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
return new UsernamePasswordAuthenticationToken(username, null, authorities);
}
}
@@ -4,7 +4,7 @@
(mouseout)="isHovered = false"> (mouseout)="isHovered = false">
<div class="cover-container"> <div class="cover-container">
<img <img
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)" [attr.src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn) | secure | async"
class="book-cover placeholder" class="book-cover placeholder"
alt="Cover of {{ book.metadata?.title }}" alt="Cover of {{ book.metadata?.title }}"
loading="lazy"/> loading="lazy"/>
@@ -13,14 +13,15 @@ import {MetadataFetchOptionsComponent} from '../../../../metadata/metadata-optio
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum'; import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
import {MetadataRefreshRequest} from '../../../../metadata/model/request/metadata-refresh-request.model'; import {MetadataRefreshRequest} from '../../../../metadata/model/request/metadata-refresh-request.model';
import {UrlHelperService} from '../../../../utilities/service/url-helper.service'; import {UrlHelperService} from '../../../../utilities/service/url-helper.service';
import {NgIf} from '@angular/common'; import {AsyncPipe, NgIf} from '@angular/common';
import {SecurePipe} from '../../../../secure-pipe';
@Component({ @Component({
selector: 'app-book-card', selector: 'app-book-card',
templateUrl: './book-card.component.html', templateUrl: './book-card.component.html',
styleUrls: ['./book-card.component.scss'], styleUrls: ['./book-card.component.scss'],
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf], imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, AsyncPipe, SecurePipe],
standalone: true standalone: true
}) })
export class BookCardComponent implements OnInit { export class BookCardComponent implements OnInit {
@@ -35,7 +35,7 @@
<p-tableCheckbox [value]="book"></p-tableCheckbox> <p-tableCheckbox [value]="book"></p-tableCheckbox>
</td> </td>
<td (click)="openMetadataCenter(book.id)"> <td (click)="openMetadataCenter(book.id)">
<img [src]="urlHelper.getCoverUrl(book.id, metadata.coverUpdatedOn)" alt="Book Cover" class="size-7"/> <img [attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn) | secure | async" alt="Book Cover" class="size-7"/>
</td> </td>
<td class="min-w-[15rem] max-w-[20rem] overflow-hidden truncate">{{ metadata.title }}</td> <td class="min-w-[15rem] max-w-[20rem] overflow-hidden truncate">{{ metadata.title }}</td>
<td class="min-w-[10rem] max-w-[13rem] overflow-hidden truncate">{{ getAuthorNames(metadata.authors) }}</td> <td class="min-w-[10rem] max-w-[13rem] overflow-hidden truncate">{{ getAuthorNames(metadata.authors) }}</td>
@@ -1,12 +1,13 @@
import {Component, EventEmitter, inject, Input, OnChanges, Output} from '@angular/core'; import {Component, EventEmitter, inject, Input, OnChanges, Output} from '@angular/core';
import {TableModule} from 'primeng/table'; import {TableModule} from 'primeng/table';
import {NgIf} from '@angular/common'; import {AsyncPipe, NgIf} from '@angular/common';
import {Rating} from 'primeng/rating'; import {Rating} from 'primeng/rating';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {Book} from '../../../model/book.model'; import {Book} from '../../../model/book.model';
import {SortOption} from '../../../model/sort.model'; import {SortOption} from '../../../model/sort.model';
import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service'; import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service';
import {UrlHelperService} from '../../../../utilities/service/url-helper.service'; import {UrlHelperService} from '../../../../utilities/service/url-helper.service';
import {SecurePipe} from '../../../../secure-pipe';
@Component({ @Component({
selector: 'app-book-table', selector: 'app-book-table',
@@ -16,7 +17,9 @@ import {UrlHelperService} from '../../../../utilities/service/url-helper.service
TableModule, TableModule,
NgIf, NgIf,
Rating, Rating,
FormsModule FormsModule,
SecurePipe,
AsyncPipe
], ],
styleUrl: './book-table.component.scss' styleUrl: './book-table.component.scss'
}) })
@@ -17,7 +17,7 @@
<ng-container *ngIf="books.length > 0; else noResults"> <ng-container *ngIf="books.length > 0; else noResults">
<div class="search-dropdown-item flex flex-col" *ngFor="let book of books" (click)="onBookClick(book)"> <div class="search-dropdown-item flex flex-col" *ngFor="let book of books" (click)="onBookClick(book)">
<div class="flex flex-row w-full px-2"> <div class="flex flex-row w-full px-2">
<img [src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)" alt="Book Cover" class="search-book-cover"/> <img [attr.src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn) | secure | async" alt="Book Cover" class="search-book-cover"/>
<div class="search-book-details"> <div class="search-book-details">
<div class="flex items-center"> <div class="flex items-center">
<p class="search-book-name text-lg font-medium truncate">{{ book.metadata?.title | slice:0:70 }}</p> <p class="search-book-name text-lg font-medium truncate">{{ book.metadata?.title | slice:0:70 }}</p>
@@ -6,10 +6,11 @@ import {FormsModule} from '@angular/forms';
import {InputTextModule} from 'primeng/inputtext'; import {InputTextModule} from 'primeng/inputtext';
import {BookService} from '../../service/book.service'; import {BookService} from '../../service/book.service';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {NgForOf, NgIf, SlicePipe} from '@angular/common'; import {AsyncPipe, NgForOf, NgIf, SlicePipe} from '@angular/common';
import {MetadataDialogService} from '../../../metadata/service/metadata-dialog.service'; import {MetadataDialogService} from '../../../metadata/service/metadata-dialog.service';
import {Divider} from 'primeng/divider'; import {Divider} from 'primeng/divider';
import {UrlHelperService} from '../../../utilities/service/url-helper.service'; import {UrlHelperService} from '../../../utilities/service/url-helper.service';
import {SecurePipe} from '../../../secure-pipe';
@Component({ @Component({
selector: 'app-book-searcher', selector: 'app-book-searcher',
@@ -21,7 +22,9 @@ import {UrlHelperService} from '../../../utilities/service/url-helper.service';
NgIf, NgIf,
NgForOf, NgForOf,
SlicePipe, SlicePipe,
Divider Divider,
AsyncPipe,
SecurePipe
], ],
styleUrls: ['./book-searcher.component.scss'], styleUrls: ['./book-searcher.component.scss'],
standalone: true standalone: true
@@ -1,17 +1,27 @@
import { Injectable } from '@angular/core'; import { Injectable, Injector } from '@angular/core';
import {HttpClient} from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs'; import { Observable, tap } from 'rxjs';
import { RxStompService } from '../../shared/websocket/rx-stomp.service';
import { createRxStompConfig } from '../../shared/websocket/rx-stomp.config';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class AuthService { export class AuthService {
private apiUrl = 'http://localhost:7050/api/v1/auth/login'; private apiUrl = 'http://localhost:7050/api/v1/auth/login';
private rxStompService?: RxStompService;
constructor(private http: HttpClient) {} constructor(private http: HttpClient, private injector: Injector) {}
login(credentials: { username: string; password: string }): Observable<any> { login(credentials: { username: string; password: string }): Observable<any> {
return this.http.post(this.apiUrl, credentials); return this.http.post<{ token: string }>(this.apiUrl, credentials).pipe(
tap((response) => {
if (response.token) {
this.saveToken(response.token);
this.startWebSocket();
}
})
);
} }
saveToken(token: string): void { saveToken(token: string): void {
@@ -24,5 +34,22 @@ export class AuthService {
logout(): void { logout(): void {
localStorage.removeItem('token'); localStorage.removeItem('token');
this.getRxStompService().deactivate();
}
private startWebSocket(): void {
const token = this.getToken();
if (token) {
const rxStompService = this.getRxStompService();
rxStompService.configure(createRxStompConfig(this));
rxStompService.activate();
}
}
private getRxStompService(): RxStompService {
if (!this.rxStompService) {
this.rxStompService = this.injector.get(RxStompService);
}
return this.rxStompService;
} }
} }
@@ -16,6 +16,7 @@ import {Divider} from 'primeng/divider';
import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component'; import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component';
import {LiveNotificationBoxComponent} from '../../../core/component/live-notification-box/live-notification-box.component'; import {LiveNotificationBoxComponent} from '../../../core/component/live-notification-box/live-notification-box.component';
import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component'; import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component';
import {AuthService} from '../../../core/service/auth.service';
@Component({ @Component({
selector: 'app-topbar', selector: 'app-topbar',
@@ -49,7 +50,7 @@ export class AppTopBarComponent implements OnDestroy {
@ViewChild('topbarmenu') menu!: ElementRef; @ViewChild('topbarmenu') menu!: ElementRef;
constructor(public layoutService: LayoutService, public dialogService: PrimeDialogService, constructor(public layoutService: LayoutService, public dialogService: PrimeDialogService,
private eventService: EventService, private router: Router) { private eventService: EventService, private router: Router, private authService: AuthService) {
this.eventService.eventHighlight$.subscribe(highlight => { this.eventService.eventHighlight$.subscribe(highlight => {
this.eventHighlight = highlight; this.eventHighlight = highlight;
}); });
@@ -115,7 +116,7 @@ export class AppTopBarComponent implements OnDestroy {
} }
logout() { logout() {
localStorage.removeItem('token'); this.authService.logout();
window.location.href = '/login'; window.location.href = '/login';
} }
} }
+21 -9
View File
@@ -1,13 +1,25 @@
<div class="login-container"> <div class="login-container">
<h2>Login</h2> <p-card class="login-card p-fluid">
<form (submit)="login()"> <ng-template pTemplate="title">Login</ng-template>
<label>Username</label>
<input type="text" [(ngModel)]="username" name="username" required />
<label>Password</label> <ng-template pTemplate="content">
<input type="password" [(ngModel)]="password" name="password" required /> <form #loginForm="ngForm">
<div class="p-field">
<label for="username">Username</label>
<input pInputText id="username" [(ngModel)]="username" name="username" required fluid/>
</div>
<button type="submit">Login</button> <div class="p-field">
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p> <label for="password">Password</label>
</form> <p-password id="password" [(ngModel)]="password" name="password" [feedback]="false" fluid required></p-password>
</div>
<div class="p-mt-3">
<p-button label="Login" icon="pi pi-sign-in" (click)="login()" class="p-fluid"></p-button>
</div>
<p-message *ngIf="errorMessage" severity="error" text="{{ errorMessage }}"></p-message>
</form>
</ng-template>
</p-card>
</div> </div>
+8 -16
View File
@@ -1,27 +1,19 @@
.login-container { .login-container {
@apply flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-blue-200 to-blue-500; @apply flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-orange-200 to-gray-700;
h2 { .login-card {
@apply text-2xl font-bold text-gray-700 mb-4; @apply w-96 shadow-lg rounded-xl;
} }
form { form {
@apply bg-white p-6 rounded-2xl shadow-lg w-96 flex flex-col gap-4; @apply flex flex-col gap-4;
label { .p-field {
@apply text-sm font-semibold text-gray-600; @apply flex flex-col gap-1;
} }
input { p-button {
@apply w-full p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400; @apply mt-2;
}
button {
@apply w-full bg-blue-500 text-white py-2 rounded-lg font-semibold hover:bg-blue-600 transition duration-300;
}
.error {
@apply text-red-500 text-sm font-medium mt-2;
} }
} }
} }
+13 -1
View File
@@ -3,12 +3,24 @@ import {AuthService} from '../core/service/auth.service';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {NgIf} from '@angular/common'; import {NgIf} from '@angular/common';
import {Card} from 'primeng/card';
import {Password} from 'primeng/password';
import {Button} from 'primeng/button';
import {Message} from 'primeng/message';
import {PrimeTemplate} from 'primeng/api';
import {InputText} from 'primeng/inputtext';
@Component({ @Component({
selector: 'app-login', selector: 'app-login',
imports: [ imports: [
FormsModule, FormsModule,
NgIf NgIf,
Card,
Password,
Button,
Message,
PrimeTemplate,
InputText
], ],
templateUrl: './login.component.html', templateUrl: './login.component.html',
styleUrl: './login.component.scss' styleUrl: './login.component.scss'
@@ -10,7 +10,7 @@
<div class="flex flex-col items-center gap-2 relative"> <div class="flex flex-col items-center gap-2 relative">
<img <img
[src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)" [attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn) | secure | async"
alt="Image" alt="Image"
width="250" width="250"
[ngClass]="{ 'brightness-50': isUploading }" [ngClass]="{ 'brightness-50': isUploading }"
@@ -14,6 +14,7 @@ import {FileUpload, FileUploadErrorEvent, FileUploadEvent} from 'primeng/fileupl
import {HttpResponse} from '@angular/common/http'; import {HttpResponse} from '@angular/common/http';
import {BookService} from '../../../book/service/book.service'; import {BookService} from '../../../book/service/book.service';
import {ProgressSpinner} from 'primeng/progressspinner'; import {ProgressSpinner} from 'primeng/progressspinner';
import {SecurePipe} from '../../../secure-pipe';
@Component({ @Component({
selector: 'app-metadata-editor', selector: 'app-metadata-editor',
@@ -31,7 +32,8 @@ import {ProgressSpinner} from 'primeng/progressspinner';
ReactiveFormsModule, ReactiveFormsModule,
FileUpload, FileUpload,
ProgressSpinner, ProgressSpinner,
NgClass NgClass,
SecurePipe
] ]
}) })
export class MetadataEditorComponent implements OnInit { export class MetadataEditorComponent implements OnInit {
@@ -2,7 +2,11 @@
<div class="book-metadata-container flex-shrink-0" *ngIf="metadata$ | async as metadata"> <div class="book-metadata-container flex-shrink-0" *ngIf="metadata$ | async as metadata">
<div class="flex flex-row w-full"> <div class="flex flex-row w-full">
<img [src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)" class="book-cover placeholder" alt="Cover of {{ metadata.title }}" loading="lazy" width="250"/> <img [attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn) | secure | async"
class="book-cover placeholder"
alt="Cover of {{ metadata.title }}"
loading="lazy"
width="250"/>
<div class="pl-6 flex flex-col w-full space-y-4"> <div class="pl-6 flex flex-col w-full space-y-4">
<div class="flex flex-row items-center justify-between"> <div class="flex flex-row items-center justify-between">
@@ -10,13 +10,14 @@ import {Tag} from 'primeng/tag';
import {BookMetadata} from '../../../book/model/book.model'; import {BookMetadata} from '../../../book/model/book.model';
import {Divider} from 'primeng/divider'; import {Divider} from 'primeng/divider';
import {UrlHelperService} from '../../../utilities/service/url-helper.service'; import {UrlHelperService} from '../../../utilities/service/url-helper.service';
import {SecurePipe} from '../../../secure-pipe';
@Component({ @Component({
selector: 'app-metadata-viewer', selector: 'app-metadata-viewer',
standalone: true, standalone: true,
templateUrl: './metadata-viewer.component.html', templateUrl: './metadata-viewer.component.html',
styleUrl: './metadata-viewer.component.scss', styleUrl: './metadata-viewer.component.scss',
imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider] imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SecurePipe]
}) })
export class MetadataViewerComponent { export class MetadataViewerComponent {
+19
View File
@@ -0,0 +1,19 @@
import { Pipe, PipeTransform } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Pipe({
name: 'secure',
pure: true
})
export class SecurePipe implements PipeTransform {
constructor(private http: HttpClient, private sanitizer: DomSanitizer) {}
transform(url: string): Observable<SafeUrl> {
return this.http.get(url, { responseType: 'blob' }).pipe(
map(blob => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob)))
);
}
}
@@ -1,9 +1,10 @@
import { RxStompService } from './rx-stomp.service'; import { RxStompService } from './rx-stomp.service';
import { rxStompConfig } from './rx-stomp.config'; import { createRxStompConfig } from './rx-stomp.config';
import {AuthService} from '../../core/service/auth.service';
export function rxStompServiceFactory() { export function rxStompServiceFactory(authService: AuthService) {
const rxStomp = new RxStompService(); const rxStomp = new RxStompService(authService);
rxStomp.configure(rxStompConfig); const stompConfig = createRxStompConfig(authService);
rxStomp.activate(); rxStomp.configure(stompConfig);
return rxStomp; return rxStomp;
} }
@@ -1,31 +1,18 @@
import {RxStompConfig} from '@stomp/rx-stomp'; import { RxStompConfig } from '@stomp/rx-stomp';
import {API_CONFIG} from '../../config/api-config'; import { API_CONFIG } from '../../config/api-config';
import {AuthService} from '../../core/service/auth.service';
export const rxStompConfig: RxStompConfig = { export function createRxStompConfig(authService: AuthService): RxStompConfig {
// Which server? return {
brokerURL: API_CONFIG.BROKER_URL, brokerURL: API_CONFIG.BROKER_URL,
connectHeaders: {
// Headers Authorization: `Bearer ${authService.getToken()}`,
// Typical keys: login, passcode, host },
connectHeaders: { heartbeatIncoming: 0,
login: 'guest', heartbeatOutgoing: 20000,
passcode: 'guest', reconnectDelay: 200,
}, debug: (msg: string): void => {
//console.log(new Date(), msg);
// How often to heartbeat? },
// Interval in milliseconds, set to 0 to disable };
heartbeatIncoming: 0, // Typical value 0 - disabled }
heartbeatOutgoing: 20000, // Typical value 20000 - every 20 seconds
// Wait in milliseconds before attempting auto reconnect
// Set to 0 to disable
// Typical value 500 (500 milli seconds)
reconnectDelay: 200,
// Will log diagnostics on console
// It can be quite verbose, not recommended in production
// Skip this key to stop logging to console
debug: (msg: string): void => {
//console.log(new Date(), msg);
},
};
@@ -1,13 +1,15 @@
import { Injectable } from '@angular/core'; import { Injectable } from '@angular/core';
import { RxStomp } from '@stomp/rx-stomp'; import { RxStomp } from '@stomp/rx-stomp';
import { AuthService } from '../../core/service/auth.service';
import { createRxStompConfig } from './rx-stomp.config';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root',
}) })
export class RxStompService extends RxStomp { export class RxStompService extends RxStomp {
constructor(private authService: AuthService) {
constructor() {
super(); super();
const stompConfig = createRxStompConfig(this.authService);
this.configure(stompConfig);
} }
} }
+2
View File
@@ -12,6 +12,7 @@ import { AppComponent } from './app/app.component';
import Aura from '@primeng/themes/aura'; import Aura from '@primeng/themes/aura';
import { routes } from './app/app.routes'; import { routes } from './app/app.routes';
import {AuthInterceptorService} from './app/auth-interceptor.service'; import {AuthInterceptorService} from './app/auth-interceptor.service';
import {AuthService} from './app/core/service/auth.service';
bootstrapApplication(AppComponent, { bootstrapApplication(AppComponent, {
providers: [ providers: [
@@ -23,6 +24,7 @@ bootstrapApplication(AppComponent, {
{ {
provide: RxStompService, provide: RxStompService,
useFactory: rxStompServiceFactory, useFactory: rxStompServiceFactory,
deps: [AuthService],
}, },
{ {
provide: RouteReuseStrategy, provide: RouteReuseStrategy,