Make WS work with Auth
This commit is contained in:
@@ -1,15 +1,25 @@
|
||||
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.messaging.simp.config.ChannelRegistration;
|
||||
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
|
||||
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableWebSocketMessageBroker
|
||||
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
|
||||
private final WebSocketAuthInterceptor webSocketAuthInterceptor;
|
||||
|
||||
public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor) {
|
||||
this.webSocketAuthInterceptor = webSocketAuthInterceptor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void configureMessageBroker(MessageBrokerRegistry config) {
|
||||
config.enableSimpleBroker("/topic");
|
||||
@@ -19,6 +29,11 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
|
||||
@Override
|
||||
public void registerStompEndpoints(StompEndpointRegistry registry) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -28,8 +28,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return "websocket".equalsIgnoreCase(request.getHeader("Upgrade"));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
|
||||
|
||||
String token = getJwtFromRequest(request);
|
||||
|
||||
|
||||
+1
@@ -34,6 +34,7 @@ public class SecurityConfig {
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/v1/auth/register", "/api/v1/auth/login").permitAll()
|
||||
.requestMatchers("/ws/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
|
||||
+65
@@ -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">
|
||||
<div class="cover-container">
|
||||
<img
|
||||
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
|
||||
[attr.src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn) | secure | async"
|
||||
class="book-cover placeholder"
|
||||
alt="Cover of {{ book.metadata?.title }}"
|
||||
loading="lazy"/>
|
||||
|
||||
@@ -13,14 +13,15 @@ import {MetadataFetchOptionsComponent} from '../../../../metadata/metadata-optio
|
||||
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
|
||||
import {MetadataRefreshRequest} from '../../../../metadata/model/request/metadata-refresh-request.model';
|
||||
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({
|
||||
selector: 'app-book-card',
|
||||
templateUrl: './book-card.component.html',
|
||||
styleUrls: ['./book-card.component.scss'],
|
||||
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf],
|
||||
imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, AsyncPipe, SecurePipe],
|
||||
standalone: true
|
||||
})
|
||||
export class BookCardComponent implements OnInit {
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@
|
||||
<p-tableCheckbox [value]="book"></p-tableCheckbox>
|
||||
</td>
|
||||
<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 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>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import {Component, EventEmitter, inject, Input, OnChanges, Output} from '@angular/core';
|
||||
import {TableModule} from 'primeng/table';
|
||||
import {NgIf} from '@angular/common';
|
||||
import {AsyncPipe, NgIf} from '@angular/common';
|
||||
import {Rating} from 'primeng/rating';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
import {Book} from '../../../model/book.model';
|
||||
import {SortOption} from '../../../model/sort.model';
|
||||
import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service';
|
||||
import {UrlHelperService} from '../../../../utilities/service/url-helper.service';
|
||||
import {SecurePipe} from '../../../../secure-pipe';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-table',
|
||||
@@ -16,7 +17,9 @@ import {UrlHelperService} from '../../../../utilities/service/url-helper.service
|
||||
TableModule,
|
||||
NgIf,
|
||||
Rating,
|
||||
FormsModule
|
||||
FormsModule,
|
||||
SecurePipe,
|
||||
AsyncPipe
|
||||
],
|
||||
styleUrl: './book-table.component.scss'
|
||||
})
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<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="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="flex items-center">
|
||||
<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 {BookService} from '../../service/book.service';
|
||||
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 {Divider} from 'primeng/divider';
|
||||
import {UrlHelperService} from '../../../utilities/service/url-helper.service';
|
||||
import {SecurePipe} from '../../../secure-pipe';
|
||||
|
||||
@Component({
|
||||
selector: 'app-book-searcher',
|
||||
@@ -21,7 +22,9 @@ import {UrlHelperService} from '../../../utilities/service/url-helper.service';
|
||||
NgIf,
|
||||
NgForOf,
|
||||
SlicePipe,
|
||||
Divider
|
||||
Divider,
|
||||
AsyncPipe,
|
||||
SecurePipe
|
||||
],
|
||||
styleUrls: ['./book-searcher.component.scss'],
|
||||
standalone: true
|
||||
|
||||
@@ -1,17 +1,27 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import {HttpClient} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import { Injectable, Injector } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Observable, tap } from 'rxjs';
|
||||
import { RxStompService } from '../../shared/websocket/rx-stomp.service';
|
||||
import { createRxStompConfig } from '../../shared/websocket/rx-stomp.config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
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> {
|
||||
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 {
|
||||
@@ -24,5 +34,22 @@ export class AuthService {
|
||||
|
||||
logout(): void {
|
||||
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 {LiveNotificationBoxComponent} from '../../../core/component/live-notification-box/live-notification-box.component';
|
||||
import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component';
|
||||
import {AuthService} from '../../../core/service/auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-topbar',
|
||||
@@ -49,7 +50,7 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
@ViewChild('topbarmenu') menu!: ElementRef;
|
||||
|
||||
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.eventHighlight = highlight;
|
||||
});
|
||||
@@ -115,7 +116,7 @@ export class AppTopBarComponent implements OnDestroy {
|
||||
}
|
||||
|
||||
logout() {
|
||||
localStorage.removeItem('token');
|
||||
this.authService.logout();
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
<div class="login-container">
|
||||
<h2>Login</h2>
|
||||
<form (submit)="login()">
|
||||
<label>Username</label>
|
||||
<input type="text" [(ngModel)]="username" name="username" required />
|
||||
<p-card class="login-card p-fluid">
|
||||
<ng-template pTemplate="title">Login</ng-template>
|
||||
|
||||
<label>Password</label>
|
||||
<input type="password" [(ngModel)]="password" name="password" required />
|
||||
<ng-template pTemplate="content">
|
||||
<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>
|
||||
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>
|
||||
</form>
|
||||
<div class="p-field">
|
||||
<label for="password">Password</label>
|
||||
<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>
|
||||
|
||||
@@ -1,27 +1,19 @@
|
||||
.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 {
|
||||
@apply text-2xl font-bold text-gray-700 mb-4;
|
||||
.login-card {
|
||||
@apply w-96 shadow-lg rounded-xl;
|
||||
}
|
||||
|
||||
form {
|
||||
@apply bg-white p-6 rounded-2xl shadow-lg w-96 flex flex-col gap-4;
|
||||
@apply flex flex-col gap-4;
|
||||
|
||||
label {
|
||||
@apply text-sm font-semibold text-gray-600;
|
||||
.p-field {
|
||||
@apply flex flex-col gap-1;
|
||||
}
|
||||
|
||||
input {
|
||||
@apply w-full p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400;
|
||||
}
|
||||
|
||||
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;
|
||||
p-button {
|
||||
@apply mt-2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,12 +3,24 @@ import {AuthService} from '../core/service/auth.service';
|
||||
import {Router} from '@angular/router';
|
||||
import {FormsModule} from '@angular/forms';
|
||||
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({
|
||||
selector: 'app-login',
|
||||
imports: [
|
||||
FormsModule,
|
||||
NgIf
|
||||
NgIf,
|
||||
Card,
|
||||
Password,
|
||||
Button,
|
||||
Message,
|
||||
PrimeTemplate,
|
||||
InputText
|
||||
],
|
||||
templateUrl: './login.component.html',
|
||||
styleUrl: './login.component.scss'
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
<div class="flex flex-col items-center gap-2 relative">
|
||||
|
||||
<img
|
||||
[src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn)"
|
||||
[attr.src]="urlHelper.getCoverUrl(metadata.bookId, metadata?.coverUpdatedOn) | secure | async"
|
||||
alt="Image"
|
||||
width="250"
|
||||
[ngClass]="{ 'brightness-50': isUploading }"
|
||||
|
||||
+3
-1
@@ -14,6 +14,7 @@ import {FileUpload, FileUploadErrorEvent, FileUploadEvent} from 'primeng/fileupl
|
||||
import {HttpResponse} from '@angular/common/http';
|
||||
import {BookService} from '../../../book/service/book.service';
|
||||
import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
import {SecurePipe} from '../../../secure-pipe';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-editor',
|
||||
@@ -31,7 +32,8 @@ import {ProgressSpinner} from 'primeng/progressspinner';
|
||||
ReactiveFormsModule,
|
||||
FileUpload,
|
||||
ProgressSpinner,
|
||||
NgClass
|
||||
NgClass,
|
||||
SecurePipe
|
||||
]
|
||||
})
|
||||
export class MetadataEditorComponent implements OnInit {
|
||||
|
||||
+5
-1
@@ -2,7 +2,11 @@
|
||||
<div class="book-metadata-container flex-shrink-0" *ngIf="metadata$ | async as metadata">
|
||||
<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="flex flex-row items-center justify-between">
|
||||
|
||||
+2
-1
@@ -10,13 +10,14 @@ import {Tag} from 'primeng/tag';
|
||||
import {BookMetadata} from '../../../book/model/book.model';
|
||||
import {Divider} from 'primeng/divider';
|
||||
import {UrlHelperService} from '../../../utilities/service/url-helper.service';
|
||||
import {SecurePipe} from '../../../secure-pipe';
|
||||
|
||||
@Component({
|
||||
selector: 'app-metadata-viewer',
|
||||
standalone: true,
|
||||
templateUrl: './metadata-viewer.component.html',
|
||||
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 {
|
||||
|
||||
|
||||
@@ -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 { rxStompConfig } from './rx-stomp.config';
|
||||
import { createRxStompConfig } from './rx-stomp.config';
|
||||
import {AuthService} from '../../core/service/auth.service';
|
||||
|
||||
export function rxStompServiceFactory() {
|
||||
const rxStomp = new RxStompService();
|
||||
rxStomp.configure(rxStompConfig);
|
||||
rxStomp.activate();
|
||||
export function rxStompServiceFactory(authService: AuthService) {
|
||||
const rxStomp = new RxStompService(authService);
|
||||
const stompConfig = createRxStompConfig(authService);
|
||||
rxStomp.configure(stompConfig);
|
||||
return rxStomp;
|
||||
}
|
||||
|
||||
@@ -1,31 +1,18 @@
|
||||
import {RxStompConfig} from '@stomp/rx-stomp';
|
||||
import {API_CONFIG} from '../../config/api-config';
|
||||
import { RxStompConfig } from '@stomp/rx-stomp';
|
||||
import { API_CONFIG } from '../../config/api-config';
|
||||
import {AuthService} from '../../core/service/auth.service';
|
||||
|
||||
export const rxStompConfig: RxStompConfig = {
|
||||
// Which server?
|
||||
brokerURL: API_CONFIG.BROKER_URL,
|
||||
|
||||
// Headers
|
||||
// Typical keys: login, passcode, host
|
||||
connectHeaders: {
|
||||
login: 'guest',
|
||||
passcode: 'guest',
|
||||
},
|
||||
|
||||
// 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);
|
||||
},
|
||||
};
|
||||
export function createRxStompConfig(authService: AuthService): RxStompConfig {
|
||||
return {
|
||||
brokerURL: API_CONFIG.BROKER_URL,
|
||||
connectHeaders: {
|
||||
Authorization: `Bearer ${authService.getToken()}`,
|
||||
},
|
||||
heartbeatIncoming: 0,
|
||||
heartbeatOutgoing: 20000,
|
||||
reconnectDelay: 200,
|
||||
debug: (msg: string): void => {
|
||||
//console.log(new Date(), msg);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { RxStomp } from '@stomp/rx-stomp';
|
||||
import { AuthService } from '../../core/service/auth.service';
|
||||
import { createRxStompConfig } from './rx-stomp.config';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class RxStompService extends RxStomp {
|
||||
|
||||
constructor() {
|
||||
constructor(private authService: AuthService) {
|
||||
super();
|
||||
const stompConfig = createRxStompConfig(this.authService);
|
||||
this.configure(stompConfig);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { AppComponent } from './app/app.component';
|
||||
import Aura from '@primeng/themes/aura';
|
||||
import { routes } from './app/app.routes';
|
||||
import {AuthInterceptorService} from './app/auth-interceptor.service';
|
||||
import {AuthService} from './app/core/service/auth.service';
|
||||
|
||||
bootstrapApplication(AppComponent, {
|
||||
providers: [
|
||||
@@ -23,6 +24,7 @@ bootstrapApplication(AppComponent, {
|
||||
{
|
||||
provide: RxStompService,
|
||||
useFactory: rxStompServiceFactory,
|
||||
deps: [AuthService],
|
||||
},
|
||||
{
|
||||
provide: RouteReuseStrategy,
|
||||
|
||||
Reference in New Issue
Block a user