Skip to content

Commit

Permalink
working on finishing chat and other things
Browse files Browse the repository at this point in the history
  • Loading branch information
Wadie-ess committed Nov 10, 2023
1 parent 13a9569 commit fb41310
Show file tree
Hide file tree
Showing 44 changed files with 1,527 additions and 791 deletions.
11 changes: 11 additions & 0 deletions backend/code/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Res,
HttpCode,
HttpStatus,
Param
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthDto } from './dto/auth.dto';
Expand Down Expand Up @@ -107,4 +108,14 @@ export class AuthController {
path: '/auth',
});
}

@Get('validatToken/:token')
async validatToken(
@Param('token') token: string,
@Res({ passthrough: true }) res: Response,

Check failure on line 115 in backend/code/src/auth/auth.controller.ts

View workflow job for this annotation

GitHub Actions / Build_backend

'res' is defined but never used
) {
return this.authService.checkToken(token);
}
}


14 changes: 14 additions & 0 deletions backend/code/src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,18 @@ export class AuthService {
}
return { isValid };
}


async checkToken(tfaToken: string)
{
const user = await this.prisma.user.findUnique({
where: { tfaToken },
select: {
tfaToken: true
},
});
if(!user)
return false;
return true;
}
}
2 changes: 1 addition & 1 deletion backend/code/src/auth/stratgies/ft.strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class FtStrategy extends PassportStrategy(Strategy, '42') {
if (user.tfaEnabled) {
const tfaToken = crypto.randomBytes(20).toString('hex');
await this.usersService.updateUser(user.userId, { tfaToken });
res.redirect(process.env.FRONT_URL + '/tfa/' + tfaToken);
res.redirect(process.env.FRONT_URL + '/2fa/validate/' + tfaToken);
return cb(null, profile);
}

Expand Down
11 changes: 10 additions & 1 deletion backend/code/src/game/game.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,22 @@ export class GameService {
private readonly prisma: PrismaService,
private eventEmitter: EventEmitter2,
) {
this.launchGame();
//this.launchGame();
}

private waitingPlayers: Socket[] = [];

@OnEvent('game.start')
handleGameStartEvent(client: Socket) {
const index = this.waitingPlayers.find((player) => {
return player.data.user.sub === client.data.user.sub;
}
);
if (index) {
console.log('client already in the queue');
return;
}

this.waitingPlayers.push(client);
console.log('client subscribed to the queue');
}
Expand Down
55 changes: 35 additions & 20 deletions backend/code/src/gateways/gateways.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';
import { PrismaService } from 'src/prisma/prisma.service';
import { Game } from 'src/game/game';
import { $Enums, Notification } from '@prisma/client';
import { Client } from 'socket.io/dist/client';

Check failure on line 16 in backend/code/src/gateways/gateways.gateway.ts

View workflow job for this annotation

GitHub Actions / Build_backend

'Client' is defined but never used

@WebSocketGateway(3004, {
cors: {
Expand Down Expand Up @@ -87,7 +88,6 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {

@OnEvent('sendMessages')
sendMessage(message: MessageFormatDto) {
console.log('recive msg !');
const chanellname: string = `Room:${message.roomId}`;
this.server.to(chanellname).emit('message', message);
}
Expand Down Expand Up @@ -154,14 +154,20 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
},
},
});
const roomMembers = await this.prisma.roomMember.findMany({
let roomMembers = await this.prisma.roomMember.findMany({
where: {
roomId: message.roomId,
},
select: {
userId: true,
is_banned: true,
},
});

roomMembers = roomMembers.filter(
(member) => member.userId !== message.authorId && member.userId !== notif.actorId && !member.is_banned,
);

const clientsSockets = await this.server
.in(`Room:${message.roomId}`)
.fetchSockets();
Expand Down Expand Up @@ -221,21 +227,29 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
}

@SubscribeMessage('joinRoom')
async handleJoinRoomEvent(data: any) {
async handleJoinRoomEvent(client: Socket, data: any) {
const userId = client.data.user.sub;
const member = await this.prisma.roomMember.findFirst({
where: {
userId: data.memberId,
roomId: data.roomId,
},
});
if (member && !member.is_banned) {
const banedClientSocket = await this.server
.in(`User:${data.memberId}`)
.fetchSockets();
if (banedClientSocket.length > 0) {
banedClientSocket[0].join(`Room:${data.roomId}`);
}
if (member && !member.is_banned && userId === data.memberId) {
client.join(`Room:${data.roomId}`);
}

}

@SubscribeMessage('PingOnline')
async handlePingOnlineEvent(client: Socket, data: any) {
const userId = client.data.user.sub;
const friendId = data.friendId;
if (this.server.sockets.adapter.rooms.get(`User:${friendId}`)?.size) {

Check failure on line 248 in backend/code/src/gateways/gateways.gateway.ts

View workflow job for this annotation

GitHub Actions / Build_backend

'userId' is assigned a value but never used
client.emit('friendOnline', friendId);
return true;
}
return false;
}

@SubscribeMessage('unban')
Expand Down Expand Up @@ -269,18 +283,19 @@ export class Gateways implements OnGatewayConnection, OnGatewayDisconnect {
async hundleDeparture(
@MessageBody() data: { roomId: string; memberId: string; type: string },
) {
const clients = await this.server.in(`Room:${data.roomId}`).fetchSockets();
console.log(`Room:${data.roomId}`);
const clientToBan = clients.find(
const clients = await this.server.in(`User:${data.memberId}`).fetchSockets();
const clientsToBan = clients.filter(
(client) => client.data.user.sub === data.memberId,
);
if (clientToBan) {
clientToBan.leave(`Room:${data.roomId}`);
if (data?.type === 'kick') {
clientToBan.emit('roomDeparture', {
roomId: data.roomId,
type: 'kick',
});
if (clientsToBan.length) {
for await (const client of clientsToBan) {
client.leave(`Room:${data.roomId}`);
if (data?.type === 'kick') {
client.emit('roomDeparture', {
roomId: data.roomId,
type: 'kick',
});
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion backend/code/src/messages/messages.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export class MessagesService {
const responseMessage: MessageFormatDto = new MessageFormatDto(messageData);
this.eventEmitter.emit('sendNotification', {
actorId: userId,
type: $Enums.NotifType.addFriend,
type: $Enums.NotifType.message,
entityId: messageData.id,
entity_type: 'message',
});
Expand Down
13 changes: 13 additions & 0 deletions backend/code/src/rooms/rooms.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,17 @@ export class RoomsController {
) {
return this.roomsService.getDMs(userId, offset, limit);
}

@Get('dm/:id')
@ApiResponse({
status: HttpStatus.OK,
})
@HttpCode(HttpStatus.OK)
@UseGuards(AtGuard)
async getDM(
@GetCurrentUser('userId') userId: string,
@Param('id') dmId: string,
) {
return this.roomsService.getDM(userId, dmId);
}
}
47 changes: 47 additions & 0 deletions backend/code/src/rooms/rooms.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,7 @@ export class RoomsService {
firstName: true,
lastName: true,
avatar: true,
discreption: true,
},
},
},
Expand Down Expand Up @@ -680,9 +681,55 @@ export class RoomsService {
secondMemberId: secondMember.user.userId,
last_message,
avatar,
bio: secondMember.user.discreption,
};
}),
);
return dmsData;
}

async getDM(userId: string, dmId: string) {
const room = await this.prisma.room.findUnique({
where: {
id: dmId,
},
select: {
id: true,
type: true,
ownerId: true,
members: {
select: {
user: {
select: {
userId: true,
firstName: true,
lastName: true,
avatar: true,
discreption: true,
},
},
},
},
},
});
if (!room) throw new HttpException('room not found', HttpStatus.NOT_FOUND);
const member = room.members.find((member) => member.user.userId === userId);
if (!member)
throw new UnauthorizedException('you are not a member of this room');
const secondMember = room.members.find(
(member) => member.user.userId !== userId,
);
const avatar: PICTURE = {
thumbnail: `https://res.cloudinary.com/trandandan/image/upload/c_thumb,h_48,w_48/${secondMember.user.avatar}`,
medium: `https://res.cloudinary.com/trandandan/image/upload/c_thumb,h_72,w_72/${secondMember.user.avatar}`,
large: `https://res.cloudinary.com/trandandan/image/upload/c_thumb,h_128,w_128/${secondMember.user.avatar}`,
};
return {
id: room.id,
name: secondMember.user.firstName + ' ' + secondMember.user.lastName,
secondMemberId: secondMember.user.userId,
avatar,
bio: secondMember.user.discreption,
};
}
}
25 changes: 22 additions & 3 deletions backend/code/src/users/dto/two-factor.dto.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
import { IsBoolean } from 'class-validator';
import { IsBoolean, IsString, IsNotEmpty, IsEnum, IsOptional} from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

Check failure on line 2 in backend/code/src/users/dto/two-factor.dto.ts

View workflow job for this annotation

GitHub Actions / Build_backend

'IsBoolean' is defined but never used

export enum TwoFactorAction {
ENABLE = 'enable',
DISABLE = 'disable',
}
export class TwoFactorDto {
@IsBoolean()
activate: boolean;
@IsString()
@IsNotEmpty()
@IsOptional()
@ApiProperty({example: "MC41emVyMjFqbG4w"})
secret: string;

@IsString()
@IsNotEmpty()
@ApiProperty({example: "745896"})
otp: string;

@IsString()
@IsNotEmpty()
@IsEnum(TwoFactorAction)
@ApiProperty({example: TwoFactorAction.ENABLE})
action: string;
}
9 changes: 2 additions & 7 deletions backend/code/src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,14 @@ export class UsersController {
return this.usersService.getUsers(query.q);
}

@Post('twoFactorAuth')
@Post('enableTwoFactorAuth')
@HttpCode(HttpStatus.OK)
@UseGuards(AtGuard)
async twoFactorAuth(
@Body() dataDto: TwoFactorDto,
@GetCurrentUser('userId') userId: string,
) {
return this.usersService.twoFactorAuth(userId, dataDto.activate);
return this.usersService.twoFactorAuth(userId, dataDto);
}

@Get('2faQrCode')
@UseGuards(AtGuard)
async get2faQrCode(@GetCurrentUser('userId') userId: string) {
return this.usersService.genertQrcode(userId);
}
}
Loading

0 comments on commit fb41310

Please sign in to comment.