@@ -53,3 +53,51 @@ export class ChatGuard implements CanActivate {
53
53
return true ;
54
54
}
55
55
}
56
+
57
+ @Injectable ( )
58
+ export class MessageGuard implements CanActivate {
59
+ constructor (
60
+ private readonly chatService : ChatService , // Inject ChatService to fetch chat details
61
+ private readonly jwtService : JwtService , // JWT Service to verify tokens
62
+ ) { }
63
+
64
+ async canActivate ( context : ExecutionContext ) : Promise < boolean > {
65
+ const gqlContext = GqlExecutionContext . create ( context ) ;
66
+ const request = gqlContext . getContext ( ) . req ;
67
+
68
+ // Extract the authorization header
69
+ const authHeader = request . headers . authorization ;
70
+ if ( ! authHeader || ! authHeader . startsWith ( 'Bearer ' ) ) {
71
+ throw new UnauthorizedException ( 'Authorization token is missing' ) ;
72
+ }
73
+
74
+ // Decode the token to get user information
75
+ const token = authHeader . split ( ' ' ) [ 1 ] ;
76
+ let user : any ;
77
+ try {
78
+ user = this . jwtService . verify ( token ) ;
79
+ } catch ( error ) {
80
+ throw new UnauthorizedException ( 'Invalid token' ) ;
81
+ }
82
+
83
+ // Extract chatId from the request arguments
84
+ const args = gqlContext . getArgs ( ) ;
85
+ const { messageId } = args ;
86
+
87
+ // Fetch the message and its associated chat
88
+ const message = await this . chatService . getMessageById ( messageId ) ;
89
+ if ( ! message ) {
90
+ throw new UnauthorizedException ( 'Message not found' ) ;
91
+ }
92
+
93
+ // Ensure that the user is part of the chat the message belongs to
94
+ const chat = message . chat ;
95
+ if ( chat . user . id !== user . userId ) {
96
+ throw new UnauthorizedException (
97
+ 'User is not authorized to access this message' ,
98
+ ) ;
99
+ }
100
+
101
+ return true ;
102
+ }
103
+ }
0 commit comments