add apommier commit without messages/modal.tsx change and with useEffect in canvas commented

This commit is contained in:
Lara REALI 2023-06-26 17:32:02 +02:00
parent c5957c4813
commit e09324025d
9 changed files with 377 additions and 543 deletions

View File

@ -34,11 +34,11 @@ export class AppController {
kFactor = 36; kFactor = 36;
scaleFactor = 400; scaleFactor = 400;
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
// User // User
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get('/profile') @Get('/profile')
@ -46,6 +46,20 @@ export class AppController {
return await this.userService.findOne(req.user.username); return await this.userService.findOne(req.user.username);
} }
@UseGuards(JwtAuthGuard)
@Post('/logout')
async logout(@Request() req, @Body() data: any) {
const user = await this.userService.findOne(req.user.username)
// return await this.userService.refuseInvite(user, data.username);
if (!user)
return;
if (user.sessionNumber === 1) {
user.status = 0;
}
user.sessionNumber--;
this.userService.save(user);
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/user') @Post('/user')
async getUser(@Body() data: any) { async getUser(@Body() data: any) {
@ -138,16 +152,16 @@ export class AppController {
await this.userService.save(user); await this.userService.save(user);
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/nickname') @Post('/nickname')
async setNickname(@Request() req, @Body() data: any) { async setNickname(@Request() req, @Body() data: any) {
const taken = await this.userService.findNickname(data.nickname) const taken = await this.userService.findNickname(data.nickname)
if (taken) if (taken)
return (0); return (0);
let user = await this.userService.findOne(req.user.username) let user = await this.userService.findOne(req.user.username)
user.nickname = data.nickname; user.nickname = data.nickname;
return await this.userService.save(user); return await this.userService.save(user);
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/picture') @Post('/picture')
@ -161,21 +175,21 @@ export class AppController {
return await this.userService.save(user); return await this.userService.save(user);
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/getPicture') @Post('/getPicture')
async getProfilPicture(@Body() data: any) { async getProfilPicture(@Body() data: any) {
return await this.userService.getPic(data.username) return await this.userService.getPic(data.username)
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/addSession') @Post('/addSession')
async addSession(@Request() req) { async addSession(@Request() req) {
const user = await this.userService.findOne(req.user.username); const user = await this.userService.findOne(req.user.username);
user.sessionNumber += 1; user.sessionNumber += 1;
if (user.status !== 2) if (user.status !== 2)
user.status = 1; user.status = 1;
await this.userService.save(user); await this.userService.save(user);
} }
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
@ -183,37 +197,38 @@ export class AppController {
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/win') @Post('/win')
async addWin(@Request() req, @Body() data: any) { async addWin(@Request() req, @Body() data: any) {
const user = await this.userService.findOne(req.user.username); const user = await this.userService.findOne(req.user.username);
user.win++; user.win++;
const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor)) const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor))
const newRank = user.rank + this.kFactor * (1 - Esp); const newRank = user.rank + this.kFactor * (1 - Esp);
user.rank = newRank; user.rank = newRank;
const newMatch = new MatchLog; const newMatch = new MatchLog;
newMatch.myScore = data.myScore; newMatch.myScore = data.myScore;
newMatch.opScore = data.opScore; newMatch.opScore = data.opScore;
newMatch.opponent = data.opName; newMatch.opponent = data.opName;
newMatch.parent = user; newMatch.parent = user;
await this.userService.saveChild(user, newMatch); await this.userService.saveChild(user, newMatch);
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/loss') @Post('/loss')
async addLoss(@Request() req, @Body() data: any) { async addLoss(@Request() req, @Body() data: any) {
const user = await this.userService.findOne(req.user.username); const user = await this.userService.findOne(req.user.username);
user.loss++; user.loss++;
const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor)) user.status = 1;
const newRank = user.rank + this.kFactor * (0 - Esp); const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor))
user.rank = newRank; const newRank = user.rank + this.kFactor * (0 - Esp);
const newMatch = new MatchLog; user.rank = newRank;
newMatch.myScore = data.myScore; const newMatch = new MatchLog;
newMatch.opScore = data.opScore; newMatch.myScore = data.myScore;
newMatch.opponent = data.opName; newMatch.opScore = data.opScore;
newMatch.parent = user; newMatch.opponent = data.opName;
await this.userService.saveChild(user, newMatch); newMatch.parent = user;
} await this.userService.saveChild(user, newMatch);
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get('/rank') @Get('/rank')
@ -222,127 +237,119 @@ export class AppController {
return user.rank; return user.rank;
} }
@Get('/ranking') @Get('/ranking')
async getRanking() async getRanking() {
{ return await this.userService.getRanking();
return await this.userService.getRanking(); }
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/partyInvite') @Post('/partyInvite')
async partyInvite(@Request() req, @Body() data: any) async partyInvite(@Request() req, @Body() data: any) {
{
const user = await this.userService.findOne(data.username); const user = await this.userService.findOne(data.username);
user.partyInvite = user.partyInvite || []; user.partyInvite = user.partyInvite || [];
user.partyInvite.push({ username: req.user.username, gameId: data.gameId }); user.partyInvite.push({ username: req.user.username, gameId: data.gameId });
await this.userService.save(user); await this.userService.save(user);
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get('/partyInvite') @Get('/partyInvite')
async getPartyInvite(@Request() req) async getPartyInvite(@Request() req) {
{
const user = await this.userService.findOne(req.user.username); const user = await this.userService.findOne(req.user.username);
user.partyInvite = user.partyInvite || []; user.partyInvite = user.partyInvite || [];
return user.partyInvite; return user.partyInvite;
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/deleteInvite') @Post('/deleteInvite')
async deleteInvite(@Request() req, @Body() data: any) async deleteInvite(@Request() req, @Body() data: any) {
{ const user = await this.userService.findOne(req.user.username);
const user = await this.userService.findOne(req.user.username); user.partyInvite = user.partyInvite.filter((item) => Object.values(item)[1] !== data.username);
user.partyInvite = user.partyInvite.filter((item) => Object.values(item)[1] !== data.username); this.userService.save(user);
this.userService.save(user); }
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/history') @Post('/history')
async getHistory(@Body() data: any) async getHistory(@Body() data: any) {
{ return await this.userService.getHistory(data.username);
return await this.userService.getHistory(data.username); }
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/quit') @Post('/quit')
async setOffline(@Request() req) { async setOffline(@Request() req) {
const user = await this.userService.findOne(req.user.username); const user = await this.userService.findOne(req.user.username);
user.sessionNumber--; if (!user)
if (!user.sessionNumber) return;
user.status = 0; user.sessionNumber--;
await this.userService.save(user); if (!user.sessionNumber)
} user.status = 0;
await this.userService.save(user);
}
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
// Auth // Auth
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
@Redirect('http://' + process.env.BASE_URL + '/token', 302) @Redirect('http://' + process.env.BASE_URL + '/token', 302)
@Get('auth/login') @Get('auth/login')
async login2(@Req() request: Request) { async login2(@Req() request: Request) {
const url = request.url; const url = request.url;
const user = await this.loginClass.Login42(url); const user = await this.loginClass.Login42(url);
const data = await this.authService.login(user); const data = await this.authService.login(user);
const myJSON = JSON.stringify(data); const myJSON = JSON.stringify(data);
const token = (await data).access_token; const token = (await data).access_token;
await this.userService.save(user); await this.userService.save(user);
return { url: 'http://' + process.env.BASE_URL + `/token?data=${encodeURIComponent(JSON.stringify(token))}` }; return { url: 'http://' + process.env.BASE_URL + `/token?data=${encodeURIComponent(JSON.stringify(token))}` };
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get('/2fa') @Get('/2fa')
async get2fa(@Request() req) async get2fa(@Request() req) {
{ const user = await this.userService.findOne(req.user.username);
const user = await this.userService.findOne(req.user.username); return user.otp_enabled;
return user.otp_enabled; }
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/otp') @Post('/otp')
async createOTP(@Request() req) async createOTP(@Request() req) {
{ const user = await this.userService.findOne(req.user.username);
const user = await this.userService.findOne(req.user.username); const res = await generateOTP(user);
const res = await generateOTP(user); await this.userService.save(user);
await this.userService.save(user); return res;
return res; }
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/verifyOtp') @Post('/verifyOtp')
async verifyOTP(@Request() req, @Body() data: any) async verifyOTP(@Request() req, @Body() data: any) {
{ const user = await this.userService.findOne(req.user.username);
const user = await this.userService.findOne(req.user.username); const res = await VerifyOTP(user, data.token)
const res = await VerifyOTP(user, data.token) await this.userService.save(user);
await this.userService.save(user); return res
return res }
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/validateOtp') @Post('/validateOtp')
async validateOTP(@Request() req, @Body() data: any) async validateOTP(@Request() req, @Body() data: any) {
{ const user = await this.userService.findOne(req.user.username);
const user = await this.userService.findOne(req.user.username); const res = await ValidateOTP(user, data.token)
const res = await ValidateOTP(user, data.token) return res
return res }
}
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/deleteOtp') @Post('/deleteOtp')
async deleteOTP(@Request() req, @Body() data: any) async deleteOTP(@Request() req, @Body() data: any) {
{ const user = await this.userService.findOne(req.user.username);
const user = await this.userService.findOne(req.user.username); user.otp_verified = false;
user.otp_verified = false; await this.userService.save(user);
await this.userService.save(user); }
}
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
// Chat // Chat
//======================================================================================================== //========================================================================================================
//======================================================================================================== //========================================================================================================
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/conv') @Post('/conv')
@ -418,9 +425,12 @@ export class AppController {
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/verifyPassword') @Post('/verifyPassword')
async verifyPassword(@Body() data: any) { async verifyPassword(@Request() req, @Body() data: any) {
return await this.chatService.verifyPassword(data.convId, data.password) return await this.chatService.verifyPassword(data.convId, data.password, req.user.username)
} }
// async verifyPassword(@Body() data: any) {
// return await this.chatService.verifyPassword(data.convId, data.password)
// }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Post('/inviteConv') @Post('/inviteConv')

View File

@ -17,159 +17,167 @@ import { Conv } from '../model/chat.entity';
import { Message } from '../model/chat.entity'; import { Message } from '../model/chat.entity';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
@Injectable() @Injectable()
export class ChatService { export class ChatService {
constructor(@InjectRepository(Conv) private chatRepository: Repository<Conv>, constructor(@InjectRepository(Conv) private chatRepository: Repository<Conv>,
@InjectRepository(Message) private messageRepository: Repository<Message>, @InjectRepository(Message) private messageRepository: Repository<Message>,
) {} ) { }
async save(conv: Conv): Promise<Conv> {
return await this.chatRepository.save(conv);
}
async findAll(): Promise<Conv[]> { async save(conv: Conv): Promise<Conv> {
return await this.chatRepository.find(); return await this.chatRepository.save(conv);
}
async createConv(conv: Conv): Promise<Conv> {
return await this.chatRepository.save(conv);
}
async getConv(username: string): Promise<Conv[]>{
const convs = await this.chatRepository.query("SELECT * FROM \"conv\" WHERE $1 = ANY (ARRAY[members]);", [username])
return convs;
}
async findConv(number: number){
const conv = await this.chatRepository.findOneBy({id: number})
return conv;
}
async createMessage(message: Message, username: string): Promise<Message> {
const conv = await this.findConv(message.convid);
if (conv.banned && conv.banned.find(item => item === username))
return ;
if (conv.muted && conv.muted.find(item => item === username))
return ;
return await this.messageRepository.save(message);
}
async isAllowed(convId: number, username: string) {
const conv = await this.findConv(convId);
if (conv.banned && conv.banned.find(item => item === username))
return (0);
if (conv.muted && conv.muted.find(item => item === username))
return (0);
return (1);
}
async getMessages(convId: number): Promise<Message[]> {
const convs = await this.chatRepository
.query("SELECT * FROM \"message\" WHERE $1 = message.convid;", [convId])
return (convs)
}
async banUser(convId: number, username: string) {
const conv = await this.findConv(convId);
if (conv.owner === username)
return (0);
conv.banned = conv.banned || [];
if (conv.banned.find(item => item === username))
{
conv.banned = conv.banned.filter((item) => item !== username);
this.save(conv);
return (2);
} }
conv.members = conv.members.filter((item) => item !== username);
conv.banned.push(username);
this.save(conv);
return (1);
}
async inviteUser(convId: number, username: string) { async findAll(): Promise<Conv[]> {
const conv = await this.findConv(convId); return await this.chatRepository.find();
}
if (conv.members.find(item => item === username)) async createConv(conv: Conv): Promise<Conv> {
return (1); return await this.chatRepository.save(conv);
conv.members.push(username); }
this.save(conv);
}
async getConv(username: string): Promise<Conv[]> {
const convs = await this.chatRepository.query("SELECT * FROM \"conv\" WHERE $1 = ANY (ARRAY[members]);", [username])
return convs;
}
async findConv(number: number) {
const conv = await this.chatRepository.findOneBy({ id: number })
return conv;
}
async setPassword(convId: number, password: string) { async createMessage(message: Message, username: string): Promise<Message> {
const conv = await this.findConv(convId); const conv = await this.findConv(message.convid);
const saltRounds = 10; if (conv.banned && conv.banned.find(item => item === username))
const hashedPassword = await bcrypt.hash(password, saltRounds); return;
conv.password = hashedPassword if (conv.muted && conv.muted.find(item => item === username))
this.save(conv); return;
} return await this.messageRepository.save(message);
}
async verifyPassword(convId: number, password: string) { async isAllowed(convId: number, username: string) {
const conv = await this.findConv(convId); const conv = await this.findConv(convId);
return await bcrypt.compare(password, conv.password); if (conv.banned && conv.banned.find(item => item === username))
} return (0);
if (conv.muted && conv.muted.find(item => item === username))
async muteUser(convId: number, username: string, time: string) { return (0);
const conv = await this.findConv(convId);
const intTime = parseInt(time) * 1000;
if (conv.owner === username)
return (0);
conv.muted = conv.muted || [];
if (conv.muted.find(item => item === username))
return (1); return (1);
conv.muted.push(username); }
this.save(conv);
setTimeout(() => { async getMessages(convId: number): Promise<Message[]> {
conv.muted = conv.muted.filter((item) => item !== username) const convs = await this.chatRepository
.query("SELECT * FROM \"message\" WHERE $1 = message.convid;", [convId])
return (convs)
}
async banUser(convId: number, username: string) {
const conv = await this.findConv(convId);
if (conv.owner === username)
return (0);
conv.banned = conv.banned || [];
if (conv.banned.find(item => item === username)) {
conv.banned = conv.banned.filter((item) => item !== username);
this.save(conv);
return (2);
}
conv.members = conv.members.filter((item) => item !== username);
conv.banned.push(username);
this.save(conv); this.save(conv);
}, intTime);
}
async setAdmin(convId: number, username: string) {
const conv = await this.findConv(convId);
conv.admin = conv.admin || [];
if (conv.admin.find(item => item === username))
return (1); return (1);
conv.admin.push(username); }
this.save(conv);
}
async isAdmin(convId: number, username: string) { async inviteUser(convId: number, username: string) {
const conv = await this.findConv(convId); const conv = await this.findConv(convId);
conv.admin = conv.admin || []; if (conv.members.find(item => item === username))
if (conv.admin.find(item => item === username)) return (1);
return (1); conv.members.push(username);
console.log("nope"); this.save(conv);
return (0); }
}
async setPrivate(convId: number, bool: boolean) {
const conv = await this.findConv(convId);
console.log("bool= ", bool);
conv.private = bool;
this.save(conv);
}
async setName(convId: number, name: string) {
const conv = await this.findConv(convId);
conv.name = name;
this.save(conv);
}
async joinChannel(convId: number, username: string) { async setPassword(convId: number, password: string) {
const conv = await this.findConv(convId); const conv = await this.findConv(convId);
conv.members = conv.members || []; const saltRounds = 10;
if (conv.members.find(item => item === username)) const hashedPassword = await bcrypt.hash(password, saltRounds);
return ; conv.password = hashedPassword
conv.members.push(username); this.save(conv);
this.save(conv); }
}
// async verifyPassword(convId: number, password: string) {
async verifyPassword(convId: number, password: string, username: string) {
const conv = await this.findConv(convId);
// return await bcrypt.compare(password, conv.password);
const ret = await bcrypt.compare(password, conv.password);
if (ret === true) {
conv.members = conv.members || [];
conv.members.push(username);
this.save(conv);
}
return ret;
}
yy
async muteUser(convId: number, username: string, time: string) {
const conv = await this.findConv(convId);
const intTime = parseInt(time) * 1000;
if (conv.owner === username)
return (0);
conv.muted = conv.muted || [];
if (conv.muted.find(item => item === username))
return (1);
conv.muted.push(username);
this.save(conv);
setTimeout(() => {
conv.muted = conv.muted.filter((item) => item !== username)
this.save(conv);
}, intTime);
}
async setAdmin(convId: number, username: string) {
const conv = await this.findConv(convId);
conv.admin = conv.admin || [];
if (conv.admin.find(item => item === username))
return (1);
conv.admin.push(username);
this.save(conv);
}
async isAdmin(convId: number, username: string) {
const conv = await this.findConv(convId);
conv.admin = conv.admin || [];
if (conv.admin.find(item => item === username))
return (1);
console.log("nope");
return (0);
}
async setPrivate(convId: number, bool: boolean) {
const conv = await this.findConv(convId);
console.log("bool= ", bool);
conv.private = bool;
this.save(conv);
}
async setName(convId: number, name: string) {
const conv = await this.findConv(convId);
conv.name = name;
this.save(conv);
}
async joinChannel(convId: number, username: string) {
const conv = await this.findConv(convId);
conv.members = conv.members || [];
if (conv.members.find(item => item === username))
return;
conv.members.push(username);
this.save(conv);
}
} }

View File

@ -1,58 +0,0 @@
export const Rank = [
{
rank: '1',
name: 'jean',
},
{
rank: '2',
name: 'marc',
},
{
rank: '3',
name: 'dujardain',
},
{
rank: '4',
name: 'mom',
},
{
rank: '5',
name: 'fary',
},
{
rank: '6',
name: 'aba',
},
{
rank: '7',
name: 'preach',
},
{
rank: '1',
name: 'jean',
},
{
rank: '2',
name: 'marc',
},
{
rank: '3',
name: 'dujardain',
},
{
rank: '4',
name: 'mom',
},
{
rank: '5',
name: 'fary',
},
{
rank: '6',
name: 'aba',
},
{
rank: '7',
name: 'preach',
},
]

View File

@ -1,8 +0,0 @@
import DefaultPic from '../assets/profile.jpg';
export const UserProfile = {
Pic: DefaultPic,
UserName: 'Dipper Ratman',
}
// export default UserProfile

View File

@ -1,37 +0,0 @@
export const DBWinLoss = [
{
title: 'Victory',
score: '10 - 6',
opponent: 'chef bandit'
},
{
title: 'Defeat',
score: '9 - 10',
opponent: 'ex tueur'
},
{
title: 'Victory',
score: '10 - 0',
opponent: 'tueur'
},
{
title: 'Victory',
score: '10 - 9',
opponent: 'boulanger'
},
{
title: 'Defeat',
score: '3 - 10',
opponent: 'charcutier'
},
{
title: 'Deafet',
score: '9 - 10',
opponent: 'preach'
},
{
title: 'Victory',
score: '10 - 9',
opponent: 'aba'
},
]

View File

@ -1,9 +1,18 @@
import React from "react"; import React from "react";
import api from "../../script/axiosApi"
function Logout(){ function Logout(){
const logout = async () =>{
try {
await api.post("/logout")
} catch (err) {
console.log(err);
}
}
logout();
localStorage.clear(); localStorage.clear();
const path = 'http://' + process.env.REACT_APP_BASE_URL + '/'; const path = 'http://' + process.env.REACT_APP_BASE_URL + '/';
// history(path, { replace: true }); // history(path, { replace: true });

View File

@ -1,146 +1,38 @@
import React, { useCallback, useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import api from '../script/axiosApi.tsx'; import api from '../script/axiosApi.tsx';
// function DoubleAuth() {
// // const enabled = await api.get("/2fa");
// // const response = await api.get("/2fa");
// // const enabled = response.data;
// // console.log(`enable= ${enabled.data}`)
// // const enabled = 0;
// let enabled;
// useEffect(() => {
// async function get2fa()
// {
// const response = await api.get("/2fa");
// const enabled = response.data;
// console.log(`enable= ${enabled.data}`)
// }
// // const enabled = 0;
// }, [])
// useEffect(() => {
// async function get2fa()
// {
// api.get('/api/QRcode', { responseType: 'blob' })
// .then(response => {
// const reader = new FileReader();
// reader.onloadend = () => {
// setImageSrc(reader.result);
// };
// reader.readAsDataURL(response.data);
// })
// .catch(error => {
// console.error(error);
// });
// } }, []);
// // const [verificationCode, setVerificationCode] = useState('');
// // const [invalidCode, setInvalidCode] = useState(false);
// const handleSubmit = () => {
// // async (e) => {
// // e.preventDefault();
// // const result = await verifyOtp(verificationCode);
// // if (result) return (window.location = '/');
// // setInvalidCode(true);
// // },
// // [verificationCode]
// };
// let sourceCode
// if (!enabled)
// {
// api.get('/QRcode')
// .then(response => {
// sourceCode = response.data;
// console.log(sourceCode);
// })
// .catch(error => {
// console.error(error);
// });
// }
// return (
// <div>
// {!enabled && (
// <div>
// <p>Scan the QR code on your authenticator app</p>
// <img src={sourceCode} />
// </div>
// )}
// <form onSubmit={handleSubmit}>
// {/* <Input
// id="verificationCode"
// label="Verification code"
// type="text"
// value={verificationCode}
// onChange={(e) => setVerificationCode(e.target.value)}
// /> */}
// <button type="submit">Confirm</button>
// {/* {invalidCode && <p>Invalid verification code</p>} */}
// </form>
// </div>
// );
// }
// import { toFileStream } from 'qrcode';
const DoubleAuth = () => { const DoubleAuth = () => {
const [imageSrc, setImageSrc] = useState(''); // const [imageSrc, setImageSrc] = useState('');
const [imageSrc, setImageSrc] = useState<string | ArrayBuffer | null>('');
useEffect(() => { useEffect(() => {
async function getCode(){ async function getCode() {
await api.get('/QRcode', { responseType: 'blob' }) await api.get('/QRcode', { responseType: 'blob' })
.then(response => { .then(response => {
const reader = new FileReader(); const reader = new FileReader();
reader.onloadend = () => { if (!reader)
setImageSrc(reader.result); return;
}; reader.onloadend = () => {
reader.readAsDataURL(response.data); setImageSrc(reader.result);
}) };
.catch(error => { reader.readAsDataURL(response.data);
console.error(error); })
}); .catch(error => {
} console.error(error);
getCode(); });
}, []); }
getCode();
// return ( }, []);
// <div>
// {imageSrc && <img src={imageSrc} alt="QR Code" />}
// </div>
// );
// <img src={sourceCode} />
return ( return (
<div> <div>
<div> <div>
<p>Scan the QR code on your authenticator app</p> <p>Scan the QR code on your authenticator app</p>
{imageSrc && <img src={imageSrc} alt="QR Code" />} {/* {imageSrc && <img src={imageSrc} alt="QR Code" />} */}
</div> {imageSrc && <img src={imageSrc.toString()} alt="QR Code" />}</div>
{/* <form onSubmit={handleSubmit}>
<button type="submit">Confirm</button>
</form> */}
</div> </div>
); );
};
}; export default DoubleAuth;
export default DoubleAuth;

View File

@ -1,9 +0,0 @@
import React from "react";
function Social (){
return (
<div>je suis la partie social</div>
)
}
export default Social

View File

@ -1,3 +1,4 @@
import { useEffect } from 'react';
import api from '../script/axiosApi.tsx'; import api from '../script/axiosApi.tsx';
import io from 'socket.io-client'; import io from 'socket.io-client';
@ -9,6 +10,21 @@ interface GameProps {
function DrawCanvas(option: number, gameParam: GameProps) { function DrawCanvas(option: number, gameParam: GameProps) {
// useEffect(() => {
// const handleBeforeUnload = async (event: { preventDefault: () => void; returnValue: string; }) => {
// try {
// await api.post("/status", {status: 1});
// } catch (err) {
// console.log(err);
// }
// };
// window.addEventListener('beforeunload', handleBeforeUnload);
// return () => {
// window.removeEventListener('beforeunload', handleBeforeUnload);
// };
// }, []);
console.log(`option= ${option}`); console.log(`option= ${option}`);
const superpowerModifier = option & 1; // Retrieves the superpower modifier const superpowerModifier = option & 1; // Retrieves the superpower modifier
const obstacleModifier = (option >> 1) & 1; // Retrieves the obstacle modifier const obstacleModifier = (option >> 1) & 1; // Retrieves the obstacle modifier
@ -38,7 +54,7 @@ function DrawCanvas(option: number, gameParam: GameProps) {
} }
console.log("start function"); console.log("start function");
const canvas = document.getElementById('myCanvas') as HTMLCanvasElement | null;; const canvas = document.getElementById('myCanvas') as HTMLCanvasElement | null;
if (!canvas) if (!canvas)
return ; return ;
@ -433,6 +449,17 @@ socket.on('pong:hisPoint', (data) => {
console.log(err) console.log(err)
} }
} }
else
{
const data = {
myScore: myScore,
opScore: 5,
opName: opName,
opRank: opRank,
};
await api.post('/loss', data);
// await api.post('/status', {status: 1});
}
socket.emit('pong:disconnect', {id: myId}); socket.emit('pong:disconnect', {id: myId});
window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong"); window.location.replace("http://" + process.env.REACT_APP_BASE_URL + "/pong");
}; };