This commit is contained in:
2025-12-10 23:39:42 +03:30
parent 2d0c7dabee
commit 2be360639e
7 changed files with 692 additions and 2 deletions
@@ -0,0 +1,25 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { AuthenticatedSocket } from '../guards/ws-admin-auth.guard';
/**
* Extract restaurant ID from authenticated WebSocket client
* Use this decorator in WebSocket handlers to get the restId from the authenticated admin
*
* @example
* ```typescript
* @SubscribeMessage('get:notifications')
* handleGetNotifications(@WsRestId() restId: string) {
* // restId is automatically extracted from authenticated admin
* }
* ```
*/
export const WsRestId = createParamDecorator((data: unknown, ctx: ExecutionContext): string => {
const client = ctx.switchToWs().getClient<AuthenticatedSocket>();
const restId = client.restId;
if (!restId) {
throw new Error('Restaurant ID not found. Ensure WsAdminAuthGuard is applied.');
}
return restId;
});
@@ -0,0 +1,104 @@
import { CanActivate, ExecutionContext, Injectable, Logger, Inject } from '@nestjs/common';
import { WsException } from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { IAdminTokenPayload } from '../../auth/interfaces/IToken-payload';
export interface AuthenticatedSocket extends Socket {
adminId?: string;
restId?: string;
}
@Injectable()
export class WsAdminAuthGuard implements CanActivate {
private readonly logger = new Logger(WsAdminAuthGuard.name);
constructor(
@Inject(JwtService)
private readonly jwtService: JwtService,
@Inject(ConfigService)
private readonly configService: ConfigService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const client: Socket = context.switchToWs().getClient<Socket>();
try {
const token = this.extractToken(client);
if (!token) {
this.logger.warn('No token provided in WebSocket connection', {
socketId: client.id,
auth: client.handshake.auth,
query: client.handshake.query,
});
throw new WsException('Authentication required');
}
const secret = this.configService.getOrThrow<string>('JWT_SECRET');
const payload = await this.jwtService.verifyAsync<IAdminTokenPayload>(token, {
secret,
});
if (!payload.adminId || !payload.restId) {
this.logger.error('Invalid token payload structure', payload);
throw new WsException('Invalid token payload');
}
// Attach admin info to socket
(client as AuthenticatedSocket).adminId = payload.adminId;
(client as AuthenticatedSocket).restId = payload.restId;
this.logger.log(`Admin authenticated via WebSocket: ${payload.adminId}, restId: ${payload.restId}`);
return true;
} catch (error) {
if (error instanceof WsException) {
throw error;
}
this.logger.error('WebSocket authentication error', {
error: error instanceof Error ? error.message : 'Unknown error',
socketId: client.id,
});
throw new WsException('Authentication failed');
}
}
private extractToken(client: Socket): string | undefined {
// Try to get token from handshake auth (recommended for socket.io)
const auth = client.handshake.auth;
const authToken = (auth?.token as string | undefined) || (auth?.authorization as string | undefined);
if (authToken) {
// If it's "Bearer <token>", extract just the token
if (typeof authToken === 'string' && authToken.startsWith('Bearer ')) {
return authToken.substring(7);
}
return authToken;
}
// Try to get from query parameters (fallback)
const queryToken = client.handshake.query?.token || client.handshake.query?.authorization;
if (queryToken) {
if (typeof queryToken === 'string' && queryToken.startsWith('Bearer ')) {
return queryToken.substring(7);
}
return queryToken as string;
}
// Try to get from headers (if available)
const headers = client.handshake.headers;
const authHeader = headers.authorization || headers['authorization'];
if (authHeader && typeof authHeader === 'string') {
const [type, token] = authHeader.split(' ');
if (type?.toLowerCase() === 'bearer' && token) {
return token;
}
}
return undefined;
}
}
@@ -30,6 +30,15 @@ export class NotificationsController {
);
}
@UseGuards(AdminAuthGuard)
@ApiBearerAuth()
@Get('admin/notifications')
@ApiOperation({ summary: 'Get Admin restaurant notifications' })
@ApiQuery({ name: 'limit', required: false, type: Number })
async getAdminNotifications(@RestId() restaurantId: string, @Query('limit') limit?: number) {
return await this.notificationService.findByRestaurant(restaurantId, limit ? parseInt(limit.toString(), 30) : 50);
}
@UseGuards(AdminAuthGuard)
@ApiBearerAuth()
@Delete('admin/notification/:id')
@@ -39,6 +48,7 @@ export class NotificationsController {
await this.notificationService.removeNotification(id, restaurantId);
return { message: 'Notification deleted successfully' };
}
// @UseGuards(AuthGuard)
// @ApiBearerAuth()
// @Get('public/notifications/:id')
@@ -0,0 +1,69 @@
import {
WebSocketGateway,
WebSocketServer,
SubscribeMessage,
OnGatewayConnection,
OnGatewayDisconnect,
MessageBody,
ConnectedSocket,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { Logger, UseGuards } from '@nestjs/common';
import { WsAdminAuthGuard, type AuthenticatedSocket } from './guards/ws-admin-auth.guard';
import { WsRestId } from './decorators/ws-rest-id.decorator';
import { NotificationService } from './services/notification.service';
@WebSocketGateway({
cors: {
origin: true,
credentials: true,
},
namespace: '/notifications',
})
export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server!: Server;
private readonly logger = new Logger(NotificationsGateway.name);
constructor(private readonly notificationService: NotificationService) {}
handleConnection(client: Socket) {
this.logger.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
}
/**
* Get admin restaurant notifications
* Requires admin authentication via JWT token
* Restaurant ID is extracted from the authenticated admin's token
* This is a WebSocket substitution for GET /admin/notifications
*/
@UseGuards(WsAdminAuthGuard)
@SubscribeMessage('get:notifications')
async handleGetNotifications(
@ConnectedSocket() client: AuthenticatedSocket,
@WsRestId() restId: string,
@MessageBody() data?: { limit?: number },
) {
try {
const limit = data?.limit ? parseInt(data.limit.toString(), 10) : 50;
const notifications = await this.notificationService.findByRestaurant(restId, limit);
void client.emit('notifications:list', { notifications });
this.logger.log(`Admin ${client.adminId} requested notifications list for restaurant ${restId}`);
} catch (error) {
this.logger.error(
`Error getting notifications list: ${error instanceof Error ? error.message : 'Unknown error'}`,
);
void client.emit('error', {
message: 'Failed to get notifications list',
code: 'GET_NOTIFICATIONS_ERROR',
details: error instanceof Error ? error.message : 'Unknown error',
});
}
}
}
@@ -19,6 +19,8 @@ import { AuthModule } from '../auth/auth.module';
import { ConfigService } from '@nestjs/config';
import { NotificationQueueNameEnum } from './constants/queue';
import { UtilsModule } from '../utils/utils.module';
import { NotificationsGateway } from './notifications.gateway';
import { WsAdminAuthGuard } from './guards/ws-admin-auth.guard';
@Module({
imports: [
@@ -48,6 +50,8 @@ import { UtilsModule } from '../utils/utils.module';
PushProcessor,
SmsProcessor,
NotificationListeners,
NotificationsGateway,
WsAdminAuthGuard,
],
exports: [
NotificationService,
@@ -12,8 +12,8 @@ export class SmsAdaptorService {
private readonly configService: ConfigService,
private readonly smsService: SmsService,
) {
this.smsPatternOrderCreated = this.configService.getOrThrow<string>('SMS_PATTERN_ORDER_CREATED');
this.smsPatternPaymentSuccess = this.configService.getOrThrow<string>('SMS_PATTERN_PAYMENT_SUCCESS');
this.smsPatternOrderCreated = this.configService.get<string>('SMS_PATTERN_ORDER_CREATED') ?? '1';
this.smsPatternPaymentSuccess = this.configService.get<string>('SMS_PATTERN_PAYMENT_SUCCESS') ?? '2';
}
async sendNotifySms(params: ISmsNotifyPayload) {
+478
View File
@@ -0,0 +1,478 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Notifications Socket.IO Test</title>
<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
overflow: hidden;
}
.header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 30px;
text-align: center;
}
.header h1 {
font-size: 28px;
margin-bottom: 10px;
}
.header p {
opacity: 0.9;
}
.content {
padding: 30px;
}
.section {
margin-bottom: 30px;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #667eea;
}
.section h2 {
color: #333;
margin-bottom: 15px;
font-size: 20px;
}
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
color: #555;
font-weight: 500;
}
input,
select {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus,
select:focus {
outline: none;
border-color: #667eea;
}
.button-group {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
button {
padding: 12px 24px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
flex: 1;
min-width: 120px;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-success {
background: #28a745;
color: white;
}
.btn-success:hover {
background: #218838;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-danger:hover {
background: #c82333;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(220, 53, 69, 0.4);
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn-secondary:hover {
background: #5a6268;
}
.status {
padding: 15px;
border-radius: 6px;
margin-bottom: 20px;
font-weight: 500;
}
.status.connected {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.status.disconnected {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.status.connecting {
background: #fff3cd;
color: #856404;
border: 1px solid #ffeaa7;
}
.events {
max-height: 400px;
overflow-y: auto;
background: #1e1e1e;
color: #d4d4d4;
padding: 15px;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 13px;
}
.event-item {
margin-bottom: 10px;
padding: 10px;
background: #2d2d2d;
border-radius: 4px;
border-left: 3px solid #667eea;
}
.event-time {
color: #858585;
font-size: 11px;
margin-bottom: 5px;
}
.event-type {
color: #4ec9b0;
font-weight: bold;
margin-bottom: 5px;
}
.event-data {
color: #ce9178;
white-space: pre-wrap;
word-break: break-all;
}
.clear-btn {
margin-top: 10px;
}
.notifications-list {
max-height: 300px;
overflow-y: auto;
background: #f8f9fa;
border-radius: 6px;
padding: 15px;
margin-top: 15px;
}
.notification-item {
background: white;
padding: 12px;
margin-bottom: 10px;
border-radius: 6px;
border-left: 3px solid #667eea;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.notification-title {
font-weight: 600;
color: #333;
margin-bottom: 5px;
}
.notification-content {
color: #666;
font-size: 14px;
margin-bottom: 5px;
}
.notification-meta {
font-size: 12px;
color: #999;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🔔 Notifications Socket.IO Test Client</h1>
<p>Test real-time admin notifications</p>
</div>
<div class="content">
<!-- Connection Section -->
<div class="section">
<h2>Connection</h2>
<div class="form-group">
<label for="serverUrl">Server URL:</label>
<input type="text" id="serverUrl" value="http://localhost:4000" placeholder="http://localhost:4000" />
</div>
<div class="form-group">
<label for="authToken">Admin Token:</label>
<input type="text" id="authToken" placeholder="Bearer token (required)" />
<small style="color: #666; display: block; margin-top: 5px"
>Enter JWT token for admin authentication. Restaurant ID will be extracted from token.</small
>
</div>
<div class="button-group">
<button class="btn-primary" onclick="connect()">Connect</button>
<button class="btn-danger" onclick="disconnect()">Disconnect</button>
</div>
<div id="connectionStatus" class="status disconnected">Status: Disconnected</div>
</div>
<!-- Notifications Section -->
<div class="section">
<h2>Get Notifications</h2>
<div class="form-group">
<label for="limit">Limit (optional):</label>
<input type="number" id="limit" placeholder="50" value="50" min="1" max="100" />
<small style="color: #666; display: block; margin-top: 5px"
>Number of notifications to retrieve (default: 50)</small
>
</div>
<div class="button-group">
<button class="btn-success" onclick="getNotifications()">Get Notifications</button>
</div>
</div>
<!-- Notifications List Section -->
<div class="section">
<h2>Notifications List</h2>
<div id="notificationsList" class="notifications-list">
<div style="text-align: center; color: #999; padding: 20px">
No notifications loaded yet. Click "Get Notifications" to fetch.
</div>
</div>
</div>
<!-- Events Section -->
<div class="section">
<h2>Events Log <button class="btn-secondary clear-btn" onclick="clearEvents()">Clear</button></h2>
<div id="events" class="events">
<div class="event-item">
<div class="event-time">Ready to connect...</div>
<div class="event-type">INFO</div>
<div class="event-data">Enter server URL and admin token, then click Connect to start</div>
</div>
</div>
</div>
</div>
</div>
<script>
let socket = null;
function connect() {
const serverUrl = document.getElementById('serverUrl').value || 'http://localhost:4000';
const token = document.getElementById('authToken').value.trim();
if (socket && socket.connected) {
addEvent('WARNING', 'Already connected!');
return;
}
if (!token) {
addEvent('ERROR', 'Admin token is required!');
return;
}
updateStatus('connecting', 'Connecting...');
addEvent('INFO', `Connecting to ${serverUrl}/notifications...`);
const authOptions = {};
if (token) {
// Remove "Bearer " prefix if present
const cleanToken = token.startsWith('Bearer ') ? token.substring(7) : token;
authOptions.token = cleanToken;
addEvent('INFO', 'Using authentication token');
}
socket = io(`${serverUrl}/notifications`, {
transports: ['websocket', 'polling'],
reconnection: true,
reconnectionDelay: 1000,
reconnectionAttempts: 5,
auth: authOptions,
});
socket.on('connect', () => {
updateStatus('connected', 'Connected');
addEvent('SUCCESS', `Connected! Socket ID: ${socket.id}`);
});
socket.on('disconnect', reason => {
updateStatus('disconnected', 'Disconnected');
addEvent('WARNING', `Disconnected: ${reason}`);
});
socket.on('connect_error', error => {
updateStatus('disconnected', 'Connection Failed');
addEvent('ERROR', `Connection error: ${error.message}`);
});
socket.on('notifications:list', data => {
addEvent('SUCCESS', `Received ${data.notifications?.length || 0} notifications`, data);
displayNotifications(data.notifications || []);
});
socket.on('error', data => {
addEvent('ERROR', data.message || 'Error occurred', data);
});
// Handle authentication errors
socket.on('exception', data => {
addEvent('ERROR', `Server error: ${data.message || JSON.stringify(data)}`, data);
});
}
function disconnect() {
if (socket) {
socket.disconnect();
socket = null;
updateStatus('disconnected', 'Disconnected');
addEvent('INFO', 'Manually disconnected');
}
}
function getNotifications() {
if (!socket || !socket.connected) {
addEvent('ERROR', 'Please connect first!');
return;
}
const limitInput = document.getElementById('limit');
const limit = limitInput.value ? parseInt(limitInput.value, 10) : 50;
if (limit < 1 || limit > 100) {
addEvent('ERROR', 'Limit must be between 1 and 100');
return;
}
socket.emit('get:notifications', { limit });
addEvent('INFO', `Requesting notifications (limit: ${limit})...`);
}
function displayNotifications(notifications) {
const listDiv = document.getElementById('notificationsList');
if (!notifications || notifications.length === 0) {
listDiv.innerHTML =
'<div style="text-align: center; color: #999; padding: 20px;">No notifications found.</div>';
return;
}
let html = '';
notifications.forEach(notification => {
const date = notification.createdAt ? new Date(notification.createdAt).toLocaleString() : 'N/A';
html += `
<div class="notification-item">
<div class="notification-title">${notification.title || 'N/A'}</div>
<div class="notification-content">${notification.content || 'No content'}</div>
<div class="notification-meta">
ID: ${notification.id} | Created: ${date}
${notification.user ? ` | User: ${notification.user.firstName || ''} ${notification.user.lastName || ''}` : ''}
</div>
</div>
`;
});
listDiv.innerHTML = html;
}
function updateStatus(status, message) {
const statusEl = document.getElementById('connectionStatus');
statusEl.className = `status ${status}`;
statusEl.textContent = `Status: ${message}`;
}
function addEvent(type, message, data = null) {
const eventsDiv = document.getElementById('events');
const eventItem = document.createElement('div');
eventItem.className = 'event-item';
const time = new Date().toLocaleTimeString();
const typeColors = {
INFO: '#4ec9b0',
SUCCESS: '#4ec9b0',
WARNING: '#dcdcaa',
ERROR: '#f48771',
NOTIFICATIONS_LIST: '#4fc1ff',
};
eventItem.innerHTML = `
<div class="event-time">${time}</div>
<div class="event-type" style="color: ${typeColors[type] || '#4ec9b0'}">[${type}]</div>
<div class="event-data">${message}</div>
${data ? `<div class="event-data" style="margin-top: 8px; color: #9cdcfe;">${JSON.stringify(data, null, 2)}</div>` : ''}
`;
eventsDiv.insertBefore(eventItem, eventsDiv.firstChild);
}
function clearEvents() {
document.getElementById('events').innerHTML = '';
addEvent('INFO', 'Events log cleared');
}
</script>
</body>
</html>