merge from master

This commit is contained in:
simplonco
2023-01-03 20:03:26 +01:00
81 changed files with 2624 additions and 4454 deletions

View File

@@ -37,10 +37,10 @@ export class AuthenticationController {
const user : User = request.user
if (user.isEnabledTwoFactorAuth === false || user.isTwoFactorAuthenticated === true){
console.log('ON VA VERS PROFILE');
return response.status(200).redirect('http://transcendance:8080/#/profile');
return response.status(200).redirect('http://' + process.env.WEBSITE_HOST + ':' + process.env.WEBSITE_PORT + '/#/profile');
}
console.log('ON VA VERS 2FA')
return response.status(200).redirect('http://transcendance:8080/#/2fa');
return response.status(200).redirect('http://' + process.env.WEBSITE_HOST + ':' + process.env.WEBSITE_PORT + '/#/2fa');
}
/**
@@ -83,6 +83,6 @@ export class AuthenticationController {
throw new UnauthorizedException('Wrong Code.');
await this.userService.authenticateUserWith2FA(request.user.id);
console.log('ON REDIRIGE');
return response.status(200).redirect('http://transcendance:8080/#/profile');
return response.status(200).redirect('http://' + process.env.WEBSITE_HOST + ':' + process.env.WEBSITE_PORT + '/#/profile');
}
}

View File

@@ -4,7 +4,7 @@ import {
WebSocketServer,
MessageBody,
OnGatewayConnection,
OnGatewayDisconnect,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { UsersService } from 'src/users/users.service';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
@@ -32,9 +32,8 @@ export class ChatGateway
async handleDisconnect(client) {
console.log('---- client disconnected :', client.id);
}
/*
*/
@SubscribeMessage('test_users')
@SubscribeMessage('')
handleMessage(): void {
const paginationQuery = new PaginationQueryDto();
const users = this.usersService.findAll(paginationQuery);

View File

@@ -1,4 +1,4 @@
import { Module } from '@nestjs/common';
//import { Module } from '@nestjs/common';
//import { TypeOrmModule } from '@nestjs/typeorm';
//import { FriendshipService } from './friendship.service';
//import { FriendshipController } from './friendship.controller';
@@ -12,5 +12,5 @@ import { Module } from '@nestjs/common';
// exports: [FriendshipService],
//})
export class FriendshipsModule {}
//export class FriendshipsModule {}

View File

@@ -0,0 +1,204 @@
//import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
//import { InjectRepository } from '@nestjs/typeorm';
//import { User } from 'src/users/entities/user.entity';
//import { Repository } from 'typeorm';
//import { CreateFriendshipDto } from './dto/create-friendship.dto';
//import { Friendship, FriendshipStatus } from './entities/friendship.entity';
/*
@Injectable()
export class FriendshipService {
constructor(
@InjectRepository(Friendship)
private readonly friendshipRepository: Repository<Friendship>,
@InjectRepository(User)
private readonly userRepository: Repository<User>,
) { }
async findOneFriend(friendshipId: string, username: string) {
const friendship = await this.friendshipRepository.find({ where: { id: +friendshipId, senderUsername: username, status: FriendshipStatus.ACCEPTED } });
if (!friendship)
throw new HttpException(`The requested friend not found.`, HttpStatus.NOT_FOUND);
return friendship;
}
async findOneBlocked(friendshipId: string, username: string) {
const friendship = await this.friendshipRepository.find({ where: { id: +friendshipId, senderUsername: username, status: FriendshipStatus.BLOCKED } });
if (!friendship)
throw new HttpException(`The requested blocked not found.`, HttpStatus.NOT_FOUND);
return friendship;
}
async findAllFriends(username: string) {
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.status = :status', { status: FriendshipStatus.ACCEPTED })
.andWhere('friendship.receiverUsername = :addressee', { addressee: username })
.orWhere('friendship.senderUsername = :requester', { requester: username })
.andWhere('friendship.status = :status', { status: FriendshipStatus.ACCEPTED })
.getMany();
for (const friend of friendship)
console.log("FRIENDSHIP : " + friend.status);
return friendship;
}
async findAllBlockedFriends(username: string) {
const friendships : Friendship[] = await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.senderUsername = :requestee', { requestee: username })
.andWhere('friendship.status = :status', { status: FriendshipStatus.BLOCKED })
.getMany();
let partialFriendship : Partial<Friendship>[] = [];
for (const friendship of friendships) {
partialFriendship.push({id: friendship.id, date: friendship.date, senderUsername: friendship.senderUsername, receiverUsername: friendship.receiverUsername, status: friendship.status});
}
return partialFriendship;
}
async findAllPendantRequestsForFriendship(username: string) {
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.senderUsername = :requestee', { requestee: username })
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany();
let partialFriendship : Partial<Friendship>[] = [];
for (const friend of friendship) {
console.log("FRIENDSHIP : " + friend);
partialFriendship.push({id: friend.id, senderUsername: friend.senderUsername, receiverUsername: friend.receiverUsername, status: friend.status});
}
console.log("Pendant requests : " + partialFriendship);
return partialFriendship;
}
async findAllReceivedRequestsForFriendship(username: string) {
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.receiverUsername = :addressee', { addressee: username })
.andWhere('friendship.status = :status', { status: FriendshipStatus.REQUESTED })
.getMany();
let partialFriendship : Partial<Friendship>[] = [];
for (const friend of friendship) {
partialFriendship.push({id: friend.id, senderUsername: friend.senderUsername, receiverUsername: friend.receiverUsername, status: friend.status});
}
return partialFriendship;
}
async create(createFriendshipDto: CreateFriendshipDto, creator : User) : Promise <Partial<Friendship>> {
console.log("DTO : \n")
console.log({...createFriendshipDto})
const receiver = await this.userRepository.findOneBy({username: createFriendshipDto.receiverUsername});
if (!receiver)
throw new HttpException(`The addressee does not exist.`, HttpStatus.NOT_FOUND);
if (createFriendshipDto.status !== FriendshipStatus.REQUESTED && createFriendshipDto.status !== FriendshipStatus.BLOCKED)
throw new HttpException(`The status is not valid.`, HttpStatus.NOT_FOUND);
const friendship = await this.friendshipRepository.findOneBy({ sender: creator, receiver: receiver });
if (friendship) {
if (friendship.status && friendship.status === FriendshipStatus.ACCEPTED)
throw new HttpException(`The friendship request has already been accepted.`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.REQUESTED)
throw new HttpException(`The friendship request has already been sent the ${friendship.date}.`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.BLOCKED)
throw new HttpException(`We can't do that`, HttpStatus.OK);
else if (friendship.status && friendship.status === FriendshipStatus.DECLINED)
throw new HttpException(`The request has been declined.`, HttpStatus.OK);
}
const newFriendship = new Friendship();
newFriendship.sender = creator;
newFriendship.senderUsername = creator.username;
newFriendship.receiver = receiver;
newFriendship.receiverUsername = receiver.username;
newFriendship.status = createFriendshipDto.status;
const savedFriendship = this.friendshipRepository.save(newFriendship);
const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id,
date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername,
status : (await savedFriendship).status
}
console.log({...partialFriendship})
return partialFriendship;
}
async acceptFriendship(relationshipId: string, user: User) {
const relation = await this.friendshipRepository.findOneBy({ id: +relationshipId });
if (!relation)
throw new HttpException(`The requested relationship not found.`, HttpStatus.NOT_FOUND);
if (relation.sender.id === user.id) {
throw new HttpException(`You can't accept your own request.`, HttpStatus.NOT_FOUND);
}
relation.status = FriendshipStatus.ACCEPTED;
const savedFriendship = this.friendshipRepository.save(relation);
const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id,
date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername,
status : (await savedFriendship).status
}
return partialFriendship;
}
async declineFriendship(relationshipId: string, user: User) {
const relation = await this.friendshipRepository.findOneBy({ id: +relationshipId });
if (!relation)
throw new HttpException(`The requested relationship not found.`, HttpStatus.NOT_FOUND);
if (relation.sender.id === user.id) {
throw new HttpException(`You can't accept your own request.`, HttpStatus.NOT_FOUND);
}
relation.status = FriendshipStatus.DECLINED;
const savedFriendship = this.friendshipRepository.save(relation);
const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id,
date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername,
status : (await savedFriendship).status
}
return partialFriendship
}
async blockFriendship(relationshipId: string, user: User) {
const relation = await this.friendshipRepository.findOneBy({ id: +relationshipId });
if (!relation)
throw new HttpException(`The requested relationship not found.`, HttpStatus.NOT_FOUND);
if (relation.sender.id === user.id) {
throw new HttpException(`You can't accept your own request.`, HttpStatus.NOT_FOUND);
}
relation.status = FriendshipStatus.BLOCKED;
const savedFriendship = this.friendshipRepository.save(relation);
const partialFriendship : Partial<Friendship> = {
id : (await savedFriendship).id,
date : (await savedFriendship).date,
receiverUsername: (await savedFriendship).receiverUsername,
status : (await savedFriendship).status
}
return partialFriendship
}
async removeFriendship(relationshipId: string, user : User) {
const friendship = await this.friendshipRepository.findOneBy({ id: +relationshipId });
if (!friendship)
throw new HttpException(`Your friend could not be deleted.`, HttpStatus.NOT_FOUND);
if (friendship.sender.id !== user.id || friendship.receiver.id !== user.id) {
throw new HttpException(`You can't do that.`, HttpStatus.FORBIDDEN);
}
return this.friendshipRepository.remove(friendship);
}
async findIfUserIsBlockedOrHasBlocked(userConnectedId: string, userToFindId: string) {
console.log("finding if user is blocked")
const friendship = await this.friendshipRepository
.createQueryBuilder('friendship')
.where('friendship.senderUsername = :requestee', { requestee: userConnectedId })
.orWhere('friendship.senderUsername = :requesteeBis', { requesteeBis: userToFindId })
.andWhere('friendship.status = :status', { status: FriendshipStatus.BLOCKED })
.getOne();
if (friendship) {
console.log('we are blocked in friendship.service')
return true;
}
return false;
}
}
*/

View File

@@ -24,5 +24,13 @@ export const storageForAvatar = {
const extension : string = MIME_TYPES[file.mimetype];
cb(null, `${filename}${extension}`);
}
})
}),
fileFilter: (req, file, cb) => {
if (file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg') {
cb(null, true);
}
else {
cb(null, false);
}
}
}

View File

@@ -17,6 +17,9 @@ export class Game {
@Column({default : 0, nullable : true})
playerTwoUsernameResult : number
@Column({default : 0})
gameOptions: number
@Column({unique : true})
gameServerIdOfTheMatch: string

View File

@@ -13,6 +13,14 @@ export class GameController {
constructor (private readonly gameService : GameService) { }
@Get('match/all')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
async getMatchesForSpectator()
{
return this.gameService.getMatchesForSpectator();
}
@Get('ranking')
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)

View File

@@ -28,6 +28,21 @@ export class GameService {
private readonly friendShipService : FriendshipService
) { }
async getMatchesForSpectator() {
const games = await this.gameRepository.createQueryBuilder("game")
.where('game.isMatchIsFinished = :isMatchIsFinished', {isMatchIsFinished : false})
.getMany();
const gamesToReturn : Partial<Game>[] = []
for (const game of games)
{
gamesToReturn.push({gameServerIdOfTheMatch : game.gameServerIdOfTheMatch,
gameOptions : game.gameOptions, playerOneUsername : game.playerOneUsername,
playerTwoUsername : game.playerTwoUsername})
console.log("Is match is finished : " + game.isMatchIsFinished)
}
return gamesToReturn;
}
async getRankingForAllUsers(currentUser : User) {
const users = await this.userRepository.createQueryBuilder("user")
.leftJoinAndSelect("user.stats", "stats")
@@ -255,6 +270,8 @@ export class GameService {
game.playerOneUsernameResult = updateGameDto.playerOneUsernameResult
game.playerTwoUsernameResult = updateGameDto.playerTwoUsernameResult
this.gameRepository.save(game);
console.log("On a sauvegardé la partie. Game :")
console.log(game)
const playerOne = await this.userRepository.findOneBy({username : game.playerOneUsername})
const playerTwo = await this.userRepository.findOneBy({username : game.playerTwoUsername})
if (!playerOne || !playerTwo)

View File

@@ -8,7 +8,7 @@ import * as connectRedis from 'connect-redis';
async function bootstrap() {
const app = await NestFactory.create(AppModule, { cors: true });
const port = process.env.PORT || 3001;
const port = process.env.PORT || 3000;
const client = redis.createClient(
{
socket: { host: process.env.REDIS_HOST, port: parseInt(process.env.REDIS_PORT) },
@@ -50,6 +50,6 @@ async function bootstrap() {
);
app.use(passport.initialize());
app.use(passport.session());
await app.listen(port, () => { console.log(`Listening on port ${port}`); });
await app.listen(port, () => { console.log(`Listening on port ${process.env.WEBSITE_HOST}:${process.env.WEBSITE_PORT}}`); });
}
bootstrap();

View File

@@ -1,5 +1,5 @@
import {
Body, Controller, Delete, Get, NotFoundException, Param, Patch, Post, Query, Redirect, Req, Res, UploadedFile, UseGuards, UseInterceptors
Body, Controller, Delete, Get, NotFoundException,HttpStatus, Param, Patch, Post, Query, Redirect, Req, Res, UploadedFile, UseGuards, UseInterceptors
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
@@ -31,19 +31,6 @@ export class UsersController {
///////////////////////// RUD //////////////////////////
////////////////////////////////////////////////////////
/**
* On ne fait de création via une route
* car un utilisateur est crée à la première connexion avec l'Oauth de 42.
*/
// @UseGuards(AuthenticateGuard)
// @UseGuards(TwoFactorGuard)
// @Get()
// findOne(@Req() req) {
// console.log("Backend Getting current user");
// return this.usersService.findOne(req.user.id);
// }
@UseGuards(AuthenticateGuard)
@UseGuards(TwoFactorGuard)
@Get()
@@ -100,9 +87,14 @@ export class UsersController {
@UseGuards(TwoFactorGuard)
@Post('avatar')
@UseInterceptors(FileInterceptor('file', storageForAvatar))
uploadAvatar(@UploadedFile() file, @Req() request){
uploadAvatar(@UploadedFile() file, @Req() request, @Res() res){
const user : User = request.user;
this.usersService.updateAvatar(user.id, file.filename);
if (file)
{
this.usersService.updateAvatar(user.id, file.filename);
return res.status(HttpStatus.OK).json({message : "Avatar updated"});
}
return res.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE).json({message : "Unsupported media type. Please use a valid image file."});
}
@UseGuards(AuthenticateGuard)