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

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
<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 { onMount } from 'svelte';
import Button from './Element_button.svelte';
@@ -12,9 +12,16 @@
{
console.log("inside go_to_room");
console.log("room:", room);
await change_room(room);
await get_room_messages();
if (room.protection)
{
await current_room.set(room);
layout.set("protected");
}
else
{
await change_room(room);
await get_room_messages();
}
}
</script>

View File

@@ -1,6 +1,6 @@
<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 Button from './Element_button.svelte';
@@ -38,7 +38,7 @@
<!-- room_name -->
<Button my_class="room_name deactivate __border_top">
{$current_room_name}
{$current_room.name}
</Button>
<!-- panel_new -->

View File

@@ -1,6 +1,6 @@
<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 Button from './Element_button.svelte';
@@ -13,11 +13,12 @@
{
console.log("inside join_room");
console.log("room:", room);
const updated_room = await join_room(room);
console.log("updated room:", updated_room);
if (room.protection)
if (updated_room.protection)
{
current_room.set(updated_room);
layout.set("protected");
}
else
await change_room(updated_room);
}

View File

@@ -1,6 +1,6 @@
<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 { FetchResponse } from './Types_chat';
import Button from './Element_button.svelte';
@@ -14,23 +14,27 @@
async function handleSubmit(evt)
{
console.log("in handleSubmit");
let formIsValid = evt.target.checkValidity();
if (!formIsValid)
return;
let room = {
name: current_room_name,
type: current_room_type,
name: $current_room.name,
type: $current_room.type,
protection: true,
password: room_password,
};
// send password
response = await send_password(room);
show_error = response.display;
// go to room
if (response.status === 200)
if (response.error)
show_error = response.error;
else
await change_room(response.room);
}
@@ -56,12 +60,6 @@
<!-- panel_protected -->
<div class="panel panel_protected __border_top">
<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}>
{#if show_error}
<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 type="submit" value="&#x2BA1">
</form>
</div>
</div>
<style>

View File

@@ -1,6 +1,6 @@
<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 Msg from './Element_msg.svelte';
@@ -42,7 +42,7 @@
<!-- room_name -->
<Button new_layout="room_set" my_class="room_name transparent">
{$current_room_name}
{$current_room.name}
</Button>
<!-- close -->

View File

@@ -1,6 +1,6 @@
<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 Button from './Element_button.svelte';
@@ -31,7 +31,7 @@
<!-- room_name -->
<Button my_class="room_name deactivate">
{$current_room_name}
{$current_room.name}
</Button>
<!-- close -->
@@ -41,7 +41,7 @@
<!-- panel_room_set -->
<div class="panel panel_room_set __border_top">
{#if $current_room_type !== "direct"}
{#if $current_room.type !== "direct"}
<Button on_click={user_leave_room}>
leave
</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 { 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("room sent to create:", room);
let response: FetchResponse = await fetch_chat_request('create', FetchMethod.POST, room);
console.log("room returned from create:", response.room);
return response;
}
@@ -35,7 +37,9 @@ export async function join_room(room: Room)
{
console.log("in join_room");
console.log("room sent to join:", room);
let response: FetchResponse = await fetch_chat_request('join', FetchMethod.POST, room);
console.log("room returned from join:", response.room);
return response.room;
}
@@ -44,14 +48,15 @@ export async function change_room(room: 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();
set_client_name_on_room(room);
current_room_name.set(room.client_name);
current_room_type.set(room.type);
current_room.set(room);
layout.set("room");
}
@@ -60,7 +65,9 @@ export async function send_password(room: Room)
{
console.log("in send_password");
console.log("room sent to set password:", room);
let response: FetchResponse = await fetch_chat_request('password', FetchMethod.POST, room);
console.log("room returned from set password:", response.room);
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)
{
console.log("in fetch_chat_request");
let response: FetchResponse = { status: 0 };
let fetch_params: FetchInit = {
@@ -12,30 +14,31 @@ export async function fetch_chat_request(route: string, fetchMethod: FetchMethod
if (param)
fetch_params.body = JSON.stringify(param);
try {
try
{
const resp = await fetch(`/api/v2/chat/${route}`, fetch_params);
response.status = resp.status;
if (!resp.ok)
throw new Error(resp.statusText);
let data = await resp.json();
fill_fetch_response(response, data);
if (!resp.ok)
throw new Error(data.message);
}
catch (error)
{
console.error('Error', error);
console.error(error.message);
}
console.log("response:", response);
return response;
}
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')
{
console.log("in direct room");
room.client_name = room.users[0];
if (room.client_name === user.username)
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)
{
console.log("data:", data);
console.log("in fill_fetch_response");
Object.keys(data).forEach(key =>
{
console.log(key)
response[key] = data[key];
});
console.log(response);
}

View File

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

View File

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