forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpayment.gateway.ts
More file actions
168 lines (143 loc) · 4.71 KB
/
Copy pathpayment.gateway.ts
File metadata and controls
168 lines (143 loc) · 4.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import {
BadRequestException,
CanActivate,
ExecutionContext,
Injectable,
Logger,
UnauthorizedException,
UseGuards,
} from '@nestjs/common';
import {
WebSocketGateway,
WebSocketServer,
SubscribeMessage,
OnGatewayInit,
OnGatewayConnection,
OnGatewayDisconnect,
ConnectedSocket,
MessageBody,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import {
JoinRoomPayload,
JoinUserRoomPayload,
JoinedRoomEvent,
JoinedUserRoomEvent,
PaymentStatusUpdatePayload,
SplitCompletionPayload,
PaymentNotificationPayload,
ActivityNewPayload,
ActivityReadPayload,
WsHandlerResponse,
WsJwtPayload,
} from './payment-events.types';
import { AuthorizationService } from '../auth/services/authorization.service';
import { WsJwtAuthService } from '../ws-auth/ws-auth.service';
// Re-exported for backwards compatibility with existing import sites.
export { WsJwtAuthService };
@Injectable()
export class WsPaymentAuthGuard implements CanActivate {
constructor(
private readonly wsJwtAuthService: WsJwtAuthService,
) {}
canActivate(context: ExecutionContext): boolean {
const client = context.switchToWs().getClient<Socket>();
const payload = this.wsJwtAuthService.authenticateClient(client);
client.data.user = payload;
return true;
}
}
@WebSocketGateway({
cors: {
origin: '*',
credentials: true,
},
})
export class PaymentGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() server!: Server;
private logger: Logger = new Logger('PaymentGateway');
constructor(
private readonly wsJwtAuthService: WsJwtAuthService,
private readonly authorizationService: AuthorizationService,
) {}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
afterInit(_server: Server) {
this.logger.log('PaymentGateway initialized');
}
handleConnection(client: Socket): void {
try {
const payload = this.wsJwtAuthService.authenticateClient(client);
client.data.user = payload;
this.logger.log(`Client connected: ${client.id}`);
} catch {
this.logger.warn(`Unauthorized socket connection rejected: ${client.id}`);
client.disconnect(true);
}
}
handleDisconnect(client: Socket): void {
this.logger.log(`Client disconnected: ${client.id}`);
}
@UseGuards(WsPaymentAuthGuard)
@SubscribeMessage('join-room')
async handleJoinRoom(
@ConnectedSocket() client: Socket,
@MessageBody() payload: JoinRoomPayload,
): Promise<WsHandlerResponse<JoinedRoomEvent>> {
if (!payload?.roomId) {
throw new BadRequestException('roomId is required');
}
const userId = (client.data.user as WsJwtPayload)?.sub;
if (!userId) {
throw new UnauthorizedException('Authenticated user required');
}
const canAccess = await this.authorizationService.canAccessSplit(
userId,
payload.roomId,
);
if (!canAccess) {
throw new UnauthorizedException('Not allowed to join this room');
}
client.join(payload.roomId);
return { event: 'joined-room', data: { roomId: payload.roomId } };
}
emitPaymentStatusUpdate(roomId: string, data: PaymentStatusUpdatePayload): void {
this.server.to(roomId).emit('payment-status-update', data);
}
emitSplitCompletion(roomId: string, data: SplitCompletionPayload): void {
this.server.to(roomId).emit('split-completion', data);
}
emitPaymentNotification(roomId: string, data: PaymentNotificationPayload): void {
this.server.to(roomId).emit('payment-notification', data);
}
sendActivityUpdate(userId: string, activity: ActivityNewPayload): void {
this.server.to(`user-${userId}`).emit('activity-new', activity);
}
sendActivityReadUpdate(userId: string, activityIds: string[]): void {
this.server.to(`user-${userId}`).emit('activity-read', { activityIds } as ActivityReadPayload);
}
sendActivityReadAllUpdate(userId: string): void {
this.server.to(`user-${userId}`).emit('activity-read-all', {});
}
@UseGuards(WsPaymentAuthGuard)
@SubscribeMessage('join-user-room')
async handleJoinUserRoom(
@ConnectedSocket() client: Socket,
@MessageBody() payload: JoinUserRoomPayload,
): Promise<WsHandlerResponse<JoinedUserRoomEvent>> {
if (!payload?.userId) {
throw new BadRequestException('userId is required');
}
const userId = (client.data.user as WsJwtPayload)?.sub;
if (!userId) {
throw new UnauthorizedException('Authenticated user required');
}
if (payload.userId !== userId) {
throw new UnauthorizedException('Cannot join another user room');
}
client.join(`user-${payload.userId}`);
return { event: 'joined-user-room', data: { userId: payload.userId } };
}
}
export { PaymentGateway as WebSocketGateway };