wip password, and better catch error http request

This commit is contained in:
simplonco
2023-01-14 18:40:18 +01:00
parent 0449262398
commit efc836eac0
16 changed files with 185 additions and 167 deletions

View File

@@ -9,6 +9,7 @@ import { setCurrentRoomDto } from './dto/setCurrentRoom.dto';
import { ChatGateway } from './chat.gateway'; import { ChatGateway } from './chat.gateway';
import { socketDto } from './dto/socket.dto'; import { socketDto } from './dto/socket.dto';
import { Chatroom } from './entities/chatroom.entity'; import { Chatroom } from './entities/chatroom.entity';
import { printCaller } from './dev/dev_utils';
@Controller('chat') @Controller('chat')
export class ChatController { export class ChatController {
@@ -23,13 +24,12 @@ export class ChatController {
let new_room: roomDto = { let new_room: roomDto = {
name: room.name, name: room.name,
type: room.type, type: room.type,
protection: room.protection,
}; };
if (room.owner) if (room.owner)
new_room.owner = room.owner; new_room.owner = room.owner;
if (room.users) if (room.users)
new_room.users = room.users; new_room.users = room.users;
if (room.protection)
new_room.protection = room.protection;
return new_room; return new_room;
} }
@@ -46,15 +46,14 @@ export class ChatController {
@Get('myrooms') @Get('myrooms')
async getMyRooms(@Req() req, @Res() res): Promise<void> async getMyRooms(@Req() req, @Res() res): Promise<void>
{ {
console.log("- in getMyRooms controller"); printCaller("- in ");
let fields = ["name", "type", "users"]; let fields = ["name", "type", "users", "protection"];
const rooms = await this.chatService.getMyRooms(req.user.username, fields); const rooms = await this.chatService.getMyRooms(req.user.username, fields);
const ret_rooms = rooms.map(room => this.format_room(room)); const ret_rooms = rooms.map(room => this.format_room(room));
res.status(HttpStatus.OK).json({ rooms: ret_rooms }); res.status(HttpStatus.OK).json({ rooms: ret_rooms });
printCaller("- out ");
console.log("- out getMyRooms controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -62,14 +61,13 @@ export class ChatController {
@Get('allrooms') @Get('allrooms')
async getAllRooms(@Req() req, @Res() res): Promise<void> async getAllRooms(@Req() req, @Res() res): Promise<void>
{ {
console.log("- in getAllRooms controller"); printCaller("- in ");
const rooms: roomDto[] = await this.chatService.getAllOtherRoomsAndUsers(req.user.username) const rooms: roomDto[] = await this.chatService.getAllOtherRoomsAndUsers(req.user.username)
const ret_rooms = rooms.map(room => this.format_room(room)); const ret_rooms = rooms.map(room => this.format_room(room));
res.status(HttpStatus.OK).json({ rooms: ret_rooms }); res.status(HttpStatus.OK).json({ rooms: ret_rooms });
printCaller("- out ");
console.log("- out getAllRooms controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -77,12 +75,11 @@ export class ChatController {
@Get('current') @Get('current')
async setCurrentRoom(@Body() setCurrentRoomDto: setCurrentRoomDto, @Req() req, @Res() res): Promise<void> async setCurrentRoom(@Body() setCurrentRoomDto: setCurrentRoomDto, @Req() req, @Res() res): Promise<void>
{ {
console.log("- in setCurrentRoom controller"); printCaller("- in ");
const response = await this.chatService.setCurrentRoom(req.user.username, setCurrentRoomDto.name); const response = await this.chatService.setCurrentRoom(req.user.username, setCurrentRoomDto.name);
res.status(HttpStatus.OK).json({ message: response }); res.status(HttpStatus.OK).json({ message: response });
printCaller("- out ");
console.log("- out setCurrentRoom controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -90,11 +87,10 @@ export class ChatController {
@Get('allowedchars') @Get('allowedchars')
async allowedChars(@Res() res): Promise<void> async allowedChars(@Res() res): Promise<void>
{ {
console.log("- in allowedChars controller"); printCaller("- in ");
res.status(HttpStatus.OK).json({ chars: this.allowed_chars }); res.status(HttpStatus.OK).json({ chars: this.allowed_chars });
printCaller("- out ");
console.log("- out allowedChars controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -102,7 +98,7 @@ export class ChatController {
@Post('create') @Post('create')
async createRoom(@Body() room: roomDto, @Req() req, @Res() res): Promise<void> async createRoom(@Body() room: roomDto, @Req() req, @Res() res): Promise<void>
{ {
console.log("- in createRoom controller"); printCaller("- in ");
// check chars in room name // check chars in room name
let chars = this.escape_chars(this.allowed_chars); let chars = this.escape_chars(this.allowed_chars);
@@ -111,8 +107,8 @@ export class ChatController {
if (test_regex.test(room.name) === false) if (test_regex.test(room.name) === false)
{ {
let forbidden_chars = room.name.replace(new RegExp(regex_base, "g"), ""); let forbidden_chars = room.name.replace(new RegExp(regex_base, "g"), "");
console.log(`throw error: display: true, code: 'FORBIDDEN_CHARACTERS', message: 'Your room name can not contains these characters : ${forbidden_chars}'`); console.log(`throw error: error: true, code: 'FORBIDDEN_CHARACTERS', message: 'Your room name can not contains these characters : ${forbidden_chars}'`);
throw new HttpException({ display: true, code: 'FORBIDDEN_CHARACTERS', message: `Your room name can not contains these characters : ${forbidden_chars}` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'FORBIDDEN_CHARACTERS', message: `Your room name can not contains these characters : ${forbidden_chars}` }, HttpStatus.OK);
} }
if (typeof room.protection === 'undefined') if (typeof room.protection === 'undefined')
@@ -121,8 +117,8 @@ export class ChatController {
{ {
if (!room.password || room.password.length === 0) if (!room.password || room.password.length === 0)
{ {
console.log(`throw error: display: true, code: 'PASSWORD_TOO_SHORT', message: 'your password is too short'`); console.log(`throw error: error: true, code: 'PASSWORD_TOO_SHORT', message: 'your password is too short'`);
throw new HttpException({ display: true, code: 'PASSWORD_TOO_SHORT', message: `your password is too short` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'PASSWORD_TOO_SHORT', message: `your password is too short` }, HttpStatus.OK);
} }
} }
room.users = [req.user.username]; room.users = [req.user.username];
@@ -130,8 +126,7 @@ export class ChatController {
const ret_room = this.format_room(room); const ret_room = this.format_room(room);
res.status(HttpStatus.OK).json({ room: ret_room }); res.status(HttpStatus.OK).json({ room: ret_room });
printCaller("- out ");
console.log("- out createRoom controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -139,7 +134,7 @@ export class ChatController {
@Post('join') @Post('join')
async joinRoom(@Body() room: roomDto, @Req() req, @Res() res): Promise<void> async joinRoom(@Body() room: roomDto, @Req() req, @Res() res): Promise<void>
{ {
console.log("- in joinRoom controller"); printCaller("- in ");
let response = ""; let response = "";
if (room.type === 'user') if (room.type === 'user')
@@ -156,18 +151,18 @@ export class ChatController {
const room_db = await this.chatService.getRoomByName(room.name, fields); const room_db = await this.chatService.getRoomByName(room.name, fields);
if (room_db.type === 'direct') if (room_db.type === 'direct')
{ {
console.log("throw error: display: true, code: 'JOIN_DIRECT_FORBIDDEN', message: 'cannot join a direct messages room'"); console.log("throw error: error: true, code: 'JOIN_DIRECT_FORBIDDEN', message: 'cannot join a direct messages room'");
throw new HttpException({ display: true, code: 'JOIN_DIRECT_FORBIDDEN', message: `cannot join a direct messages room` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'JOIN_DIRECT_FORBIDDEN', message: `cannot join a direct messages room` }, HttpStatus.OK);
} }
if (room_db.type === 'private') if (room_db.type === 'private')
{ {
console.log("throw error: display: true, code: 'JOIN_PRIVATE_FORBIDDEN', message: 'cannot join a private room'"); console.log("throw error: error: true, code: 'JOIN_PRIVATE_FORBIDDEN', message: 'cannot join a private room'");
throw new HttpException({ display: true, code: 'JOIN_PRIVATE_FORBIDDEN', message: `cannot join a private room` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'JOIN_PRIVATE_FORBIDDEN', message: `cannot join a private room` }, HttpStatus.OK);
} }
if (room_db.users.includes(req.user.username)) if (room_db.users.includes(req.user.username))
{ {
console.log("throw error: display: true, code: 'ALREADY_JOIN', message: 'your have already joined this room'"); console.log("throw error: error: true, code: 'ALREADY_JOIN', message: 'your have already joined this room'");
throw new HttpException({ display: true, code: 'ALREADY_JOIN', message: `your have already joined this room` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'ALREADY_JOIN', message: `your have already joined this room` }, HttpStatus.OK);
} }
room = await this.chatService.addUserToRoom(req.user.username, room.name); room = await this.chatService.addUserToRoom(req.user.username, room.name);
} }
@@ -177,8 +172,7 @@ export class ChatController {
const ret_room = this.format_room(room); const ret_room = this.format_room(room);
res.status(HttpStatus.OK).json({ room: ret_room }); res.status(HttpStatus.OK).json({ room: ret_room });
printCaller("- out ");
console.log("- out joinRoom controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -186,7 +180,7 @@ export class ChatController {
@Post('change') @Post('change')
async changeRoom(@Body() room: roomDto, @Req() req, @Res() res): Promise<void> async changeRoom(@Body() room: roomDto, @Req() req, @Res() res): Promise<void>
{ {
console.log("- in changeRoom controller"); printCaller("- in ");
let fields = ["protection", "allowed_users"]; let fields = ["protection", "allowed_users"];
const room_db = await this.chatService.getRoomByName(room.name, fields); const room_db = await this.chatService.getRoomByName(room.name, fields);
@@ -194,8 +188,8 @@ export class ChatController {
{ {
if (!room_db.allowed_users.includes(req.user.username)) if (!room_db.allowed_users.includes(req.user.username))
{ {
console.log("throw error: display: true, code: 'NEED_AUTHENTICATE', message: 'You didn't provide the password for this room'"); console.log("throw error: error: true, code: 'NEED_AUTHENTICATE', message: 'You didn't provide the password for this room'");
throw new HttpException({ display: true, code: 'NEED_AUTHENTICATE', message: `You didn't provide the password for this room` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'NEED_AUTHENTICATE', message: `You didn't provide the password for this room` }, HttpStatus.OK);
} }
} }
@@ -205,8 +199,7 @@ export class ChatController {
const ret_room = this.format_room(room); const ret_room = this.format_room(room);
res.status(HttpStatus.OK).json({ room: ret_room }); res.status(HttpStatus.OK).json({ room: ret_room });
printCaller("- out ");
console.log("- out changeRoom controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -214,7 +207,7 @@ export class ChatController {
@Post('password') @Post('password')
async setPassword(@Body() room: roomDto, @Req() req, @Res() res): Promise<void> async setPassword(@Body() room: roomDto, @Req() req, @Res() res): Promise<void>
{ {
console.log("- in setPassword controller"); printCaller("- in ");
let fields = ["protection", "allowed_users"]; let fields = ["protection", "allowed_users"];
const room_db = await this.chatService.getRoomByName(room.name, fields); const room_db = await this.chatService.getRoomByName(room.name, fields);
@@ -222,14 +215,13 @@ export class ChatController {
{ {
if (!room.password) if (!room.password)
{ {
console.log("throw error: display: true, code: 'PASSWORD_MISSING', message: 'this room is protected, you need to provide a password'"); console.log("throw error: error: true, code: 'PASSWORD_MISSING', message: 'this room is protected, you need to provide a password'");
throw new HttpException({ display: true, code: 'PASSWORD_MISSING', message: `this room is protected, you need to provide a password` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'PASSWORD_MISSING', message: `this room is protected, you need to provide a password` }, HttpStatus.OK);
} }
if (!room_db.allowed_users.includes(req.user.username)) if (!room_db.allowed_users.includes(req.user.username))
await this.chatService.setPasswordValidation(req.user.username, room); await this.chatService.setPasswordValidation(req.user.username, room);
} }
printCaller("- out ");
console.log("- out setPassword controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -237,7 +229,7 @@ export class ChatController {
@Post('invite') @Post('invite')
async inviteUser(@Body('username') username: string, @Req() req, @Res() res): Promise<void> async inviteUser(@Body('username') username: string, @Req() req, @Res() res): Promise<void>
{ {
console.log("- in inviteUser controller"); printCaller("- in ");
let current_room_name = await this.chatService.getCurrentRoomName(req.user.username); let current_room_name = await this.chatService.getCurrentRoomName(req.user.username);
let room = await this.chatService.addUserToRoom(username, current_room_name); let room = await this.chatService.addUserToRoom(username, current_room_name);
@@ -246,8 +238,7 @@ export class ChatController {
const ret_room = this.format_room(room); const ret_room = this.format_room(room);
res.status(HttpStatus.OK).json({ room: ret_room }); res.status(HttpStatus.OK).json({ room: ret_room });
printCaller("- out ");
console.log("- out inviteUser controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -255,7 +246,7 @@ export class ChatController {
@Delete('leave') @Delete('leave')
async leaveRoom(@Req() req, @Res() res): Promise<void> async leaveRoom(@Req() req, @Res() res): Promise<void>
{ {
console.log("- in leaveRoom controller"); printCaller("- in ");
const room_name = await this.chatService.getCurrentRoomName(req.user.username); const room_name = await this.chatService.getCurrentRoomName(req.user.username);
let response = await this.chatService.removeUserFromRoom(req.user.username, room_name); let response = await this.chatService.removeUserFromRoom(req.user.username, room_name);
@@ -271,8 +262,7 @@ export class ChatController {
await socket.leave(socket.room); await socket.leave(socket.room);
res.status(HttpStatus.OK).json({ message: response }); res.status(HttpStatus.OK).json({ message: response });
printCaller("- out ");
console.log("- out leaveRoom controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -280,12 +270,11 @@ export class ChatController {
@Get('messages') @Get('messages')
async getMessages(@Req() req, @Res() res): Promise<void> async getMessages(@Req() req, @Res() res): Promise<void>
{ {
console.log("- in getMessages controller"); printCaller("- in ");
const messages = await this.chatService.getMessagesFromCurrentRoom(req.user.username); const messages = await this.chatService.getMessagesFromCurrentRoom(req.user.username);
res.status(HttpStatus.OK).json({ messages: messages }); res.status(HttpStatus.OK).json({ messages: messages });
printCaller("- out ");
console.log("- out getMessages controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -293,14 +282,13 @@ export class ChatController {
@Get('roomusers') @Get('roomusers')
async getRoomUsers(@Req() req, @Res() res): Promise<void> async getRoomUsers(@Req() req, @Res() res): Promise<void>
{ {
console.log("- in getRoomUsers controller"); printCaller("- in ");
const room_name = await this.chatService.getCurrentRoomName(req.user.username); const room_name = await this.chatService.getCurrentRoomName(req.user.username);
const room = await this.chatService.getRoomByName(room_name); const room = await this.chatService.getRoomByName(room_name);
const users = room.users; const users = room.users;
res.status(HttpStatus.OK).json({ users: users }); res.status(HttpStatus.OK).json({ users: users });
printCaller("- out ");
console.log("- out getRoomUsers controller");
} }
@UseGuards(AuthenticateGuard) @UseGuards(AuthenticateGuard)
@@ -308,13 +296,12 @@ export class ChatController {
@Get('users') @Get('users')
async getAllUsers(@Req() req, @Res() res): Promise<void> async getAllUsers(@Req() req, @Res() res): Promise<void>
{ {
console.log("- in getAllUsers controller"); printCaller("- in ");
const room_name = await this.chatService.getCurrentRoomName(req.user.username); const room_name = await this.chatService.getCurrentRoomName(req.user.username);
const users = await this.chatService.getAllUsersNotInRoom(room_name); const users = await this.chatService.getAllUsersNotInRoom(room_name);
res.status(HttpStatus.OK).json({ users: users }); res.status(HttpStatus.OK).json({ users: users });
printCaller("- out ");
console.log("- out getAllUsers controller");
} }
} }

View File

@@ -8,6 +8,7 @@ import { roomDto } from './dto/room.dto';
import { messagesDto } from './dto/messages.dto'; import { messagesDto } from './dto/messages.dto';
import { socketDto } from './dto/socket.dto'; import { socketDto } from './dto/socket.dto';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
import { printCaller } from './dev/dev_utils';
@Injectable() @Injectable()
@@ -32,7 +33,7 @@ export class ChatService {
async getMyRooms(username: string, fieldsToReturn: string[] = null): Promise<Chatroom[]> async getMyRooms(username: string, fieldsToReturn: string[] = null): Promise<Chatroom[]>
{ {
console.log("-- in getMyRooms service"); printCaller("-- in ");
const queryBuilder = this.chatroomRepository const queryBuilder = this.chatroomRepository
.createQueryBuilder('chatroom') .createQueryBuilder('chatroom')
@@ -46,36 +47,36 @@ export class ChatService {
const rooms = await queryBuilder.getMany(); const rooms = await queryBuilder.getMany();
console.log("-- out getMyRooms service"); printCaller("-- out ");
return rooms; return rooms;
} }
async getMyDirects(username: string): Promise<Chatroom[]> async getMyDirects(username: string): Promise<Chatroom[]>
{ {
console.log("-- in getAllNotMyRooms service"); printCaller("-- in ");
const my_rooms = await this.getMyRooms(username); const my_rooms = await this.getMyRooms(username);
const directs = my_rooms.filter(room => room.type === 'direct'); const directs = my_rooms.filter(room => room.type === 'direct');
console.log("-- out getAllNotMyRooms service"); printCaller("-- out ");
return directs; return directs;
} }
async getAllRooms(): Promise<Chatroom[]> async getAllRooms(): Promise<Chatroom[]>
{ {
console.log("-- in getAllRooms service"); printCaller("-- in ");
const rooms = await this.chatroomRepository const rooms = await this.chatroomRepository
.createQueryBuilder('chatroom') .createQueryBuilder('chatroom')
.getMany(); .getMany();
console.log("-- out getAllRooms service"); printCaller("-- out ");
return rooms; return rooms;
} }
async getAllNotMyRooms(username: string): Promise<Chatroom[]> async getAllNotMyRooms(username: string): Promise<Chatroom[]>
{ {
console.log("-- in getAllNotMyRooms service"); printCaller("-- in ");
const user_db = await this.getUserByName(username); const user_db = await this.getUserByName(username);
const rooms = await this.chatroomRepository const rooms = await this.chatroomRepository
@@ -84,13 +85,13 @@ export class ChatService {
.andWhere('chatroom.users NOT LIKE :user_name', { user_name: `%${username}%` }) .andWhere('chatroom.users NOT LIKE :user_name', { user_name: `%${username}%` })
.getMany(); .getMany();
console.log("-- out getAllNotMyRooms service"); printCaller("-- out ");
return rooms; return rooms;
} }
async getAllOtherRoomsAndUsers(username: string): Promise<roomDto[]> async getAllOtherRoomsAndUsers(username: string): Promise<roomDto[]>
{ {
console.log("-- in getAllOtherRoomsAndUsers service"); printCaller("-- in ");
const all_rooms = await this.getAllNotMyRooms(username); const all_rooms = await this.getAllNotMyRooms(username);
const all_users = await this.getAllUsersNotMyRooms(username); const all_users = await this.getAllUsersNotMyRooms(username);
@@ -99,23 +100,25 @@ export class ChatService {
return { return {
name: room.name, name: room.name,
type: room.type, type: room.type,
protection: room.protection,
}; };
}); });
let users = all_users.map(user => { let users = all_users.map(user => {
return { return {
name: user.username, name: user.username,
type: "user", type: "user",
protection: false,
}; };
}); });
let rooms: roomDto[] = row_rooms.concat(users); let rooms: roomDto[] = row_rooms.concat(users);
console.log("-- in getAllOtherRoomsAndUsers service"); printCaller("-- out ");
return rooms; return rooms;
} }
async getMessagesFromCurrentRoom(username: string): Promise<messagesDto[]> async getMessagesFromCurrentRoom(username: string): Promise<messagesDto[]>
{ {
console.log("-- in getMessagesFromCurrentRoom service"); printCaller("-- in ");
const user_db = await this.getUserByName(username); const user_db = await this.getUserByName(username);
const currentRoom = await this.getRoomByName(user_db.currentRoom); const currentRoom = await this.getRoomByName(user_db.currentRoom);
@@ -123,23 +126,23 @@ export class ChatService {
if (currentRoom) if (currentRoom)
messages = currentRoom.messages; messages = currentRoom.messages;
console.log("-- out getMessagesFromCurrentRoom service"); printCaller("-- out ");
return messages; return messages;
} }
async getCurrentRoomName(username: string): Promise<string> async getCurrentRoomName(username: string): Promise<string>
{ {
console.log("-- in getCurrentRoomName service"); printCaller("-- in ");
const user_db = await this.getUserByName(username); const user_db = await this.getUserByName(username);
console.log("-- out getCurrentRoomName service"); printCaller("-- out ");
return user_db.currentRoom; return user_db.currentRoom;
} }
async getRoomByName(room_name: string, fieldsToReturn: string[] = null): Promise<Chatroom> async getRoomByName(room_name: string, fieldsToReturn: string[] = null): Promise<Chatroom>
{ {
console.log("-- in getRoomByName service"); printCaller("-- in ");
const queryBuilder = this.chatroomRepository const queryBuilder = this.chatroomRepository
.createQueryBuilder('chatroom') .createQueryBuilder('chatroom')
@@ -153,20 +156,20 @@ export class ChatService {
const room = await queryBuilder.getOne(); const room = await queryBuilder.getOne();
console.log("-- out getRoomByName service"); printCaller("-- out ");
return room; return room;
} }
async getRoomById(id: number): Promise<Chatroom> async getRoomById(id: number): Promise<Chatroom>
{ {
console.log("-- in getRoomById service"); printCaller("-- in ");
const room = await this.chatroomRepository const room = await this.chatroomRepository
.createQueryBuilder('chatroom') .createQueryBuilder('chatroom')
.where('chatroom.id = :id', { id: id }) .where('chatroom.id = :id', { id: id })
.getOne(); .getOne();
console.log("-- out getRoomById service"); printCaller("-- out ");
return room; return room;
} }
@@ -176,32 +179,31 @@ export class ChatService {
async setCurrentRoom(username: string, room_name: string): Promise<string> async setCurrentRoom(username: string, room_name: string): Promise<string>
{ {
console.log("-- in setCurrentRoom service"); printCaller("-- in ");
const user_db = await this.getUserByName(username); const user_db = await this.getUserByName(username);
user_db.currentRoom = room_name; user_db.currentRoom = room_name;
await this.userRepository.save(user_db); await this.userRepository.save(user_db);
console.log("-- out setCurrentRoom service"); printCaller("-- out ");
return `room "${room_name}" is now current room`; return `room "${room_name}" is now current room`;
} }
async setPasswordValidation(username: string, room: roomDto): Promise<void> async setPasswordValidation(username: string, room: roomDto): Promise<void>
{ {
console.log("-- in setPasswordValidation service"); printCaller("-- in ");
const room_db = await this.getRoomByName(room.name); const room_db = await this.getRoomByName(room.name);
const is_match = await bcrypt.compare(room.password, room_db.hash); const is_match = await bcrypt.compare(room.password, room_db.hash);
if (!is_match) if (!is_match)
{ {
console.log(`throw error: display: true, code: 'BAD_PASSWORD', message: 'bad password'`); console.log(`throw error: error: true, code: 'BAD_PASSWORD', message: 'bad password'`);
throw new HttpException({ display: true, code: 'BAD_PASSWORD', message: `bad password` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'BAD_PASSWORD', message: `bad password` }, HttpStatus.BAD_REQUEST);
} }
room_db.allowed_users.push(username); room_db.allowed_users.push(username);
printCaller("-- out ");
await this.chatroomRepository.save(room_db); await this.chatroomRepository.save(room_db);
console.log("-- out setPasswordValidation service");
} }
@@ -210,13 +212,13 @@ export class ChatService {
async addUserToNewRoom(username: string, room: roomDto): Promise<void> async addUserToNewRoom(username: string, room: roomDto): Promise<void>
{ {
console.log("-- in addUserToNewRoom service"); printCaller("-- in ");
const find_room = await this.getRoomByName(room.name); const find_room = await this.getRoomByName(room.name);
if (find_room) if (find_room)
{ {
console.log("throw error: display: true, code: 'ROOM_CONFLICT', message: 'This room name already exist'"); console.log("throw error: error: true, code: 'ROOM_CONFLICT', message: 'This room name already exist'");
throw new HttpException({ display: true, code: 'ROOM_CONFLICT', message: `This room name already exist` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'ROOM_CONFLICT', message: `This room name already exist` }, HttpStatus.OK);
} }
let hash; let hash;
@@ -225,8 +227,8 @@ export class ChatService {
console.log("in room protection hash"); console.log("in room protection hash");
if (room.type === 'direct') if (room.type === 'direct')
{ {
console.log("throw error: display: true, code: 'DIRECT_PASSWORD_FORBIDDEN', message: 'you cannot set a password in a direct message room'"); console.log("throw error: error: true, code: 'DIRECT_PASSWORD_FORBIDDEN', message: 'you cannot set a password in a direct message room'");
throw new HttpException({ display: true, code: 'DIRECT_PASSWORD_FORBIDDEN', message: `you cannot set a password in a direct message room`}, HttpStatus.OK); throw new HttpException({ error: true, code: 'DIRECT_PASSWORD_FORBIDDEN', message: `you cannot set a password in a direct message room`}, HttpStatus.OK);
} }
const saltOrRounds = 10; const saltOrRounds = 10;
const password = room.password; const password = room.password;
@@ -240,6 +242,7 @@ export class ChatService {
newChatroom.owner = username; newChatroom.owner = username;
newChatroom.users = room.users; newChatroom.users = room.users;
newChatroom.allowed_users = []; newChatroom.allowed_users = [];
newChatroom.protection = room.protection;
if (room.protection) if (room.protection)
{ {
newChatroom.hash = hash; newChatroom.hash = hash;
@@ -251,13 +254,12 @@ export class ChatService {
{ name: "SERVER", message: `${room.users[0]} joined the room` }, { name: "SERVER", message: `${room.users[0]} joined the room` },
]; ];
await this.chatroomRepository.save(newChatroom); await this.chatroomRepository.save(newChatroom);
printCaller("-- out ");
console.log("-- out addUserToNewRoom service");
} }
async addUserToRoom(username: string, room_name: string): Promise<roomDto> async addUserToRoom(username: string, room_name: string): Promise<roomDto>
{ {
console.log("-- in addUserToRoom service"); printCaller("-- in ");
const room = await this.getRoomByName(room_name); const room = await this.getRoomByName(room_name);
@@ -265,13 +267,13 @@ export class ChatService {
room.users.push(username); room.users.push(username);
await this.chatroomRepository.save(room); await this.chatroomRepository.save(room);
console.log("-- out addUserToRoom service"); printCaller("-- out ");
return room; return room;
} }
async addMessageToRoom(room_name: string, username: string, message: string): Promise<void> async addMessageToRoom(room_name: string, username: string, message: string): Promise<void>
{ {
console.log("-- in addMessageToRoom service"); printCaller("-- in ");
const my_room = await this.getRoomByName(room_name); const my_room = await this.getRoomByName(room_name);
let chat_message: messagesDto = { let chat_message: messagesDto = {
@@ -279,9 +281,9 @@ export class ChatService {
message: message, message: message,
}; };
my_room.messages.push(chat_message); my_room.messages.push(chat_message);
await this.chatroomRepository.save(my_room);
console.log("-- out addMessageToRoom service"); printCaller("-- out ");
await this.chatroomRepository.save(my_room);
} }
@@ -290,18 +292,18 @@ export class ChatService {
async removeUserFromRoom(username: string, room_name: string): Promise<string> async removeUserFromRoom(username: string, room_name: string): Promise<string>
{ {
console.log("-- in removeUserFromRoom service"); printCaller("-- in ");
const room = await this.getRoomByName(room_name); const room = await this.getRoomByName(room_name);
if (!room.users.includes(username)) if (!room.users.includes(username))
{ {
console.log("throw error: display: true, code: 'USER_NOT_FOUND', message: 'your are not in this room'"); console.log("throw error: error: true, code: 'USER_NOT_FOUND', message: 'your are not in this room'");
throw new HttpException({ display: true, code: 'USER_NOT_FOUND', message: `your are not in this room` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'USER_NOT_FOUND', message: `your are not in this room` }, HttpStatus.OK);
} }
if (room.type === "direct") if (room.type === "direct")
{ {
console.log("throw error: display: true, code: 'LEAVE_DIRECY_FORBIDDEN', message: 'you cannot leave a direct messages conversation'"); console.log("throw error: error: true, code: 'LEAVE_DIRECY_FORBIDDEN', message: 'you cannot leave a direct messages conversation'");
throw new HttpException({ display: true, code: 'LEAVE_DIRECY_FORBIDDEN', message: `you cannot leave a direct messages conversation` }, HttpStatus.OK); throw new HttpException({ error: true, code: 'LEAVE_DIRECY_FORBIDDEN', message: `you cannot leave a direct messages conversation` }, HttpStatus.OK);
} }
// delete user from room // delete user from room
@@ -309,7 +311,7 @@ export class ChatService {
room.users = room.users.filter(name => name !== username); room.users = room.users.filter(name => name !== username);
await this.chatroomRepository.save(room); await this.chatroomRepository.save(room);
console.log("-- out removeUserFromRoom service"); printCaller("-- out ");
return "successfully leaving room"; return "successfully leaving room";
} }
@@ -319,20 +321,20 @@ export class ChatService {
async getUserByName(username: string): Promise<User> async getUserByName(username: string): Promise<User>
{ {
console.log("-- in getUserByName service"); printCaller("-- in ");
const user = await this.userRepository const user = await this.userRepository
.createQueryBuilder('user') .createQueryBuilder('user')
.where('user.username = :name', { name: username }) .where('user.username = :name', { name: username })
.getOne(); .getOne();
console.log("-- out getUserByName service"); printCaller("-- out ");
return user; return user;
} }
async getAllUsersNotMyRooms(username: string): Promise<User[]> async getAllUsersNotMyRooms(username: string): Promise<User[]>
{ {
console.log("-- in getAllUsersNotMyRooms service"); printCaller("-- in ");
const directs = await this.getMyDirects(username); const directs = await this.getMyDirects(username);
@@ -350,13 +352,13 @@ export class ChatService {
.where('user.username NOT IN (:...usernames)', { usernames: usernames }) .where('user.username NOT IN (:...usernames)', { usernames: usernames })
.getMany(); .getMany();
console.log("-- out getAllUsersNotMyRooms service"); printCaller("-- out ");
return users; return users;
} }
async getAllUsersNotInRoom(current_room_name: string): Promise<User[]> async getAllUsersNotInRoom(current_room_name: string): Promise<User[]>
{ {
console.log("-- in getAllUsersNotInRoom service"); printCaller("-- in ");
// get all users in current room // get all users in current room
const current_room = await this.getRoomByName(current_room_name); const current_room = await this.getRoomByName(current_room_name);
@@ -367,7 +369,7 @@ export class ChatService {
.where('user.username NOT IN (:...usernames)', { usernames: usernames }) .where('user.username NOT IN (:...usernames)', { usernames: usernames })
.getMany(); .getMany();
console.log("-- out getAllUsersNotInRoom service"); printCaller("-- out ");
return users; return users;
} }
@@ -377,29 +379,29 @@ export class ChatService {
async socketIncommingMessage(socket: socketDto, message: string): Promise<void> async socketIncommingMessage(socket: socketDto, message: string): Promise<void>
{ {
console.log("-- in handleSocketIncommingMessage service"); printCaller("-- in ");
socket.to(socket.room).emit('message', socket.username, message); socket.to(socket.room).emit('message', socket.username, message);
let room_name = await this.getCurrentRoomName(socket.username); let room_name = await this.getCurrentRoomName(socket.username);
await this.addMessageToRoom(room_name, socket.username, message); await this.addMessageToRoom(room_name, socket.username, message);
console.log("-- out handleSocketIncommingMessage service"); printCaller("-- out ");
} }
async socketChangeRoom(socket: socketDto, room_name: string): Promise<void> async socketChangeRoom(socket: socketDto, room_name: string): Promise<void>
{ {
console.log('-- in socketChangeRoom service'); printCaller("-- in ");
socket.leave(socket.room); socket.leave(socket.room);
socket.join(room_name); socket.join(room_name);
socket.room = room_name; socket.room = room_name;
console.log('-- out socketChangeRoom service'); printCaller("-- out ");
} }
async socketJoinRoom(socket: socketDto, room_name: string): Promise<void> async socketJoinRoom(socket: socketDto, room_name: string): Promise<void>
{ {
console.log('-- in socketJoinRoom service'); printCaller("-- in ");
socket.leave(socket.room); socket.leave(socket.room);
socket.join(room_name); socket.join(room_name);
@@ -408,7 +410,7 @@ export class ChatService {
await socket.to(socket.room).emit('message', "SERVER", message); await socket.to(socket.room).emit('message', "SERVER", message);
await this.addMessageToRoom(room_name, "SERVER", message); await this.addMessageToRoom(room_name, "SERVER", message);
console.log('-- out socketJoinRoom service'); printCaller("-- out ");
} }
} }

View File

@@ -0,0 +1,13 @@
export function printCaller(prefix: string = "") {
try
{
throw new Error();
}
catch (e)
{
Error.captureStackTrace(e);
let stack = e.stack.split('\n');
let caller = stack[2].trim();
console.log(prefix + caller);
}
}

View File

@@ -17,8 +17,7 @@ export class roomDto
type: string; type: string;
@IsBoolean() @IsBoolean()
@IsOptional() protection: boolean;
protection?: boolean = false;
@IsString() @IsString()
@IsOptional() @IsOptional()

View File

@@ -30,8 +30,8 @@
*/ */
function set_layouts($layout) function set_layouts($layout)
{ {
console.log("layouts:", layouts); //console.log("layouts:", layouts);
console.log("layout:", $layout); //console.log("layout:", $layout);
if ($layout.length === 0) if ($layout.length === 0)
layout.set(layouts[0]); layout.set(layouts[0]);
else if ($layout === "close") else if ($layout === "close")
@@ -42,7 +42,7 @@
layouts = [$layout, "home"]; layouts = [$layout, "home"];
else else
layouts = [$layout, layouts[0]]; layouts = [$layout, layouts[0]];
console.log("- layouts:", layouts); //console.log("- layouts:", layouts);
} }
$: set_layouts($layout); $: set_layouts($layout);

View File

@@ -14,7 +14,6 @@
onMount(async() => { onMount(async() => {
let response = await fetch('/api/v2/chat/allowedchars'); let response = await fetch('/api/v2/chat/allowedchars');
let data = await response.json(); let data = await response.json();
console.log("data:", data);
allowed_chars = data.chars; allowed_chars = data.chars;
//regex = new RegExp(`^[a-zA-Z0-9\\s${allowed_chars}]+$`); //regex = new RegExp(`^[a-zA-Z0-9\\s${allowed_chars}]+$`);
}); });
@@ -40,12 +39,14 @@
}; };
if (is_protected === true) if (is_protected === true)
room.password = room_password; room.password = room_password;
// send the new room // send the new room
response = await create_room(room); response = await create_room(room);
show_error = response.display;
// go to room // go to room
if (response.status === 200) if (response.error)
show_error = response.error;
else
await change_room(response.room); await change_room(response.room);
} }

View File

@@ -1,6 +1,6 @@
<script> <script>
import { layout, msgs, user } from './Store_chat'; import { layout, msgs, user, current_room } from './Store_chat';
import { change_room, get_room_messages, get_my_rooms } from './Request_rooms'; import { change_room, get_room_messages, get_my_rooms } from './Request_rooms';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import Button from './Element_button.svelte'; import Button from './Element_button.svelte';
@@ -12,10 +12,17 @@
{ {
console.log("inside go_to_room"); console.log("inside go_to_room");
console.log("room:", room); if (room.protection)
{
await current_room.set(room);
layout.set("protected");
}
else
{
await change_room(room); await change_room(room);
await get_room_messages(); await get_room_messages();
} }
}
</script> </script>

View File

@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { layout, user, current_room_name } from './Store_chat'; import { layout, user, current_room } from './Store_chat';
import { get_all_users, invite_user } from './Request_rooms'; import { get_all_users, invite_user } from './Request_rooms';
import Button from './Element_button.svelte'; import Button from './Element_button.svelte';
@@ -38,7 +38,7 @@
<!-- room_name --> <!-- room_name -->
<Button my_class="room_name deactivate __border_top"> <Button my_class="room_name deactivate __border_top">
{$current_room_name} {$current_room.name}
</Button> </Button>
<!-- panel_new --> <!-- panel_new -->

View File

@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { layout, msgs, user, socket } from './Store_chat'; import { layout, msgs, user, socket, current_room } from './Store_chat';
import { join_room, change_room, get_room_messages, get_all_rooms } from './Request_rooms'; import { join_room, change_room, get_room_messages, get_all_rooms } from './Request_rooms';
import Button from './Element_button.svelte'; import Button from './Element_button.svelte';
@@ -13,11 +13,12 @@
{ {
console.log("inside join_room"); console.log("inside join_room");
console.log("room:", room);
const updated_room = await join_room(room); const updated_room = await join_room(room);
console.log("updated room:", updated_room); if (updated_room.protection)
if (room.protection) {
current_room.set(updated_room);
layout.set("protected"); layout.set("protected");
}
else else
await change_room(updated_room); await change_room(updated_room);
} }

View File

@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { layout, current_room_name, current_room_type } from './Store_chat'; import { layout, current_room } from './Store_chat';
import { change_room, send_password } from './Request_rooms'; import { change_room, send_password } from './Request_rooms';
import { FetchResponse } from './Types_chat'; import { FetchResponse } from './Types_chat';
import Button from './Element_button.svelte'; import Button from './Element_button.svelte';
@@ -14,23 +14,27 @@
async function handleSubmit(evt) async function handleSubmit(evt)
{ {
console.log("in handleSubmit");
let formIsValid = evt.target.checkValidity(); let formIsValid = evt.target.checkValidity();
if (!formIsValid) if (!formIsValid)
return; return;
let room = { let room = {
name: current_room_name, name: $current_room.name,
type: current_room_type, type: $current_room.type,
protection: true,
password: room_password, password: room_password,
}; };
// send password // send password
response = await send_password(room); response = await send_password(room);
show_error = response.display;
// go to room // go to room
if (response.status === 200) if (response.error)
show_error = response.error;
else
await change_room(response.room); await change_room(response.room);
} }
@@ -56,12 +60,6 @@
<!-- panel_protected --> <!-- panel_protected -->
<div class="panel panel_protected __border_top"> <div class="panel panel_protected __border_top">
<p class="title __center">this room is protected</p> <p class="title __center">this room is protected</p>
<form>
<label for="chat_pswd"><p>password :</p></label>
<input id="chat_pswd" type="password" required>
<input type="submit" value="&#x2BA1">
</form>
<form on:submit|preventDefault={handleSubmit}> <form on:submit|preventDefault={handleSubmit}>
{#if show_error} {#if show_error}
<Warning content={response.message}/> <Warning content={response.message}/>
@@ -70,11 +68,8 @@
<input id="chat_pswd" bind:value={room_password} type="password" placeholder="minimum 8 characters" minlength="8" name="password" required> <input id="chat_pswd" bind:value={room_password} type="password" placeholder="minimum 8 characters" minlength="8" name="password" required>
<input type="submit" value="&#x2BA1"> <input type="submit" value="&#x2BA1">
</form> </form>
</div> </div>
</div> </div>
<style> <style>

View File

@@ -1,6 +1,6 @@
<script> <script>
import { layout, socket, msgs, add_msg, current_room_name } from './Store_chat'; import { layout, socket, msgs, add_msg, current_room } from './Store_chat';
import Button from './Element_button.svelte'; import Button from './Element_button.svelte';
import Msg from './Element_msg.svelte'; import Msg from './Element_msg.svelte';
@@ -42,7 +42,7 @@
<!-- room_name --> <!-- room_name -->
<Button new_layout="room_set" my_class="room_name transparent"> <Button new_layout="room_set" my_class="room_name transparent">
{$current_room_name} {$current_room.name}
</Button> </Button>
<!-- close --> <!-- close -->

View File

@@ -1,6 +1,6 @@
<script> <script>
import { layout, current_room_name, current_room_type } from './Store_chat'; import { layout, current_room } from './Store_chat';
import { get_room_users, leave_room } from './Request_rooms'; import { get_room_users, leave_room } from './Request_rooms';
import Button from './Element_button.svelte'; import Button from './Element_button.svelte';
@@ -31,7 +31,7 @@
<!-- room_name --> <!-- room_name -->
<Button my_class="room_name deactivate"> <Button my_class="room_name deactivate">
{$current_room_name} {$current_room.name}
</Button> </Button>
<!-- close --> <!-- close -->
@@ -41,7 +41,7 @@
<!-- panel_room_set --> <!-- panel_room_set -->
<div class="panel panel_room_set __border_top"> <div class="panel panel_room_set __border_top">
{#if $current_room_type !== "direct"} {#if $current_room.type !== "direct"}
<Button on_click={user_leave_room}> <Button on_click={user_leave_room}>
leave leave
</Button> </Button>

View File

@@ -1,4 +1,4 @@
import { msgs, user, layout, socket, current_room_name, current_room_type } from './Store_chat'; import { msgs, user, layout, socket, current_room } from './Store_chat';
import { Room, FetchResponse, FetchMethod } from './Types_chat'; import { Room, FetchResponse, FetchMethod } from './Types_chat';
import { fetch_chat_request, set_client_name_on_room, fill_fetch_response } from './Request_utils'; import { fetch_chat_request, set_client_name_on_room, fill_fetch_response } from './Request_utils';
@@ -26,7 +26,9 @@ export async function create_room(room: Room)
{ {
console.log("in create_room"); console.log("in create_room");
console.log("room sent to create:", room);
let response: FetchResponse = await fetch_chat_request('create', FetchMethod.POST, room); let response: FetchResponse = await fetch_chat_request('create', FetchMethod.POST, room);
console.log("room returned from create:", response.room);
return response; return response;
} }
@@ -35,7 +37,9 @@ export async function join_room(room: Room)
{ {
console.log("in join_room"); console.log("in join_room");
console.log("room sent to join:", room);
let response: FetchResponse = await fetch_chat_request('join', FetchMethod.POST, room); let response: FetchResponse = await fetch_chat_request('join', FetchMethod.POST, room);
console.log("room returned from join:", response.room);
return response.room; return response.room;
} }
@@ -44,14 +48,15 @@ export async function change_room(room: Room)
{ {
console.log("in change_room"); console.log("in change_room");
await fetch_chat_request('change', FetchMethod.POST, room); console.log("room sent to change:", room);
let response: FetchResponse = await fetch_chat_request('change', FetchMethod.POST, room);
console.log("room returned from change:", response.room);
await get_room_messages(); await get_room_messages();
set_client_name_on_room(room); set_client_name_on_room(room);
current_room_name.set(room.client_name); current_room.set(room);
current_room_type.set(room.type);
layout.set("room"); layout.set("room");
} }
@@ -60,7 +65,9 @@ export async function send_password(room: Room)
{ {
console.log("in send_password"); console.log("in send_password");
console.log("room sent to set password:", room);
let response: FetchResponse = await fetch_chat_request('password', FetchMethod.POST, room); let response: FetchResponse = await fetch_chat_request('password', FetchMethod.POST, room);
console.log("room returned from set password:", response.room);
return response; return response;
} }

View File

@@ -3,6 +3,8 @@ import { Room, FetchResponse, FetchInit, FetchMethod } from './Types_chat';
export async function fetch_chat_request(route: string, fetchMethod: FetchMethod, param?: any) export async function fetch_chat_request(route: string, fetchMethod: FetchMethod, param?: any)
{ {
console.log("in fetch_chat_request");
let response: FetchResponse = { status: 0 }; let response: FetchResponse = { status: 0 };
let fetch_params: FetchInit = { let fetch_params: FetchInit = {
@@ -12,30 +14,31 @@ export async function fetch_chat_request(route: string, fetchMethod: FetchMethod
if (param) if (param)
fetch_params.body = JSON.stringify(param); fetch_params.body = JSON.stringify(param);
try { try
{
const resp = await fetch(`/api/v2/chat/${route}`, fetch_params); const resp = await fetch(`/api/v2/chat/${route}`, fetch_params);
response.status = resp.status; response.status = resp.status;
if (!resp.ok)
throw new Error(resp.statusText);
let data = await resp.json(); let data = await resp.json();
fill_fetch_response(response, data); fill_fetch_response(response, data);
if (!resp.ok)
throw new Error(data.message);
} }
catch (error) catch (error)
{ {
console.error('Error', error); console.error(error.message);
} }
console.log("response:", response);
return response; return response;
} }
export function set_client_name_on_room(room: Room) export function set_client_name_on_room(room: Room)
{ {
console.log("in set_client_name_on_room, for room:", room); console.log("in set_client_name_on_room");
if (room.type === 'direct') if (room.type === 'direct')
{ {
console.log("in direct room");
room.client_name = room.users[0]; room.client_name = room.users[0];
if (room.client_name === user.username) if (room.client_name === user.username)
room.client_name = room.users[1]; room.client_name = room.users[1];
@@ -47,11 +50,10 @@ export function set_client_name_on_room(room: Room)
export function fill_fetch_response(response: FetchResponse, data: any) export function fill_fetch_response(response: FetchResponse, data: any)
{ {
console.log("data:", data); console.log("in fill_fetch_response");
Object.keys(data).forEach(key => Object.keys(data).forEach(key =>
{ {
console.log(key)
response[key] = data[key]; response[key] = data[key];
}); });
console.log(response);
} }

View File

@@ -1,9 +1,13 @@
import { writable } from 'svelte/store'; import { writable } from 'svelte/store';
import { Room } from './Types_chat';
export let msgs = writable([]); export let msgs = writable([]);
export let layout = writable("close"); export let layout = writable("close");
export let current_room_name = writable(""); export let current_room: Room = writable({
export let current_room_type = writable(""); name: "",
type: "",
protection: false,
});
export let user; export let user;
export let socket; export let socket;

View File

@@ -1,17 +1,17 @@
export interface Room export interface Room
{ {
name: string; name: string;
type: "public" | "protected" | "private" | "direct" | "user"; type: "public" | "private" | "direct" | "user";
users?: string[]; users?: string[];
client_name?: string; client_name?: string;
protection?: boolean; protection: boolean;
} }
export interface FetchResponse export interface FetchResponse
{ {
status: number; status: number;
error?: boolean;
code?: string; code?: string;
display?: boolean;
message?: string; message?: string;
room?: Room; room?: Room;
} }