Skip to content

Commit 06b6dcb

Browse files
committed
add message guard
1 parent da1463b commit 06b6dcb

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

backend/src/chat/chat.resolver.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
ChatInput,
1111
} from 'src/chat/dto/chat.input';
1212
import { UseGuards } from '@nestjs/common';
13-
import { ChatGuard } from '../guard/chat.guard';
13+
import { ChatGuard, MessageGuard } from '../guard/chat.guard';
1414
import { GetUserIdFromToken } from '../decorator/get-auth-token';
1515

1616
@Resolver('Chat')
@@ -52,6 +52,7 @@ export class ChatResolver {
5252
return user ? user.chats : []; // Return chats if user exists, otherwise return an empty array
5353
}
5454

55+
@UseGuards(MessageGuard)
5556
@Query(() => Message, { nullable: true })
5657
async getMessageDetail(
5758
@GetUserIdFromToken() userId: string,

backend/src/guard/chat.guard.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,51 @@ export class ChatGuard implements CanActivate {
5353
return true;
5454
}
5555
}
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

Comments
 (0)