merge reborn

This commit is contained in:
Alexandre POMMIER 2023-06-26 04:16:48 +02:00
commit abf09f24fd
20 changed files with 225 additions and 162 deletions

21
.env
View File

@ -7,18 +7,17 @@
# POSTGRES_PASSWORD=pass
# POSTGRES_DB=postgreDB
# POSTGRES_ROOT_PASSWORD=pass
# POSTGRES_HOST=bess-f2r5s13
# POSTGRES_HOST=localhost
# POSTGRES_HOST_AUTH_METHOD=trust
#URL
NGINX_ENVSUBST_TEMPLATE_SUFFIX=".conf"
# BASE_URL=http://bess-f2r5s13
# SOCKET_URL=bess-f2r5s13:8080
BASE_URL=bess-f2r5s13:8080
REACT_APP_BASE_URL=bess-f2r5s13:8080
REDIRECT_URI=http://bess-f2r5s13:8080/api/auth/login
INTRA_URL="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-2bd3c5d4f41e776f2e3d5d699d2a8421f6d0c0468ec882516d9ca89b0c211789&redirect_uri=http%3A%2F%2Fbess-f2r5s13%3A8080%2Fapi%2Fauth%2Flogin&response_type=code"
# BASE_URL=http://localhost
# SOCKET_URL=localhost:8080
BASE_URL=localhost:8080
REACT_APP_BASE_URL=localhost:8080
REDIRECT_URI=http://localhost:8080/api/auth/login
#postgres var
# POSTGRES_HOST=127.0.0.1
# DB_TYPE=postgres
@ -35,7 +34,7 @@ NGINX_PORT=8080
PONG_PORT=4000
CHAT_PORT=4001
POSTGRES_PORT=5432
#????
RUN_MIGRATIONS=true
REACT_HOST=0.0.0.0
@ -43,6 +42,6 @@ REACT_HOST=0.0.0.0
#auth var
JWT_SECRET=secrethere
# REDIRECT_URI=http://bess-f2r5s13:80/api/auth/login
API_SECRET=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
CLIENT_UID=u-s4t2ud-2bd3c5d4f41e776f2e3d5d699d2a8421f6d0c0468ec882516d9ca89b0c211789
# REDIRECT_URI=http://localhost:80/api/auth/login
API_SECRET=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
CLIENT_UID=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41

View File

@ -6,13 +6,12 @@
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/17 01:00:00 by apommier #+# #+# */
/* Updated: 2023/06/26 03:23:42 by apommier ### ########.fr */
/* Updated: 2023/06/26 04:10:56 by apommier ### ########.fr */
/* */
/* ************************************************************************** */
import { Controller, Request, Req, Get, Post, UseGuards, Redirect, Res, Body, UploadedFile, UseInterceptors} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { AuthService } from './auth/auth.service';
import { loginClass } from './auth/login42'
@ -42,7 +41,7 @@ import { formatWithOptions } from 'util';
@Controller('/api')
export class AppController {
constructor(private authService: AuthService,
constructor(private authService: AuthService,
private loginClass: loginClass,
private chatService: ChatService,
private userService: UsersService, ) {}
@ -53,7 +52,7 @@ export class AppController {
//========================================================================================================
//========================================================================================================
// User
// User
//========================================================================================================
//========================================================================================================
@ -127,7 +126,7 @@ export class AppController {
await this.chatService.createConv(conv);
return await this.userService.addFriend(user, data.username);
}
@UseGuards(JwtAuthGuard)
@ -168,7 +167,7 @@ export class AppController {
async refuseInvite(@Request() req, @Body() data: any) {
// return await this.userService.getFriends(req.user.username);
// console.log(`useawdawd\n\n\nr= ${req.user.username}`)
const user = await this.userService.findOne(req.user.username)
const user = await this.userService.findOne(req.user.username)
return await this.userService.refuseInvite(user, data.username);
}
@ -223,7 +222,7 @@ export class AppController {
//========================================================================================================
//========================================================================================================
// Pong
// Pong
//========================================================================================================
//========================================================================================================
@ -261,7 +260,7 @@ export class AppController {
const Esp = 1 / (1 + Math.pow(10, (data.opRank - user.rank) / this.scaleFactor))
const newRank = user.rank + this.kFactor * (0 - Esp);
user.rank = newRank;
console.log(`loss new rank= ${newRank}`);
console.log(`data loss = ${data}`)
@ -324,8 +323,8 @@ export class AppController {
{
console.log("delete invite user= ", data.username)
const user = await this.userService.findOne(req.user.username);
// user.partyInvite = user.partyInvite.filter(item => Object.values(item)[1] !== req.user.username);
console.log("user.partyInvite before", user.partyInvite)
user.partyInvite = user.partyInvite.filter((item) => Object.values(item)[1] !== data.username);
@ -340,10 +339,10 @@ export class AppController {
// const user = await this.userService.findOne(req.user.username);
// return user.rank;
return await this.userService.getHistory(data.username);
// if (user) {
// const children = user.children;
// console.log(user);
// console.log(user);
// console.log(user.children); // or perform any operations with the children
// return children;
// // You can also access specific properties of each child
@ -358,7 +357,7 @@ export class AppController {
//========================================================================================================
//========================================================================================================
// Auth
// Auth
//========================================================================================================
//========================================================================================================
@ -452,18 +451,26 @@ export class AppController {
@UseGuards(JwtAuthGuard)
@Post('/quit')
async setOffline(@Request() req) {
const user = await this.userService.findOne(req.user.username);
user.status = 0;
user.sessionNumber-- ;
if (!user.sessionNumber)
user.status = 0;
await this.userService.save(user);
console.log("User quit");
}
@UseGuards(JwtAuthGuard)
@Post('/addSession')
async addSession(@Request() req) {
const user = await this.userService.findOne(req.user.username);
user.sessionNumber++ ;
await this.userService.save(user);
}
//========================================================================================================
//========================================================================================================
// Chat
// Chat
//========================================================================================================
//========================================================================================================
@ -511,7 +518,7 @@ export class AppController {
@Post('/message')
async postMessage(@Request() req, @Body() data: any) {
//if i can post post ?
let message =
let message =
{
convid: data.convId,
sender: data.sender,
@ -522,7 +529,7 @@ export class AppController {
console.log(data);
return await this.chatService.createMessage(message, req.user.username);
}
@UseGuards(JwtAuthGuard)
@Post('/member')
async getMember(@Body() data: any) {
@ -530,7 +537,7 @@ export class AppController {
console.log(`get member= ${data.convId}`);
return await this.chatService.findConv(data.convId);
}
@UseGuards(JwtAuthGuard)
@Post('/getMessage')
async getMessage(@Body() data: any) {
@ -542,11 +549,11 @@ export class AppController {
return await this.chatService.getMessages(data.convId);
// return await this.chatService.getConv(req.user.username);
// res.json(messages);
}
@UseGuards(JwtAuthGuard)
@Post('/name')
async setName(@Body() data: any) {
@ -554,13 +561,13 @@ export class AppController {
// data.convId
return await this.chatService.setName(data.convId, data.name)
}
@UseGuards(JwtAuthGuard)
@Post('/password')
async setPassword(@Body() data: any) {
return await this.chatService.setPassword(data.convId, data.password)
}
@UseGuards(JwtAuthGuard)
@Post('/verifyPassword')
async verifyPassword(@Body() data: any) {
@ -580,7 +587,7 @@ export class AppController {
return ;
return await this.chatService.banUser(data.convId, data.username)
}
@UseGuards(JwtAuthGuard)
@Post('/admin')
async setAdmin(@Body() data: any) {
@ -588,7 +595,7 @@ export class AppController {
return ;
return await this.chatService.setAdmin(data.convId, data.username)
}
@UseGuards(JwtAuthGuard)
@Post('/mute')
async muteUser(@Body() data: any) {
@ -596,14 +603,14 @@ export class AppController {
return ;
return await this.chatService.muteUser(data.convId, data.username, data.time)
}
@UseGuards(JwtAuthGuard)
@Post('/isAdmin')
async isAdmin(@Request() req, @Body() data: any) {
console.log("isdamin= ", req.user.username, " id=", data.convId)
return await this.chatService.isAdmin(data.convId, req.user.username)
}
@UseGuards(JwtAuthGuard)
@Post('/private')
async setPrivate(@Body() data: any) {
@ -628,4 +635,4 @@ export class AppController {
return await this.chatService.joinChannel(data.convId, req.user.username)
}
}
}

View File

@ -17,8 +17,6 @@ export class loginClass {
let userId = null;
let userName = null;
console.log("process.env.REDIRECT_URI=", process.env.REDIRECT_URI)
const params = new URLSearchParams(url.split('?')[1]);
const code = params.get('code');
@ -62,11 +60,11 @@ export class loginClass {
password: null,
username: userName,
nickname: userName,
win: 0,
win: 0,
loss: 0,
rank: 1200,
userId: userId,
otp_base32: null,
otp_base32: null,
children: null,
status: 1,
// doubleAuth: 0,
@ -76,15 +74,16 @@ export class loginClass {
friends: null,
blocked: null,
photo: null,
sessionNumber: 1,
};
await this.usersService.create(user);
}
// console.log(`in login42 user= ${user}`)
const myJSON = JSON.stringify(user);
console.log(`in login42 user= ${myJSON}`)
console.log("end of login");
return (user);
// return (await this.usersService.findOne(userName));
}
}
}

View File

@ -6,7 +6,7 @@
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/17 01:00:25 by apommier #+# #+# */
/* Updated: 2023/06/26 04:02:50 by apommier ### ########.fr */
/* Updated: 2023/06/26 04:11:00 by apommier ### ########.fr */
/* */
/* ************************************************************************** */
@ -84,10 +84,15 @@ async banUser(convId: number, username: string) {
conv.banned = conv.banned || [];
if (conv.banned.find(item => item === username))
return (1);
{
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) {

View File

@ -34,7 +34,7 @@ export class User {
@Column({ nullable: true })
nickname: string;
@Column({ nullable: true })
username: string;
@ -46,22 +46,25 @@ export class User {
@Column({ default: 0 })
win: number;
@Column({ default: 0 })
loss: number;
@Column({ default: 0 })
sessionNumber: number;
@Column({ default: 0 })
rank: number;
@Column({ default: 0 }) //0 = offline | 1 = connected | 2 = in game
status: number;
@Column({ default: 0 })
userId: number;
// @Column({ default: 0 })
// doubleAuth: number;
@Column('text', { array: true, nullable: true })
friendRequest: string[];
@ -98,4 +101,4 @@ export class MatchLog {
@ManyToOne(() => User, parent => parent.children)
parent: User;
}
}

View File

@ -3,10 +3,10 @@
/* ::: :::::::: */
/* users.service.ts :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
/* By: sadjigui <sadjigui@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/17 01:00:07 by apommier #+# #+# */
/* Updated: 2023/06/24 23:30:52 by apommier ### ########.fr */
/* Updated: 2023/06/26 02:23:16 by sadjigui ### ########.fr */
/* */
/* ************************************************************************** */
@ -143,7 +143,11 @@ export class UsersService {
return (0);
user.blocked = user.blocked || [];
if (user.blocked.find(item => item === username))
return (1);
{
this.save(user);
user.blocked = user.blocked.filter((item) => item !== username);
return (2);
}
user.blocked.push(username);
this.save(user);
return (1);

View File

@ -1,8 +1,11 @@
REACT_APP_BASE_URL=bess-f2r5s13:8080
REACT_APP_SOCKET_URL=bess-f2r5s13
REACT_APP_API_SECRET=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
REACT_APP_CLIENT_UID=u-s4t2ud-2bd3c5d4f41e776f2e3d5d699d2a8421f6d0c0468ec882516d9ca89b0c211789
REACT_APP_INTRA_URL="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-2bd3c5d4f41e776f2e3d5d699d2a8421f6d0c0468ec882516d9ca89b0c211789&redirect_uri=http%3A%2F%2Fbess-f2r5s13%3A8080%2Fapi%2Fauth%2Flogin&response_type=code"
REACT_APP_BASE_URL=localhost:8080
REACT_APP_SOCKET_URL=localhost
REACT_APP_API_SECRET=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
REACT_APP_CLIENT_UID=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41
# REACT_APP_BASE_URL=92.143.191.152
# REACT_APP_BASE_URL=192.168.1.19
# REACT_APP_BASE_URL=192.168.1.19
REACT_APP_INTRA_URL="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fapi%2Fauth%2Flogin&response_type=code"
# REACT_APP_BASE_URL=92.143.191.152
# REACT_APP_BASE_URL=192.168.1.19

View File

@ -23,8 +23,9 @@ interface AlertProps {
}
function GreenAlert ({handleClose, text}: AlertProps){
{setTimeout(handleClose, 1500)}
return(
<Backdrop onClick={handleClose}>
<motion.div
onClick={(e) => e.stopPropagation()}
@ -37,7 +38,6 @@ function GreenAlert ({handleClose, text}: AlertProps){
<AiOutlineCheckCircle/>
<p>{text}</p>
</motion.div>
{setTimeout(handleClose, 1500)}
</Backdrop>
)
}

View File

@ -23,6 +23,7 @@ interface AlertProps {
}
function RedAlert ({handleClose, text}: AlertProps) {
{setTimeout(handleClose, 1500)}
return(
<Backdrop onClick={handleClose}>
<motion.div
@ -36,7 +37,6 @@ function RedAlert ({handleClose, text}: AlertProps) {
<BiErrorCircle/>
<p>{text}</p>
</motion.div>
{setTimeout(handleClose, 1500)}
</Backdrop>
)
}

View File

@ -25,6 +25,7 @@ interface AlertProps {
}
function YellowAlert ({handleClose, text, icon}: AlertProps) {
{setTimeout(handleClose, 3000)}
return(
<Backdrop onClick={handleClose}>
<motion.div
@ -53,7 +54,6 @@ function YellowAlert ({handleClose, text, icon}: AlertProps) {
<h5>{text}</h5>
</motion.div>
{setTimeout(handleClose, 3000)}
</Backdrop>
)
}

View File

@ -40,9 +40,9 @@ function AnimatedRoute () {
// Perform your desired actions before the user leaves the page
// For example, you can show a confirmation dialog or save user data
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
@ -73,7 +73,7 @@ function AnimatedRoute () {
<Route path="/profile" element={<Home/>}/>
<Route path="/profile/:username" element={<Home/>}/>
<Route path="/qr" element={<QrCode/>}/>
<Route path="/2fa" element={<DoubleAuth/>}/>
<Route path="/Social" element={<Social/>}/>
@ -94,4 +94,4 @@ function AnimatedRoute () {
)
}
export default AnimatedRoute
export default AnimatedRoute

View File

@ -1,35 +1,23 @@
import React from 'react';
import '../../styles/field.css';
// import { useHistory } from 'react-router-dom';
import { useNavigate } from "react-router-dom";
function PlayButton() {
const history = useNavigate();
// const handleButtonClick = () => {
// let path = `play`;
// history(path);
// };
const handleButtonClick = () => {
let path = `play?`;
const superpowerCheckbox = document.querySelector<HTMLInputElement>('input[value="superpower"]');
if (superpowerCheckbox && superpowerCheckbox.checked) {
path += 'superpower=true&';
}
// const obstacleCheckbox = document.querySelector<HTMLInputElement>('input[value="obstacle"]');
// if (obstacleCheckbox && obstacleCheckbox.checked) {
// path += 'obstacle=true&';
// }
const speedCheckbox = document.querySelector<HTMLInputElement>('input[value="speed"]');
if (speedCheckbox && speedCheckbox.checked) {
path += 'speed=true&';
}
// Remove the trailing '&' character
path = path.slice(0, -1);
console.log(path)
history(path);
@ -40,12 +28,11 @@ function PlayButton() {
<button onClick={handleButtonClick} className="playButton">Play</button>
{/* !buttonClicked && <button onClick={handleButtonClick}>Draw on Canvas</button> */}
<div className='checkbox'>
<p><input className="inside_checkbox" type="checkbox" value="superpower"/> Super Power</p>
{/* <p><input className="inside_checkbox" type="checkbox" value="obstacle"/> Obstacle </p> */}
<p><input className="inside_checkbox" type="checkbox" value="superpower"/> Super Power <br/> ( w = wall power ) </p>
<p><input className="inside_checkbox" type="checkbox" value="speed"/> Faster and Faster </p>
</div>
</div>
);
}
export default PlayButton;
export default PlayButton;

View File

@ -17,6 +17,7 @@ import { ImBlocked } from 'react-icons/im';
import { MdOutlineGroupAdd } from 'react-icons/md';
import { GrAdd } from 'react-icons/gr';
import { RiListSettingsLine } from 'react-icons/ri'
import { HiChatBubbleLeft } from 'react-icons/hi2'
// import { Rank } from "../../DataBase/DataRank";
import GreenAlert from "../Alert/GreenAlert.tsx";
@ -36,7 +37,7 @@ const TouchDiv = styled.div`
margin-top: 21px;
cursor: pointer;
justify-content: space-around;
&:hover {
color: #F4F3EF;
}
@ -71,7 +72,7 @@ const SideP = styled.p`
//========================================================================================================
//========================================================================================================
// Logical part
// Logical part
//========================================================================================================
//========================================================================================================
@ -84,7 +85,7 @@ interface MessageProps {
}
function Chats(){
const [isLoading, setIsLoading] = useState<boolean>(true);
const [conversations, setConversation] = useState([]);
const [partyInvite, setPartyInvite] = useState([]);
@ -100,7 +101,7 @@ function Chats(){
const socket = useRef<Socket | null>(null);
// const socket = Socket<DefaultEventsMap, DefaultEventsMap> | null
// socket = useRef( useRef<SocketIOClient.Socket | null>(null));
useEffect(()=> {
@ -137,7 +138,7 @@ function Chats(){
console.log("muted hehe");
//set mute var to true and do nothing
});
setIsLoading(false)
}
@ -159,7 +160,7 @@ function Chats(){
}, [])
useEffect(()=> {
const updateChat = async ()=> {
// if (currentChat)
// console.log(currentChat.id)
@ -188,7 +189,7 @@ function Chats(){
}, [incomingMessage, currentChat])
useEffect(()=> {
useEffect(()=> {
const getMessage = async ()=>
{
if (!currentChat)
@ -238,7 +239,7 @@ function Chats(){
setNewMessage("");
if (socket.current)
socket.current.emit('sendMessage', message);
}
}
catch(err){
console.log(err)
}
@ -250,38 +251,40 @@ function Chats(){
return ;
handleSubmit(e);
}
const [friend, setFriend] = useState("");
// const [modalOpen, setModalOpen] = useState(false);
const [addFriend, setAddFriend] = useState(false);
const [block, setBlock] = useState(false);
const [showAddFriendAlert, setShowAddFriendAlert] = useState(false);
const [showBlockAlert, setShowBlockAlert] = useState(false);
const [setting, setSetting] = useState(false);
const [newGameModalOpen, setNewGameModalOpen] = useState(false);
const [newConversationModalOpen, setNewConversationModalOpen] = useState(false);
const [selectTags, setSelectTag] = useState([{ id: 1, selectedOption: ''}]);
const [users, setUsers] = useState<User[]>([]);
const [unblock, setUnblock] = useState(false);
const closeUnblock = () => setUnblock(false);
const openNewGameModal = () => {
setNewGameModalOpen(true);
};
const closeNewGameModal = () => {
setNewGameModalOpen(false);
};
const openNewConversationModal = () => {
setNewConversationModalOpen(true);
};
const closeNewConversationModal = () => {
setNewConversationModalOpen(false);
};
@ -300,7 +303,7 @@ function Chats(){
const handleFriend = (event: { target: { value: React.SetStateAction<string>; }; }) => {
setFriend(event.target.value);
};
const handleAddFriend = async () => {
try{
console.log("friend= ", friend);
@ -321,11 +324,14 @@ function Chats(){
console.log(err)
}
};
const handleBlockFriend = async () => {
try{
const res = await api.post("/block", {username: friend})
// if(1)
if (res.data === 2)
setUnblock(true);
if (res.data === 1)
{
setBlock(true);
@ -339,12 +345,12 @@ function Chats(){
console.log(err)
}
};
const closeAddFriend = () => {
setAddFriend(false);
setShowAddFriendAlert(false);
};
const closeBlock = () => {
setBlock(false);
setShowBlockAlert(false);
@ -353,7 +359,7 @@ function Chats(){
const handleOptionChange = (selectId: number, selectedOption: string) => {
console.log("selected Option=", selectedOption)
setFriend(selectedOption);
setSelectTag((prevTags) =>
setSelectTag((prevTags) =>
prevTags.map((tag) =>
tag.id === selectId ? { ...tag, selectedOption } : tag
)
@ -362,14 +368,14 @@ function Chats(){
//========================================================================================================
//========================================================================================================
// HTML
// HTML
//========================================================================================================
//========================================================================================================
return (
<div className="chat">
<div className='navbar'>
{/* <img src={DefaultPic} alt="profile" className="pic"/> */}
<IoLogoOctocat className="catchat"/>
@ -395,7 +401,7 @@ function Chats(){
</AnimatePresence>
</TouchDiv>
<TouchDiv>
<motion.div
<motion.div
onClick={() => (block ? setBlock(false) : setBlock(true))}
>
<ImBlocked/>
@ -410,7 +416,7 @@ function Chats(){
{currentChat ? (
<TouchDiv>
<motion.div
<motion.div
onClick={() => (setting ? setSetting(false) : setSetting(true))}
>
<RiListSettingsLine/>
@ -434,7 +440,7 @@ function Chats(){
onChange={(a) => handleOptionChange(selectTag.id, a.target.value)}
>
<option value="">{
selectTag.selectedOption ? selectTag.selectedOption : "Select an option"
selectTag.selectedOption ? selectTag.selectedOption : "Select a user"
}</option>
{users.filter((item) => !selectTags.some((tag) => tag.selectedOption === item.username)).map((item, index) => (
<option key={index} value={item.username}>
@ -468,14 +474,17 @@ function Chats(){
{showBlockAlert && !block && (
<RedAlert handleClose={closeBlock} text={friend + ' was not found'} />
)}
{unblock ? (
<GreenAlert handleClose={closeUnblock} text={friend + ' was unblocked'} />
):("")}
</AnimatePresence>
</TouchDiv>
{currentChat && isAdmin ? (
<TouchDiv>
<motion.div
<motion.div
onClick={() => (setting ? setSetting(false) : setSetting(true))}
>
<RiListSettingsLine/>
<RiListSettingsLine className="block"/>
<AnimatePresence
initial={false}
onExitComplete={() => null}
@ -526,14 +535,15 @@ function Chats(){
<div key={index}
onClick={() => setCurrentChat(c)}>
<UserChat>
<img className="pic-user" src={DefaultPic} alt="User" />
{/* <img className="pic-user" src={DefaultPic} alt="User" /> */}
<HiChatBubbleLeft className="catchat"/>
<div className="infoSideBar">
<span>{c.name}</span>
{/* <SideP>Desc?</SideP> */}
</div>
</UserChat>
</div>
)})}
</div>
@ -569,7 +579,7 @@ function Chats(){
</div>
</div>
// </div>
);
);
}
export default Chats
export default Chats

View File

@ -59,7 +59,7 @@ const Modal = ({handleClose}: ModalProps) => {
const handleOptionChange = (selectId: number, selectedOption: string) => {
console.log("selected Option=", selectedOption)
setSelectTag((prevTags) =>
setSelectTag((prevTags) =>
prevTags.map((tag) =>
tag.id === selectId ? { ...tag, selectedOption } : tag
)
@ -123,7 +123,7 @@ const Modal = ({handleClose}: ModalProps) => {
onChange={(a) => handleOptionChange(selectTag.id, a.target.value)}
>
<option value="">{
selectTag.selectedOption ? selectTag.selectedOption : "Select an option"
selectTag.selectedOption ? selectTag.selectedOption : "Select a user"
}</option>
{users.filter((item) => !selectTags.some((tag) => tag.selectedOption === item.nickname)).map((item, index) => (
<option key={index} value={item.username}>
@ -137,9 +137,7 @@ const Modal = ({handleClose}: ModalProps) => {
<GrAdd onClick={addNewSelectedTag}/>
</div>
<div className="div_submit">
<Link to='#' className="submit" onClick={ saveSelectedOptions}>Submit</Link>
<Link to="#" className="submit" onClick={() => handleClose}>Cancel</Link>
<Link to='#' className="submit" onClick={saveSelectedOptions}>Submit</Link>
</div>
</div>
@ -150,9 +148,9 @@ const Modal = ({handleClose}: ModalProps) => {
<select
value={channel}
onChange={(event) => setChannel(event.target.value)}
>
<option value="">Select an option</option>
<option value="">Select a channel</option>
{convs.map((conv) => (
!(!conv.group || conv.private || (conv.banned && user && conv.banned.includes(user.username)) || (conv.members && user && conv.members.includes(user.username))) && (
<option key={conv.id} value={conv.id}>
@ -179,4 +177,4 @@ const Modal = ({handleClose}: ModalProps) => {
)
}
export default Modal
export default Modal

View File

@ -1,4 +1,4 @@
import { motion } from "framer-motion";
import { AnimatePresence, motion } from "framer-motion";
import Backdrop from "../Sidebar/Backdrop.tsx";
// import { Rank } from "../../DataBase/DataRank"
import '../../styles/Messages.css'
@ -9,6 +9,7 @@ import api from "../../script/axiosApi.tsx";
import React from "react";
import {User} from "../../../interfaces.tsx"
import { Socket } from "socket.io-client";
import GreenAlert from "../Alert/GreenAlert.tsx";
const dropIn = {
@ -161,13 +162,18 @@ const ModalSetting = ({handleClose, convId, socket }: ModalSettingProps) => {
handleClose();
}
const [unban, setUnban] = useState(false);
const closeUnban = () => setUnban(false);
const handleBan = async () => {
// console.log("ban option= ", selectedUser)
try{
// console.log("user select=", selectedUser.length)
if (!selectedUser.length)
return ;
await api.post("/ban", {convId: convId, username: selectedUser})
const res = await api.post("/ban", {convId: convId, username: selectedUser})
if (res.data === 2)
setUnban(true);
if (socket)
{
console.log("emit to ban server")
@ -207,8 +213,8 @@ const ModalSetting = ({handleClose, convId, socket }: ModalSettingProps) => {
const handleInvite = async () => {
try{
console.log("post invite bitch")
await api.post("/inviteConv", {convId: convId, username: selectedUser})
console.log("post invite bitch");
await api.post("/inviteConv", {convId: convId, username: selectedUser});
} catch(err) {
console.log(err);
}
@ -244,7 +250,7 @@ const ModalSetting = ({handleClose, convId, socket }: ModalSettingProps) => {
<Link to="#" onClick={dark} className={ privateConv ? "darkSubmit" : "submit"}>Private</Link>
</div>
{/* <p className="checkbox">Private<input className="check"type="checkbox" value="private" onChange={handleCheckPriv}/></p> */}
<p className="checkbox">Password<input type="checkbox" value="password" checked={password} onChange={handleCheckPass}/> </p>
<p className="checkbox">Password<input className="inside_ckeckbox" type="checkbox" value="password" checked={password} onChange={handleCheckPass}/> </p>
{password ? (
@ -294,7 +300,7 @@ const ModalSetting = ({handleClose, convId, socket }: ModalSettingProps) => {
<div>
<Link to="#" onClick={handleInvite} className="submit">Send</Link>
<Link to="#" onClick={handleInvite} className="submit">Invite</Link>
<Link to="#" onClick={handleBan} className="submit">Ban</Link>
<Link to="#" onClick={mute ? darkMute : lightMute} className={mute ? "darkSubmit": "submit"}>Mute</Link>
<Link to="#" onClick={handleAdmin} className="submit">Admin</Link>
@ -306,11 +312,16 @@ const ModalSetting = ({handleClose, convId, socket }: ModalSettingProps) => {
onKeyDown={handleMute}
type="number"
className="in_howLong"
placeholder="How long ?"
placeholder="Time"
value={time}
onChange={(e) => setTime(e.target.value)}
/>
):("")}
<AnimatePresence initial={false} onExitComplete={() => null}>
{unban ? (
<GreenAlert handleClose={closeUnban} text={selectedUser+": was unbanned"} />
): ("")}
</AnimatePresence>
</motion.div>
</Backdrop>

View File

@ -54,22 +54,25 @@ const ModalEdit = () => {
const handlePostNickname = async () => {
console.log("nickname=", nickname)
try {
const ret = await api.post("/nickname", { nickname: nickname });
// console.log("cest ici = ",ret);
// if (!ret)
console.log("test ret =", ret.data);
if (nickname.length < 3) {
// console.log("test ret =", ret.data);
if (nickname.length > 3) {
const ret = await api.post("/nickname", { nickname: nickname });
if (ret.data) {
console.log("ici error = ", ret.data);
window.location.reload();
}
else {
console.log("nickname already set = ", ret.data);
setErrTaken(true);
}
}
else if (nickname.length < 3)
{
setErrTooShort(true);
}
else if (ret.data) {
console.log("ici error = ", ret.data);
window.location.reload();
}
else {
console.log("nickname already set = ", ret.data);
setErrTaken(true);
}
// setUser(tmpUser.data);

View File

@ -3,16 +3,18 @@
/* ::: :::::::: */
/* Home.tsx :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: apommier <apommier@student.42.fr> +#+ +:+ +#+ */
/* By: sadjigui <sadjigui@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/09 08:19:04 by apommier #+# #+# */
/* Updated: 2023/06/24 23:26:45 by apommier ### ########.fr */
/* Updated: 2023/06/26 04:03:16 by sadjigui ### ########.fr */
/* */
/* ************************************************************************** */
// import { React, useState } from "react";
import '../styles/Profile.css'
// import '../styles/App.css'
import RedAlert from "../components/Alert/RedAlert.tsx";
import DefaultPicture from "../assets/profile.jpg";
import WinLoss from "../components/Profile/Win_Loss.tsx";
import { motion, AnimatePresence } from 'framer-motion'
@ -52,7 +54,10 @@ function Profile () {
const [isLoading, setIsLoading] = useState<boolean>(true);
const [modalOpen, setModalOpen] = useState<boolean>(false);
const [mine, setMine] = useState<boolean>(false);
const [error, setError] = useState<boolean>(false);
// const [visible, setVisible] = useState<boolean>(false);
const close = () => setModalOpen(false);
const closeError = () => setError(false);
const open = () => setModalOpen(true);
const { username } = useParams();
@ -76,6 +81,7 @@ function Profile () {
console.log('File uploaded successfully');
window.location.reload();
} catch (error) {
setError(true);
console.error('Error uploading file:', error);
}
}
@ -146,6 +152,14 @@ function Profile () {
<>
<label htmlFor="file-input" className="edit_name"><MdOutlinePhotoLibrary/></label>
<input type="file" id="file-input" className="file-input" accept="image/*" onChange={handleFileChange} />
<AnimatePresence initial={false} onExitComplete={() => null}>
{error ? (
<RedAlert handleClose={closeError} text={'Error : upload failed'} />
): ("")}
</AnimatePresence>
</>
)}
</motion.div>
@ -191,7 +205,7 @@ function Home () {
const tmpUser = await api.get("/profile");
setUser(tmpUser.data);
}
else
else
{
const tmpUser = await api.post("/user", {username: username});
setUser(tmpUser.data);
@ -224,12 +238,12 @@ function Home () {
):("")}
</div>
<div className="home">
<motion.div
<motion.div
// style={{
// backdropFilter: move ? "blur(10px)" : "none",
// WebkitBackdropFilter: move ? "blur(10px)" : "none"
// }}
animate={{x: move ? '-50%' : '30%'}}
animate={{x: move ? '-50%' : '25%'}}
transition={{type: "tween", duration: 0.5}}>
<Profile/>
</motion.div>

View File

@ -6,7 +6,8 @@ import "../styles/App.css";
import api from '../script/axiosApi.tsx';
import QRCodeStyling from "qr-code-styling";
import { motion } from 'framer-motion'
import { AnimatePresence, motion } from 'framer-motion'
import RedAlert from "../components/Alert/RedAlert.tsx";
@ -36,6 +37,8 @@ function QrCode () {
const [secret, setSecret] = useState(false);
const [code, setCode] = useState('');
const [activated, setActivated] = useState(false);
const [err, setErr] = useState(false);
const closeErr = () => setErr(false);
// const history = useHistory();
@ -80,6 +83,10 @@ function QrCode () {
const res = await api.post("/verifyOtp", {token: code})
console.log("res= ", res.data)
console.log("res= ", res)
if (!res.data)
{
setErr(true);
}
if (res.data === 1)
{
console.log("registered")
@ -158,6 +165,11 @@ function QrCode () {
) : (
<button className="desactivate" onClick={handleDesactivate}>Desactivate 2FA</button>
)}
<AnimatePresence
initial={false}
onExitComplete={() => null}>
{err ? (<RedAlert handleClose={closeErr} text="Error: Bad intput. Try again"/>):("")}
</AnimatePresence>
</>
{/* {!localStorage.getItem('token') && (

View File

@ -15,9 +15,10 @@ input.qr{
border-radius: 5px;
background-color: rgb(0, 0, 0);
margin : 1%;
color:rgb(42, 41, 41);
border-style: solid;
border-width: 1px;
border-color:rgb(42, 41, 41);
border-style: solid;
border-width: 1px;
color: #ccc;
}
.desactivate {

View File

@ -233,9 +233,9 @@ p {
backdrop-filter: sepia(90%);
background-color: rgba(0, 0, 0, 0.3);
border-radius: 4px;
width: 11rem;
height: 1.5rem;
margin-top: 1rem;
width: 15rem;
height: 2rem;
margin-top: 1.3rem;
}
.greenAlert{
@ -385,4 +385,11 @@ input.in_howLong{
.block{
font-size: 25px;
margin-left: 12px;
margin-top: 0.2rem;
}
.inside_ckeckbox{
height: 25px;
margin-left: -50px;
}