Merge branch 'cherif_back_and_game' into luke

This commit is contained in:
LuckyLaszlo
2022-12-21 20:19:11 +01:00
28 changed files with 1834 additions and 1012 deletions

View File

@@ -1,4 +1,5 @@
NODE_ENV=development
WEBSITE_HOST=transcendance
POSTGRES_USER=postgres
POSTGRES_PASSWORD=9pKpKEgiamxwk5P7Ggsz
POSTGRES_DB=transcendance_db

View File

@@ -232,7 +232,6 @@ export class GameSession {
client.socket.send(JSON.stringify(eventEnd));
});
/* // WIP nest , send match result
const gc = this.components;
await fetch(c.addressBackEnd + "/game/matchEnd",
{
@@ -241,11 +240,11 @@ export class GameSession {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: this.id,
scoreLeft: gc.scoreLeft,
scoreRight: gc.scoreRight,
gameServerIdOfTheMatch: this.id,
playerOneUsernameResult: gc.scoreLeft,
playerTwoUsernameResult: gc.scoreRight,
})
}); */
});
// logs
if (winner === en.PlayerSide.left) {

View File

@@ -9,4 +9,4 @@ export const fixedDeltaTime = serverGameLoopIntervalMS/1000; // second
export const playersUpdateIntervalMS = 1000/30; // millisecond
export const spectatorsUpdateIntervalMS = 1000/30; // millisecond
export const addressBackEnd = "http://backend_dev:3000";
export const addressBackEnd = "http://backend_dev:3000/api/v2";

View File

@@ -78,7 +78,7 @@ async function clientAnnounceListener(this: WebSocket, data: string)
if (announce.privateMatch) {
body.playerTwoUsername = announce.playerTwoUsername;
}
const response = await fetch(c.addressBackEnd + "/game/validateToken",
const response = await fetch(c.addressBackEnd + "/game/gameserver/validate",
{
method: "POST",
headers: {
@@ -168,7 +168,7 @@ function privateMatchmaking(player: ClientPlayer)
const maxPlayersNumber = 2;
privateMatchmakingMap.set(player.id, player);
const matchOptions = player.matchOptions;
console.log(player)
const token = player.token;
const compatiblePlayers: ClientPlayer[] = [];
for (const [id, client] of privateMatchmakingMap)
@@ -243,17 +243,20 @@ async function playerReadyConfirmationListener(this: WebSocket, data: string)
{
// WIP nest , send gameSession.id
const gameSessionPlayersIterator = gameSession.playersMap.values();
const response = await fetch(c.addressBackEnd + "/game/newGameSession",
const response = await fetch(c.addressBackEnd + "/game/gameserver/creategame",
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: gameSession.id,
gameServerIdOfTheMatch : gameSession.id,
gameOptions: gameSession.matchOptions,
playerOneUsername: (<ClientPlayer>gameSessionPlayersIterator.next().value).username,
playerTwoUsername: (<ClientPlayer>gameSessionPlayersIterator.next().value).username,
playerOneUsernameResult : 0,
playerTwoUsernameResult : 0
})
});
if (!response.ok)

View File

@@ -20,3 +20,6 @@ REDIS_PORT=6379
REDIS_PASSWORD=1a5e04138b91b3d683c708e4689454c2
#2fa
TWO_FACTOR_AUTHENTICATION_APP_NAME=Transcendance
NAME_OF_REDIS_DB = tokenGameDatabase
TICKET_FOR_PLAYING_GAME_SECRET = a2aef785c388497f5fca18f9ccff37ed

File diff suppressed because it is too large Load Diff

View File

@@ -7,13 +7,14 @@ import { ConfigModule } from '@nestjs/config';
import { FriendshipsModule } from './friendship/friendships.module';
import { AuthenticationModule } from './auth/42/authentication.module';
import { PassportModule } from '@nestjs/passport';
// import { GameModule } from './game/game/game.module';
import { GameModule } from './game/game.module';
@Module({
imports: [UsersModule,
AuthenticationModule,
PassportModule.register({ session: true }),
FriendshipsModule,
GameModule,
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: 'postgres',
@@ -27,7 +28,6 @@ import { PassportModule } from '@nestjs/passport';
//avec une classe pour le module
synchronize: true,
}),
// GameModule,
],
controllers: [AppController],
providers: [AppService],

View File

@@ -1,16 +0,0 @@
import { IsBoolean, IsEmail, IsNotEmpty, IsString } from 'class-validator';
export class CreateUsersDto {
@IsString()
@IsNotEmpty()
readonly username: string;
readonly fortyTwoId: string;
@IsEmail()
readonly email: string;
@IsString()
readonly image_url: string;
@IsString()
readonly status: string;
@IsBoolean()
readonly isEnabledTwoFactorAuth: boolean;
}

View File

@@ -0,0 +1,19 @@
import { IsBoolean, IsNotEmpty, IsNumber, IsString } from "class-validator";
export class CreateGameDto {
@IsString()
@IsNotEmpty()
gameServerIdOfTheMatch : string
@IsNumber()
@IsNotEmpty()
gameOptions: number
@IsString()
@IsNotEmpty()
playerOneUsername : string
@IsString()
playerTwoUsername : string
@IsNumber()
playerTwoUsernameResult : number
@IsNumber()
playerOneUsernameResult : number
}

View File

@@ -0,0 +1,14 @@
import { IsBoolean, IsEmpty, IsInt, IsNotEmpty, IsNumber, IsString } from "class-validator";
import { IsNull } from "typeorm";
export class GrantTicketDto {
@IsString()
@IsNotEmpty()
playerOneUsername : string
@IsString()
playerTwoUsername : string
@IsNumber()
gameOptions : number
@IsBoolean()
isGameIsWithInvitation : boolean
}

View File

@@ -0,0 +1,5 @@
import { OmitType } from "@nestjs/mapped-types";
import { IsBoolean, IsNotEmpty, IsNumber, IsString } from "class-validator";
import { CreateGameDto } from "./createGame.dto";
export class UpdateGameDto extends OmitType(CreateGameDto, ['playerOneUsername', 'playerTwoUsername', 'gameOptions'] as const){}

View File

@@ -0,0 +1,16 @@
import { IsBase64, IsBoolean, IsEmpty, IsNotEmpty, IsNumber, IsString } from "class-validator";
export class ValidateTicketDto {
@IsString()
@IsNotEmpty()
playerOneUsername : string
@IsString()
playerTwoUsername : string
@IsNumber()
gameOptions : number
@IsBoolean()
isGameIsWithInvitation : boolean
@IsBase64()
@IsNotEmpty()
token : string
}

View File

@@ -0,0 +1,25 @@
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity('game')
export class Game {
@PrimaryGeneratedColumn()
id: number;
@Column()
playerOneUsername: string
@Column()
playerTwoUsername: string
@Column({default : 0, nullable : true})
playerOneUsernameResult : number
@Column({default : 0, nullable : true})
playerTwoUsernameResult : number
@Column({unique : true})
gameServerIdOfTheMatch: string
@Column({default: false, nullable : true}) //éric pourra trouver un meilleur mot : ongoing ?
isMatchIsFinished: boolean
}

View File

@@ -0,0 +1,22 @@
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity('tokenGame')
export class TokenGame {
@PrimaryGeneratedColumn()
id: number;
@Column()
playerOneUsername : string
@Column({nullable: true})
playerTwoUsername : string
@Column()
gameOptions : number
@Column()
isGameIsWithInvitation : boolean
@Column({default: 0, nullable: true})
numberOfRegisteredUser : number
@Column({default : false})
isSecondUserAcceptedRequest : boolean
@Column()
token : string
}

View File

@@ -1,22 +0,0 @@
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity('gameParty')
export class gameParty {
@PrimaryGeneratedColumn()
id: number;
@Column()
playerOne: string
@Column()
playerTwo: string
@Column()
resultOfTheMatch: string
@Column()
gameServerIdOfTheMatch: string
}

View File

@@ -1,4 +1,107 @@
import { Controller } from '@nestjs/common';
import { Body, Controller, Get, HttpException, HttpStatus, Post, Req, UseGuards } from '@nestjs/common';
import { Console } from 'console';
import { request } from 'http';
import { use } from 'passport';
import { AuthenticateGuard, TwoFactorGuard } from 'src/auth/42/guards/42guards';
import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
import { CreateGameDto } from './dto/createGame.dto';
import { GrantTicketDto } from './dto/grantTicket.dto';
import { UpdateGameDto } from './dto/updateGame.dto';
import { ValidateTicketDto } from './dto/validateTicket.dto';
import { TokenGame } from './entity/tokenGame.entity';
import { GameService } from './game.service';
@Controller('game')
export class GameController {}
export class GameController {
constructor (private readonly gameService : GameService) { }
@Get('ranking')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async getRankingForAllUsers(@Req() req)
{
const currentUser : User = req.user
return this.gameService.getRankingForAllUsers(currentUser);
}
@Post('ticket')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async grantTicket(@Req() req, @Body() grantTicketDto : GrantTicketDto)
{
const user : User = req.user
if (grantTicketDto.playerOneUsername != user.username)
return new HttpException('You can\'t request a game for another person.', 403 )
// else if (user.status !== "connected")
// return new HttpException('You must not be in game...', HttpStatus.FORBIDDEN )
return this.gameService.generateToken(user, grantTicketDto);
}
@Post('requested')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async requestIfAnotherUserHasRespondToquestForGame(@Req() req, @Body('token') token)
{
const user : User = req.user;
return this.gameService.requestIfAnotherUserHasRespondToquestForGame(user, token);
}
@Post('decline')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async declineInvitation(@Body('token') token, @Req() req)
{
const user : User = req.user;
return this.gameService.declineInvitation(user, token);
}
@Post('accept')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async acceptInvitation(@Body('token') token, @Req() req)
{
const user : User = req.user;
return this.gameService.acceptInvitation(user, token);
}
@Get('invitations')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async findInvitations(@Req() request)
{
const user : User = request.user;
return this.gameService.findInvitations(user);
}
//
//N'est valable que pour le game-serveur.
@Post('gameserver/validate')
async validateTicket(@Body() validateTicketDto : ValidateTicketDto, @Req() request)
{
if (await this.gameService.validateToken(validateTicketDto) === false)
return new HttpException("The token is not valid", HttpStatus.NOT_FOUND);
console.log("200 retourné côté nest")
return HttpStatus.OK;
}
@Post('gameserver/creategame')
async createGame(@Body() creategameDto : CreateGameDto)
{
console.log("On est dans create game")
console.log(creategameDto)
return this.gameService.createGame(creategameDto);
}
@Post('gameserver/updategame')
async updateGame(@Body() updateGameDto : UpdateGameDto)
{
console.log("On est dans update game")
console.log(updateGameDto)
return this.gameService.updateGame(updateGameDto);
}
}

View File

@@ -1,9 +1,17 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Friendship } from 'src/friendship/entities/friendship.entity';
import { FriendshipService } from 'src/friendship/friendship.service';
import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
import { Game } from './entity/game.entity';
import { TokenGame } from './entity/tokenGame.entity';
import { GameController } from './game.controller';
import { GameService } from './game.service';
@Module({
imports: [TypeOrmModule.forFeature([TokenGame, User, Game, Friendship])],
controllers: [GameController],
providers: [GameService]
providers: [GameService, UsersService, FriendshipService]
})
export class GameModule {}

View File

@@ -1,18 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { GameService } from './game.service';
// import { Test, TestingModule } from '@nestjs/testing';
// // import { GameService } from './game.service';
describe('GameService', () => {
let service: GameService;
// describe('GameService', () => {
// let service: GameService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [GameService],
}).compile();
// beforeEach(async () => {
// const module: TestingModule = await Test.createTestingModule({
// providers: [GameService],
// }).compile();
service = module.get<GameService>(GameService);
});
// service = module.get<GameService>(GameService);
// });
it('should be defined', () => {
expect(service).toBeDefined();
});
});
// it('should be defined', () => {
// expect(service).toBeDefined();
// });
// });

View File

@@ -1,4 +1,264 @@
import { Injectable } from '@nestjs/common';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { createCipheriv, randomBytes, scrypt } from 'crypto';
import { User } from 'src/users/entities/user.entity';
import { Repository } from 'typeorm';
import { promisify } from 'util';
import { GrantTicketDto } from './dto/grantTicket.dto';
import { Game } from './entity/game.entity';
import { ValidateTicketDto } from './dto/validateTicket.dto';
import { TokenGame } from './entity/tokenGame.entity';
import { UsersService } from 'src/users/users.service';
import { CreateGameDto } from './dto/createGame.dto';
import { UpdateGameDto } from './dto/updateGame.dto';
import { FriendshipService } from 'src/friendship/friendship.service';
@Injectable()
export class GameService {}
export class GameService {
constructor (
@InjectRepository(Game)
private readonly gameRepository : Repository<Game>,
@InjectRepository(User)
private readonly userRepository : Repository<User>,
@InjectRepository(TokenGame)
private readonly tokenGameRepository : Repository<TokenGame>,
private readonly userService : UsersService,
private readonly friendShipService : FriendshipService
) { }
async getRankingForAllUsers(currentUser : User) {
const users = await this.userRepository.createQueryBuilder("user")
.leftJoinAndSelect("user.stats", "stats")
.orderBy('stats.winGame', "DESC")
.getMany();
if (!users)
return new HttpException("No ranking for now.", HttpStatus.NOT_FOUND)
const partialUser : Partial<User>[] = []
for (const user of users)
{
if (await this.friendShipService.findIfUserIsBlockedOrHasBlocked(currentUser.id.toString(), user.id.toString()) === false)
partialUser.push({username : user.username, stats : user.stats })
}
return partialUser;
}
async encryptToken(toEncrypt : string) : Promise<string> {
const iv = randomBytes(16);
const password = process.env.TICKET_FOR_PLAYING_GAME_SECRET + new Date();
const key = (await promisify(scrypt)(password, 'salt', 32)) as Buffer;
const cipher = createCipheriv('aes-256-ctr', key, iv);
const encryptedText = Buffer.concat([
cipher.update(toEncrypt),
cipher.final(),
]);
const encryptedTextToReturn = encryptedText.toString('base64');
return encryptedTextToReturn
}
async generateToken(user : User, grantTicketDto : GrantTicketDto)
{
// if (user.status === "In Game")
// return new HttpException("You can't play two games", HttpStatus.FORBIDDEN);
// else
if (grantTicketDto.isGameIsWithInvitation === true)
{
const secondUser : Partial<User> = await this.userService.findOneByUsername(user.id.toString(), grantTicketDto.playerTwoUsername)
if (!secondUser)
return new HttpException("The requested second player does not exist", HttpStatus.NOT_FOUND);
const encryptedTextToReturn = await this.encryptToken(user.username + '_' + secondUser.username + '_'
+ grantTicketDto.gameOptions + '_' + grantTicketDto.isGameIsWithInvitation + '_' + new Date())
const tok = this.tokenGameRepository.create(grantTicketDto);
tok.isSecondUserAcceptedRequest = false;
tok.numberOfRegisteredUser = 0;
tok.token = encryptedTextToReturn;
this.tokenGameRepository.save(tok);
return { token : encryptedTextToReturn };
}
else if (grantTicketDto.isGameIsWithInvitation === false) {
const encryptedTextToReturn = await this.encryptToken(user.username + '_'
+ grantTicketDto.gameOptions + '_' + grantTicketDto.isGameIsWithInvitation + '_' + new Date())
const tok = this.tokenGameRepository.create(grantTicketDto);
tok.numberOfRegisteredUser = 0;
tok.token = encryptedTextToReturn;
this.tokenGameRepository.save(tok);
return { token : encryptedTextToReturn };
}
return new HttpException("Something went wrong !", HttpStatus.INTERNAL_SERVER_ERROR)
}
async validateToken(validateTicketDto : ValidateTicketDto) {
console.log("On valide le token pour : ")
console.log(validateTicketDto)
if (validateTicketDto.isGameIsWithInvitation === true)
{
const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : validateTicketDto.playerTwoUsername})
.andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokengame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: true})
.andWhere('tokengame.isSecondUserAcceptedRequest = :choice', {choice : true})
.andWhere('tokengame.token = :token', {token : validateTicketDto.token})
.getOne();
if (tokenGame)
{
tokenGame.numberOfRegisteredUser++;
if (tokenGame.numberOfRegisteredUser === 2)
{
this.tokenGameRepository.remove(tokenGame)
const userOne : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerOneUsername})
.getOne();
userOne.status = "In Game";
this.userRepository.save(userOne);
const userTwo : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerTwoUsername})
.getOne();
userTwo.status = "In Game";
this.userRepository.save(userTwo);
}
return true;
}
}
else if (validateTicketDto.isGameIsWithInvitation === false)
{
const tokenGame : TokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerOneUsername = :playerOneUsername', {playerOneUsername : validateTicketDto.playerOneUsername})
.andWhere('tokengame.gameOptions = :gameOption', {gameOption : validateTicketDto.gameOptions})
.andWhere('tokengame.isGameIsWithInvitation = :isGameIsWithInvitation', {isGameIsWithInvitation: false})
.andWhere('tokengame.token = :token', {token : validateTicketDto.token})
.getOne();
if (tokenGame)
{
this.tokenGameRepository.remove(tokenGame)
console.log("USERNAME : " + tokenGame.playerOneUsername)
const user : User = await this.userRepository.createQueryBuilder('user')
.where("user.username = :username", {username : tokenGame.playerOneUsername})
.getOne();
user.status = "In Game";
this.userRepository.save(user);
return true;
}
}
return false;
}
async findInvitations(user : User) {
const game = await this.tokenGameRepository.createQueryBuilder('tokengame')
.where('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokengame.isGameIsWithInvitation = :invit', {invit : true})
.andWhere('tokengame.isSecondUserAcceptedRequest = :choice', {choice : false})
.getMany();
if (!game)
return new HttpException( "No invitations !", HttpStatus.NOT_FOUND);
let partialGame : Partial<TokenGame>[] = [];
for (const gameToken of game) {
partialGame.push({
playerOneUsername : gameToken.playerOneUsername,
playerTwoUsername : gameToken.playerTwoUsername,
gameOptions : gameToken.gameOptions,
token : gameToken.token,
});
}
console.log("Il y a des invitations !")
return partialGame;
}
async declineInvitation(user : User, token : string)
{
// if (user.status === "In Game")
// return new HttpException("You must finish your game before decline.", HttpStatus.FORBIDDEN)
console.log("On décline l'invitation")
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokengame')
.andWhere('tokengame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokengame.token = :token', {token : token})
.getOne();
if (tokenGame)
return this.tokenGameRepository.remove(tokenGame);
return new HttpException("Invitation not found !", HttpStatus.NOT_FOUND)
}
async acceptInvitation(user : User, token : string)
{
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.andWhere('tokenGame.playerTwoUsername = :playerTwoUsername', {playerTwoUsername : user.username})
.andWhere('tokenGame.token = :token', {token : token})
.getOne();
if (tokenGame)
{
tokenGame.isSecondUserAcceptedRequest = true;
this.tokenGameRepository.save(tokenGame)
return HttpStatus.OK
}
return new HttpException("Invitation not found !", HttpStatus.NOT_FOUND)
}
async requestIfAnotherUserHasRespondToquestForGame(user : User, token : string) {
// if (user.status === "In Game")
// return new HttpException("You can't do that.", HttpStatus.BAD_REQUEST)
const tokenGame = await this.tokenGameRepository.createQueryBuilder('tokenGame')
.where('tokenGame.token = :token', {token : token})
.andWhere('tokenGame.isSecondUserAcceptedRequest = :isSecondUserAcceptedRequest', {isSecondUserAcceptedRequest : true})
.getOne();
if (tokenGame && tokenGame.isSecondUserAcceptedRequest === true)
return {isSecondUserAcceptedRequest : true}
else if (tokenGame && tokenGame.isSecondUserAcceptedRequest === false)
return {isSecondUserAcceptedRequest : false}
else if (!tokenGame)
return new HttpException("Not Found", HttpStatus.NOT_FOUND)
}
async createGame(creategameDto : CreateGameDto)
{
const game = this.gameRepository.create(creategameDto)
game.isMatchIsFinished = false;
this.gameRepository.save(game);
if (!game)
return HttpStatus.INTERNAL_SERVER_ERROR
console.log("200 retourné pour la création de partie")
const playerOne = await this.userRepository.findOneBy({username : game.playerOneUsername})
const playerTwo = await this.userRepository.findOneBy({username : game.playerTwoUsername})
playerOne.status = "In Game"
playerTwo.status = "In Game"
this.userRepository.save(playerOne)
this.userRepository.save(playerTwo)
return HttpStatus.OK
}
async updateGame(updateGameDto : UpdateGameDto) {
const game = await this.gameRepository.preload(
{gameServerIdOfTheMatch : updateGameDto.gameServerIdOfTheMatch,
...updateGameDto}
)
if (!game)
throw new HttpException(`The game could not be updated.`,HttpStatus.NOT_FOUND);
game.isMatchIsFinished = true;
this.userRepository.save(game);
const playerOne = await this.userRepository.findOneBy({username : game.playerOneUsername})
const playerTwo = await this.userRepository.findOneBy({username : game.playerTwoUsername})
if (!playerOne || !playerTwo)
return new HttpException("Internal Server Error. Impossible to update the database", HttpStatus.INTERNAL_SERVER_ERROR);
if (game.playerOneUsernameResult === game.playerTwoUsernameResult)
{
this.userService.incrementDraws(playerOne.id)
this.userService.incrementDraws(playerTwo.id)
}
else if (game.playerOneUsernameResult < game.playerTwoUsernameResult)
{
this.userService.incrementDefeats(playerOne.id)
this.userService.incrementVictories(playerTwo.id)
}
else
{
this.userService.incrementVictories(playerOne.id)
this.userService.incrementDefeats(playerTwo.id)
}
playerOne.status = "Connected"
playerTwo.status = "Connected"
this.userRepository.save(playerOne)
this.userRepository.save(playerTwo)
return HttpStatus.OK
}
}

View File

@@ -2,7 +2,7 @@
// et de les mettre comme optionnelles. De plus on peut hériter
// des décorateurs de la classe parente (par exemple @IsString()).
import { OmitType, PartialType } from "@nestjs/mapped-types";
import { OmitType } from "@nestjs/mapped-types";
import { CreateUsersDto } from "./create-users.dto";
export class UpdateUsersDto extends OmitType(CreateUsersDto, ['fortyTwoId', 'email', 'image_url', 'status'] as const){}

View File

@@ -83,10 +83,9 @@ export class UsersController {
async update(@Req() req, @Body(new ValidationPipe()) usersUpdateDto: UpdateUsersDto, @Res() response : Response) {
console.log("DANS PATCH USERS");
const user = await this.usersService.update(req.user.id, usersUpdateDto);
// const user : User = req.user;
if (user.isEnabledTwoFactorAuth === false && user.isTwoFactorAuthenticated === true)
this.usersService.setIsTwoFactorAuthenticatedWhenLogout(user.id);
console.log ("Enbale 2FA " + user.isEnabledTwoFactorAuth + " Is authenticated " + user.isTwoFactorAuthenticated);
console.log ("Enable 2FA " + user.isEnabledTwoFactorAuth + " Is authenticated " + user.isTwoFactorAuthenticated);
if (user.isEnabledTwoFactorAuth === true && user.isTwoFactorAuthenticated === false)
{
response.status(201).send('2FA redirect')

View File

@@ -4,12 +4,9 @@ import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { CreateUsersDto } from './dto/create-users.dto';
import { UpdateUsersDto } from './dto/update-users.dto';
import { Friendship } from '../friendship/entities/friendship.entity';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { UserStats } from './entities/userStat.entities';
import { FriendshipService } from 'src/friendship/friendship.service';
import { stringify } from 'querystring';
// On va devoir sûrement trouver un moyen plus simple pour passer l'id, sûrement via des pipes
// ou des interceptors, mais pour l'instant on va faire comme ça.
@Injectable()

View File

@@ -11,6 +11,10 @@ server {
proxy_pass http://backend_dev:3000;
}
location /api/v2/game/gameserver {
deny all;
}
location /pong {
proxy_pass http://game_server:8042/pong;
proxy_http_version 1.1;

View File

@@ -0,0 +1,186 @@
<script lang="ts">
import * as enumeration from './shared_js/enums'
import * as constants from './client/constants'
import { initPong, initGc, initMatchOptions, initStartFunction } from './client/global'
import { GameArea } from './client/class/GameArea';
import { GameComponentsClient } from './client/class/GameComponentsClient';
import { handleInput } from './client/handleInput';
import {gameLoop} from './client/gameLoop'
import { drawLoop } from './client/draw';
import {countdown} from './client/utils'
import { initWebSocket } from './client/ws';
import { initAudio } from './client/audio';
import { pong, gc} from './client/global'
let optionsAreNotSet = true
let sound = "on"; // possible de faire un boolean avec svelte et radio buttons ?
let multi_balls = false;
let moving_walls = false;
let matchOptions : enumeration.MatchOptions = enumeration.MatchOptions.noOption;
const init = async() => {
// WIP nest, fetch token generation
// const address = "http://transcendance:8080";
// const responsePromise = fetch(address + "/token");
if (sound === "off") {
initAudio(true);
}
else if (sound === "on") {
initAudio(false);
}
console.log(sound); //debug
if (multi_balls === true) {
matchOptions |= enumeration.MatchOptions.multiBalls;
}
if (moving_walls === true) {
matchOptions |= enumeration.MatchOptions.movingWalls;
}
initMatchOptions(matchOptions);
optionsAreNotSet = false;
initPong(new GameArea());
initGc(new GameComponentsClient(matchOptions, pong.ctx));
initStartFunction(start);
// const response = await responsePromise;
// if (!response.ok) {
// console.log("Token retrieve failed"); // TODO: error message
// return;
// }
// const responseJson = await response.json();
initWebSocket(matchOptions, "yolo", "usernamePLACEHOLDER");
// ou est stocké le username dans le front svelte ?
}
function start() : void {
gc.text1.pos.assign(constants.w*0.5, constants.h*0.75);
countdown(constants.matchStartDelay/1000, (count: number) => {
gc.text1.clear();
gc.text1.text = `${count}`;
gc.text1.update();
}, resume);
}
function resume(): void {
gc.text1.text = "";
window.addEventListener('keydown', function (e) {
pong.addKey(e.key);
});
window.addEventListener('keyup', function (e) {
pong.deleteKey(e.key);
});
pong.handleInputInterval = window.setInterval(handleInput, constants.handleInputIntervalMS);
// pong.handleInputInterval = window.setInterval(sendLoop, c.sendLoopIntervalMS);
pong.gameLoopInterval = window.setInterval(gameLoop, constants.gameLoopIntervalMS);
pong.drawLoopInterval = window.setInterval(drawLoop, constants.drawLoopIntervalMS);
}
</script>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
{#if optionsAreNotSet}
<form on:submit|preventDefault={init}>
<div id="div_game_options">
<fieldset>
<legend>game options</legend>
<div>
<input type="checkbox" id="multi_balls" name="multi_balls">
<label for="multi_balls">multiples balls</label>
</div>
<div>
<input type="checkbox" id="moving_walls" name="moving_walls">
<label for="moving_walls">moving walls</label>
</div>
<div>
<!-- svelte-ignore a11y-label-has-associated-control -->
<label>sound :</label>
<input type="radio" id="sound_on" name="sound_selector" bind:group={sound} value="on">
<label for="sound_on">on</label>
<input type="radio" id="sound_off" name="sound_selector" bind:group={sound} value="off">
<label for="sound_off">off</label>
</div>
<div>
<button id="play_pong_button">PLAY</button>
</div>
</fieldset>
</div>
</form>
<div id="div_game_instructions">
<h2>--- keys ---</h2>
<p>move up: 'w' or 'up arrow'</p>
<p>move down: 's' OR 'down arrow'</p>
<p>grid on/off: 'g'</p>
</div>
{/if}
<div id="canvas_container">
<!-- <p> =) </p> -->
</div>
</body>
<style>
@font-face {
font-family: "Bit5x3";
src:
url("/fonts/Bit5x3.woff2") format("woff2"),
local("Bit5x3"),
url("/fonts/Bit5x3.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
}
body {
margin: 0;
background-color: #222425;
}
#canvas_container {
margin-top: 20px;
text-align: center;
/* border: dashed rgb(245, 245, 245) 5px; */
/* max-height: 80vh; */
/* overflow: hidden; */
}
#div_game_instructions {
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: large;
}
#div_game_options {
margin-top: 20px;
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: x-large;
}
#div_game_options fieldset {
max-width: 50vw;
width: auto;
margin: 0 auto;
}
#div_game_options fieldset div {
padding: 10px;
}
#play_pong_button {
font-family: "Bit5x3";
color: rgb(245, 245, 245);
background-color: #333333;
font-size: x-large;
padding: 10px;
}
canvas {
background-color: #333333;
max-width: 75vw;
/* max-height: 100vh; */
width: 80%;
}
</style>

View File

@@ -1,60 +1,126 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import * as enumeration from './shared_js/enums'
import * as constants from './client/constants'
import { initPong, initGc, initMatchOptions, initStartFunction } from './client/global'
import { GameArea } from './client/class/GameArea';
import { GameComponentsClient } from './client/class/GameComponentsClient';
import { handleInput } from './client/handleInput';
import {gameLoop} from './client/gameLoop'
import { gameLoop } from './client/gameLoop'
import { drawLoop } from './client/draw';
import {countdown} from './client/utils'
import { countdown } from './client/utils'
import { initWebSocket } from './client/ws';
import { initAudio } from './client/audio';
import { pong, gc} from './client/global'
import Header from '../../pieces/Header.svelte';
import { fade, fly } from 'svelte/transition'
let optionsAreNotSet = true
let sound = "on"; // possible de faire un boolean avec svelte et radio buttons ?
//user's stuff
let user;
let allUsers;
//Game's stuff nest side
let optionsAreNotSet = true;
let isSomeoneIsIvited = false;
let playerTwoUsername = "";
//Game's stuff gameserver side
let sound = "on";
let multi_balls = false;
let moving_walls = false;
let matchOptions : enumeration.MatchOptions = enumeration.MatchOptions.noOption;
let matchOption : enumeration.MatchOptions = enumeration.MatchOptions.noOption;
const init = async() => {
// WIP nest, fetch token generation
const address = "http://transcendance:8080";
const responsePromise = fetch(address + "/token");
//html boolean for pages
let showWaitPage = false;
let showInvitations = false;
let showGameOption = true;
let showError = false;
if (sound === "off") {
initAudio(true);
}
else if (sound === "on") {
initAudio(false);
}
console.log(sound); //debug
let isThereAnyInvitation = false;
let invitations = [];
if (multi_balls === true) {
matchOptions |= enumeration.MatchOptions.multiBalls;
}
if (moving_walls === true) {
matchOptions |= enumeration.MatchOptions.movingWalls;
}
initMatchOptions(matchOptions);
optionsAreNotSet = false;
initPong(new GameArea());
initGc(new GameComponentsClient(matchOptions, pong.ctx));
initStartFunction(start);
let waitingMessage = "Please wait..."
let errorMessageWhenAttemptingToGetATicket = "";
const response = await responsePromise;
if (!response.ok) {
console.log("Token retrieve failed"); // TODO: error message
return;
onMount( async() => {
user = await fetch('http://transcendance:8080/api/v2/user')
.then( x => x.json() );
allUsers = await fetch('http://transcendance:8080/api/v2/user/all')
.then( x => x.json() );
})
onDestroy( async() => {
})
const initGame = async() => {
optionsAreNotSet = false
showWaitPage = true
if (multi_balls === true)
matchOption |= enumeration.MatchOptions.multiBalls
if (moving_walls === true )
matchOption |= enumeration.MatchOptions.movingWalls
const responseWhenGrantToken = fetch("http://transcendance:8080/api/v2/game/ticket", {
method : "POST",
headers : {'Content-Type': 'application/json'},
body : JSON.stringify({
playerOneUsername : user.username,
playerTwoUsername : playerTwoUsername,
gameOptions : matchOption,
isGameIsWithInvitation : isSomeoneIsIvited
})
})
const responseFromServer = await responseWhenGrantToken;
const responseInjson = await responseFromServer.json();
const token : string = responseInjson.token;
showWaitPage = false
if (!responseFromServer.ok)
{
errorMessageWhenAttemptingToGetATicket = responseInjson.message;
showError = true;
setTimeout(() => {
showError = false;
showWaitPage = false
optionsAreNotSet = true
playerTwoUsername = "";
matchOption = 0;
}, 5000)
}
const responseJson = await response.json();
initWebSocket(matchOptions, responseJson.token, "usernamePLACEHOLDER");
// ou est stocké le username dans le front svelte ?
else if (token)
{
(sound === "off") ? initAudio(true) : initAudio(false);
initMatchOptions(matchOption)
initPong(new GameArea())
initGc(new GameComponentsClient(matchOption, pong.ctx))
initStartFunction(start)
isSomeoneIsIvited ?
initWebSocket(matchOption, token, user.username, true, playerTwoUsername) :
initWebSocket(matchOption, token, user.username)
}
}
const initGameForPrivateParty = async(invitation : any) => {
optionsAreNotSet = false
showWaitPage = true
console.log("invitation : ")
console.log(invitation)
if (invitation.token)
{
initMatchOptions(matchOption)
initPong(new GameArea())
initGc(new GameComponentsClient(matchOption, pong.ctx))
initStartFunction(start)
showWaitPage = false
initWebSocket(matchOption, invitation.token, invitation.playerOneUsername, true, user.username)
}
}
function start() : void {
gc.text1.pos.assign(constants.w*0.5, constants.h*0.75);
@@ -62,10 +128,10 @@
gc.text1.clear();
gc.text1.text = `${count}`;
gc.text1.update();
}, resume);
}, responseWhenGrantTokenume);
}
function resume(): void {
function responseWhenGrantTokenume(): void {
gc.text1.text = "";
window.addEventListener('keydown', function (e) {
pong.addKey(e.key);
@@ -74,102 +140,218 @@
pong.deleteKey(e.key);
});
pong.handleInputInterval = window.setInterval(handleInput, constants.handleInputIntervalMS);
// pong.handleInputInterval = window.setInterval(sendLoop, c.sendLoopIntervalMS);
pong.gameLoopInterval = window.setInterval(gameLoop, constants.gameLoopIntervalMS);
pong.drawLoopInterval = window.setInterval(drawLoop, constants.drawLoopIntervalMS);
}
const showOptions = () => {
showGameOption = true
showInvitations = false
}
const showInvitation = async() => {
showGameOption = false;
showInvitations = true;
invitations = await fetch("http://transcendance:8080/api/v2/game/invitations")
.then(x => x.json())
invitations.length !== 0 ? isThereAnyInvitation = true : isThereAnyInvitation = false
}
const rejectInvitation = async(invitation) => {
await fetch("http://transcendance:8080/api/v2/game/decline",{
method: "POST",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
token : invitation.token
})
})
.then(x => x.json())
.catch(error => console.log(error))
showInvitation()
}
const acceptInvitation = async(invitation : any) => {
await fetch("http://transcendance:8080/api/v2/game/accept",{
method: "POST",
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({
token : invitation.token
})
})
.then(x => x.json())
.catch(error => {
console.log(error)
})
showInvitation()
initGameForPrivateParty(invitation)
}
</script>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<Header />
<body>
<div id="preload_font">.</div>
{#if showError === true}
<div id="div_game" in:fly="{{ y: 10, duration: 1000 }}">
<fieldset>
<legend>Error</legend>
<p>{errorMessageWhenAttemptingToGetATicket}</p>
<button id="pong_button">Retry</button>
</fieldset>
</div>
{/if}
{#if showWaitPage === true}
<div id="div_game" in:fly="{{ y: 10, duration: 1000 }}">
<fieldset>
<legend>Connecting to the game...</legend>
<p>{waitingMessage}</p>
</fieldset>
</div>
{/if}
{#if optionsAreNotSet}
<form on:submit|preventDefault={init}>
<div id="div_game_options">
{#if showGameOption === true}
<div id="game_option">
<form on:submit|preventDefault={() => initGame()}>
<div id="div_game">
<button id="pong_button" on:click={showInvitation}>Show invitations</button>
<fieldset>
<legend>game options</legend>
<div>
<input type="checkbox" id="multi_balls" name="multi_balls">
<label for="multi_balls">multiples balls</label>
<input type="checkbox" id="multi_balls" name="multi_balls" bind:checked={multi_balls}>
<label for="multi_balls">Multiples balls</label>
</div>
<div>
<input type="checkbox" id="moving_walls" name="moving_walls">
<label for="moving_walls">moving walls</label>
<input type="checkbox" id="moving_walls" name="moving_walls" bind:checked={moving_walls}>
<label for="moving_walls">Moving walls</label>
</div>
<div>
<!-- svelte-ignore a11y-label-has-associated-control -->
<label>sound :</label>
<p>sound :</p>
<input type="radio" id="sound_on" name="sound_selector" bind:group={sound} value="on">
<label for="sound_on">on</label>
<input type="radio" id="sound_off" name="sound_selector" bind:group={sound} value="off">
<label for="sound_off">off</label>
</div>
<div>
<button id="play_pong_button">PLAY</button>
<input type="checkbox" id="isSomeoneIsIvited" bind:checked={isSomeoneIsIvited}>
<label for="moving_walls">Invite a friend</label>
</div>
{#if isSomeoneIsIvited === true}
<select bind:value={playerTwoUsername}>
{#each allUsers as user }
<option value={user.username}>{user.username}</option>
{/each}
</select>
{/if}
<div>
<button id="pong_button" >PLAY</button>
</div>
</fieldset>
</div>
</form>
<div id="div_game_instructions">
<h2>--- keys ---</h2>
<p>move up: 'w' or 'up arrow'</p>
<p>move down: 's' OR 'down arrow'</p>
<p>grid on/off: 'g'</p>
</div>
{/if}
{#if showInvitations}
<div id="invitations_options" in:fly="{{ y: 10, duration: 1000 }}">
<div id="div_game">
<button id="pong_button" on:click={showOptions}>Play a Game</button>
<fieldset>
<legend>Current invitation(s)</legend>
{#if isThereAnyInvitation}
{#each invitations as invitation }
<div>
{invitation.playerOneUsername} has invited you to play a pong !
<button id="pong_button" on:click={() => acceptInvitation(invitation)}>V</button>
<button id="pong_button" on:click={() => rejectInvitation(invitation)}>X</button>
</div>
{/each}
{/if}
{#if isThereAnyInvitation === false}
<p>Currently, no one asked to play with you.</p>
<button id="pong_button" on:click={showInvitation}>Reload</button>
{/if}
</fieldset>
</div>
</div>
{/if}
{/if}
<div id="canvas_container">
<div id="canvas_container">
<!-- <p> =) </p> -->
</div>
</div>
</body>
<style>
@font-face {
font-family: "Bit5x3";
src:
url("/fonts/Bit5x3.woff2") format("woff2"),
local("Bit5x3"),
url("/fonts/Bit5x3.woff") format("woff");
src: url("/fonts/Bit5x3.woff2") format("woff2"),local("Bit5x3"), url("/fonts/Bit5x3.woff") format("woff");
font-weight: normal;
font-style: normal;
font-display: swap;
}
#preload_font {
font-family: "Bit5x3";
opacity:0;
height:0;
width:0;
display:inline-block;
}
body {
margin: 0;
background-color: #222425;
}
#canvas_container {
margin-top: 20px;
text-align: center;
/* border: dashed rgb(245, 245, 245) 5px; */
/* max-height: 80vh; */
/* overflow: hidden; */
}
#div_game_instructions {
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: large;
}
#div_game_options {
margin-top: 20px;
#users_name {
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: x-large;
}
#div_game_options fieldset {
#div_game {
text-align: center;
font-family: "Bit5x3";
color: rgb(245, 245, 245);
font-size: x-large;
}
#error_notification {
text-align: center;
display: block;
font-family: "Bit5x3";
color: rgb(143, 19, 19);
font-size: x-large;
}
#div_game fieldset {
max-width: 50vw;
width: auto;
margin: 0 auto;
}
#div_game_options fieldset div {
#div_game fieldset div {
padding: 10px;
}
#play_pong_button {
#pong_button {
font-family: "Bit5x3";
color: rgb(245, 245, 245);
background-color: #333333;
@@ -177,7 +359,7 @@ body {
padding: 10px;
}
canvas {
background-color: #333333;
background-color: #ff0000;
max-width: 75vw;
/* max-height: 100vh; */
width: 80%;

View File

@@ -34,6 +34,8 @@ export const clientInfoSpectator = new ClientInfoSpectator(); // WIP, could refa
export function initWebSocket(options: en.MatchOptions, token: string, username: string, privateMatch = false, playerTwoUsername?: string)
{
socket = new WebSocket(wsUrl, "json");
console.log("Infos from ws.ts : options => " + options + " token => " + token + " username => " + username + " priavte match => " + privateMatch
+ " player two => " + playerTwoUsername)
socket.addEventListener("open", (event) => {
if (privateMatch) {
socket.send(JSON.stringify( new ev.ClientAnnouncePlayer(options, token, username, privateMatch, playerTwoUsername) ));

View File

@@ -24,6 +24,7 @@
<img src="/img/potato_logo.png" alt="Potato Pong Logo" on:click={() => (push('/'))}>
<h1>Potato Pong</h1>
<nav>
<button on:click={() => (push('/game'))}>Game</button>
{#if $location !== '/profile'}
<button on:click={() => (push('/profile'))}>My Profile</button>
{:else if $location === '/profile'}