change dir name frontend -> react and api/profile on the way

This commit is contained in:
kinou-p 2023-05-09 16:49:00 +02:00
parent 38f967576f
commit c0f402455c
41 changed files with 187 additions and 290 deletions

View File

@ -6,6 +6,7 @@ import { AuthService } from './auth/auth.service';
// import { Login42 } from './auth/login42' // import { Login42 } from './auth/login42'
import { loginClass } from './auth/login42' import { loginClass } from './auth/login42'
// import { loginClass } from './auth/test'
@Controller('/api') @Controller('/api')
@ -16,32 +17,48 @@ export class AppController {
// @Post('auth/login') // @Post('auth/login')
// async login() { // async login() {
// const user = Login42(); // const user = Login42();
// return this.authService.login(user); // return this.authService.login5(user);
// } // }
@Redirect('http://localhost/token', 302) @Redirect('http://localhost/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;
console.log("login function"); const user = await this.loginClass.Login42(url);
console.log(`url = ${url}`); console.log(`user in auth/login= ${user}`);
const data = this.authService.login(user);
console.log(`all data in api = ${data}`)
const myJSON = JSON.stringify(data);
console.log(`response2= ${myJSON}`)
console.log(`data in api = ${(await data).access_token}`)
const token = (await data).access_token;
return { url: `http://localhost/token?data=${encodeURIComponent(JSON.stringify(token))}` };
// console.log("login function");
// console.log(`url = ${url}`);
// const user = this.loginClass.Login42(url); // const user = this.loginClass.Login42(url);
const user = this.loginClass.Login42(url); // console.log("login42 done");
console.log("login42 done"); // console.log(`user= ${user}`);
console.log(`user= ${user}`); // console.log(`dataaaa = ${data}`);
const data2 = this.authService.login(user); // console.log("before return");
const data = (await data2).access_token;
console.log(`dataaaa = ${data}`);
console.log("before return");
// return { data }; // return { data };
return { url: `http://localhost/token?data=${encodeURIComponent(JSON.stringify(data))}` };
} }
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get('profile') @Get('profile')
getProfile(@Request() req) { getProfile(@Request() req) {
console.log("in profile get") // const myJSON = JSON.stringify(req.user);
// console.log(`req user api= ${req.user}`)
// console.log(`json user api= ${myJSON}`)
return req.user; return req.user;
// const user = req.user;
// const returned = {
// username: user.username,
// sub: user.sub,
// };
// console.log(`user in api = ${returned}`)
// return returned;
} }
@Get(`conversation/:id`) @Get(`conversation/:id`)

View File

@ -20,8 +20,12 @@ export class AuthService {
} }
async login(user: any) { async login(user: any) {
console.log(`in login user= ${user.username}`)
const payload = { username: user.username, sub: user.userId }; const payload = { username: user.username, sub: user.userId };
console.log(`in login payload name= ${payload.username}`)
console.log(`in login payload sub= ${payload.sub}`)
return { return {
username: user.username,
access_token: this.jwtService.sign(payload), access_token: this.jwtService.sign(payload),
}; };
} }

View File

@ -14,6 +14,6 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
} }
async validate(payload: any) { async validate(payload: any) {
return { userId: payload.sub, username: payload.username }; return { userId: payload.userId, username: payload.nickname };
} }
} }

View File

@ -9,31 +9,18 @@ import { User } from '../model/item.entity';
@Injectable() @Injectable()
export class loginClass { export class loginClass {
// const userService = new UsersService();
constructor(private readonly usersService: UsersService) {}; constructor(private readonly usersService: UsersService) {};
async Login42(url: string) async Login42(url: string)
{ {
// const [token, setToken] = useState(null);
// const [userId, setUserId] = useState(null);
// const [userName, setUserName] = useState(null);
// const usersService = UsersService;
// constructor(private readonly usersService: UsersService) {}
let token = null; let token = null;
let userId = null; let userId = 0;
let userName = null; let userName = null;
// let = null;
// const usersService = UsersService;
// const private , usersService: UsersService
// const url = new URL(urlString);
console.log("you said yes to connect with 42");
const params = new URLSearchParams(url.split('?')[1]); const params = new URLSearchParams(url.split('?')[1]);
// const params = new URLSearchParams(url);
console.log(`params is= ${params}`);
const code = params.get('code'); const code = params.get('code');
console.log(`code is= ${code}`);
const data = { const data = {
grant_type: 'authorization_code', grant_type: 'authorization_code',
@ -43,73 +30,46 @@ export class loginClass {
redirect_uri: 'http://localhost:80/api/auth/login', redirect_uri: 'http://localhost:80/api/auth/login',
}; };
axios.post('https://api.intra.42.fr/oauth/token', data) try {
.then(response => { const response = await axios.post('https://api.intra.42.fr/oauth/token', data);
// handle success response
// console.log(response);
token = response.data.access_token; token = response.data.access_token;
// setToken(token);
// console.log(`token= ${token}`); const response2 = await axios.get('https://api.intra.42.fr/v2/me', {
axios.get('https://api.intra.42.fr/oauth/token/info', {
headers: { headers: {
Authorization: `Bearer ${token}` Authorization: `Bearer ${token}`
} }
}) });
.then(response => { userName = response2.data.login;
// console.log(response) console.log(`all user data= ${response2.data}`)
userId = response.data.resource_owner_id;
// setUserId(userId);
// console.log(userId);
// axios.get(`https://api.intra.42.fr/v2/users/${userId}`)
// axios.get(`https://api.intra.42.fr/v2/me`)
axios.get('https://api.intra.42.fr/v2/me', {
headers: {
Authorization: `Bearer ${token}`
} }
}) catch(error)
.then(response => { {
// console.log(response); console.log(error);
// const login = response.data.login; return ;
// console.log(`login= ${login}`); }
// setUserName(response.data.login); console.log(`username before serach= ${userName}`)
userName = response.data.login
// console.log(`username= ${userName}`);
// Gérer les données de réponse ici
})
.catch(error => {
console.error(error);
// Gérer les erreurs ici
});
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
// handle error response
console.error(error);
});
// async findOne(username: string): Promise<User> {
let user = await this.usersService.findOne(userName); let user = await this.usersService.findOne(userName);
if (!user) { if (!user) {
// throw new NotFoundException(`User with username '${userName}' not found`); console.log(`no user, creating one`)
// user = { nickname: userName}; user = {
const user = {
name: null, name: null,
description: null, description: null,
id: null, id: null,
password: null, password: null,
username: userName,
nickname: userName, nickname: userName,
win: 0, win: 0,
loose: 0, loose: 0,
rank: 0, rank: 0,
userId: userId,
}; };
await this.usersService.create(user); await this.usersService.create(user);
} }
return user; console.log(`in login42 user= ${user}`)
const myJSON = JSON.stringify(user);
console.log(`in login42 user2= ${myJSON}`)
console.log("end of login");
return (await this.usersService.findOne(userName));
} }
} }

View File

@ -0,0 +1,95 @@
// import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { UsersService } from '../users/users.service';
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from '../model/item.entity';
@Injectable()
export class loginClass {
constructor(private readonly usersService: UsersService) {};
async Login42(url: string)
{
let token = null;
let userId = 0;
let userName = null;
// let = null;
console.log("you said yes to connect with 42");
const params = new URLSearchParams(url.split('?')[1]);
console.log(`params is= ${params}`);
const code = params.get('code');
console.log(`code is= ${code}`);
const data = {
grant_type: 'authorization_code',
client_id: 'u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41',
client_secret: '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',
code: code,
redirect_uri: 'http://localhost:80/api/auth/login',
};
await axios.post('https://api.intra.42.fr/oauth/token', data)
.then(response => {
token = response.data.access_token;
console.log("HEEEEEEEERRREEEEEEE")
axios.get('https://api.intra.42.fr/oauth/token/info', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
userId = response.data.resource_owner_id;
axios.get('https://api.intra.42.fr/v2/me', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
console.log(`data get success data= ${response.data}`)
userName = response.data.login
})
.catch(error => {
console.log("ERROR BITCH");
console.error(error);
});
})
.catch(error => {
console.log("ERROR BITCH");
console.error(error);
});
})
.catch(error => {
console.log("ERROR BITCH");
console.error(error);
});
console.log(`username before serach= ${userName}`)
let user = await this.usersService.findOne(userName);
if (!user) {
console.log(`no user, creating one`)
user = {
name: null,
description: null,
id: null,
password: null,
username: userName,
nickname: userName,
win: 0,
loose: 0,
rank: 0,
userId: userId,
};
await this.usersService.create(user);
}
console.log(`in login42 user= ${user}`)
const myJSON = JSON.stringify(user);
console.log(`in login42 user2= ${myJSON}`)
console.log("end of login");
return (await this.usersService.findOne(userName));
}
}

View File

@ -63,6 +63,9 @@ export abstract class BaseEntity {
@Column({ nullable: true }) @Column({ nullable: true })
nickname: string; nickname: string;
@Column({ nullable: true })
username: string;
@Column({ nullable: true }) @Column({ nullable: true })
password: string; password: string;
@ -80,4 +83,7 @@ export abstract class BaseEntity {
@Column({ default: 0 }) @Column({ default: 0 })
rank: number; rank: number;
@Column({ default: 0 })
userId: number;
} }

View File

@ -25,7 +25,7 @@ services:
ports: ports:
- 8080:8080 - 8080:8080
volumes: volumes:
- ./frontend:/app - ./react:/app
networks: networks:
- pongNetwork - pongNetwork
entrypoint: ["sh", "-c" , "npm install && npm run start:dev"] entrypoint: ["sh", "-c" , "npm install && npm run start:dev"]

View File

@ -1,11 +0,0 @@
import axios from 'axios';
const api = axios.create({
baseURL: 'https://localhost/api',
withCredentials: true,
headers: {
Authorization: 'Bearer My token here',
},
});
export default api;

View File

@ -1,82 +0,0 @@
// import GoogleLogin from 'react-google-login';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
// import setupLogin from '../script/login42';
// import React, { useEffect } from 'react';
function Login42()
{
const [token, setToken] = useState(null);
const [userId, setUserId] = useState(null);
const [userName, setUserName] = useState(null);
useEffect(() => {
console.log("you said yes to connect with 42");
const url = new URL(window.location.href);
const code = url.searchParams.get('code');
console.log(`code is= ${code}`);
const data = {
grant_type: 'authorization_code',
client_id: 'u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41',
client_secret: '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',
code: code,
redirect_uri: 'http://localhost:8080/login42',
};
axios.post('https://api.intra.42.fr/oauth/token', data)
.then(response => {
// handle success response
console.log(response);
const token = response.data.access_token;
setToken(token);
console.log(`token= ${token}`);
axios.get('https://api.intra.42.fr/oauth/token/info', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
console.log(response)
const userId = response.data.resource_owner_id;
setUserId(userId);
console.log(userId);
// axios.get(`https://api.intra.42.fr/v2/users/${userId}`)
// axios.get(`https://api.intra.42.fr/v2/me`)
axios.get('https://api.intra.42.fr/v2/me', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
console.log(response);
const login = response.data.login;
console.log(`login= ${login}`);
setUserName(response.data.login);
console.log(`username= ${userName}`);
// Gérer les données de réponse ici
})
.catch(error => {
console.error(error);
// Gérer les erreurs ici
});
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
// handle error response
console.error(error);
});
}, []);
return (
<div>
<p>Le token d'accès est : {userName}</p>
</div>
);
}
export default Login42;

View File

@ -1,14 +0,0 @@
// export const login()
// {
// alert("Le bouton a été cliqué !");
// var formulaire = document.getElementById("loginForm");
// formulaire.submit();
// }
export const login = () => {
console.log('Hello from myFunction');
// alert("Le bouton a été cliqué !");
var formulaire = document.getElementById("loginForm");
formulaire.submit();
}

View File

@ -1,91 +0,0 @@
// function setupLogin()
// {
// // alert("Le bouton a été cliqué !");
// console.log('Hello from login42');
// }
// export default setupLogin;
function Login42()
{
const [token, setToken] = useState(null);
const [userId, setUserId] = useState(null);
const [login, setLogin] = useState(null);
useEffect(() => {
console.log("you said yes to connect with 42");
const url = new URL(window.location.href);
const code = url.searchParams.get('code');
console.log(`code is= ${code}`);
const data = {
grant_type: 'authorization_code',
client_id: 'u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41',
client_secret: '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',
code: code,
redirect_uri: 'http://localhost:8080/login42',
};
axios.post('https://api.intra.42.fr/oauth/token', data)
.then(response => {
// handle success response
console.log(response);
const token = response.data.access_token;
setToken(token);
console.log(`token= ${token}`);
axios.get('https://api.intra.42.fr/oauth/token/info', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
console.log(response)
const userId = response.data.resource_owner_id;
setUserId(userId);
console.log(userId);
// axios.get(`https://api.intra.42.fr/v2/users/${userId}`)
// axios.get(`https://api.intra.42.fr/v2/me`)
axios.get('https://api.intra.42.fr/v2/me', {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(response => {
console.log(response);
const login = response.data.login;
setLogin(login);
// Gérer les données de réponse ici
})
.catch(error => {
console.error(error);
// Gérer les erreurs ici
});
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
// handle error response
console.error(error);
});
}, []);
return (
<div className="header">
<a href="http://localhost" className="box menu"> <p className="userTxt">Menu</p> </a>
<div className="box headerName">
<a href="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Flogin42&response_type=code"
className="center pong">PONG</a>
</div>
<a href="http://localhost/pong" className="box username">
<p className="userTxt">{login}</p>
{/* <img className="pp center" src="../../public/logo192.png" alt="profile picture"> */}
<img src={logo} className="pp center" alt="logo" />
</a>
</div>
);
}
export default Login42;

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

Before

Width:  |  Height:  |  Size: 5.2 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

View File

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -14,7 +14,14 @@ function Home()
const login2 = () => { const login2 = () => {
console.log('Hello from myFunction'); console.log('Hello from myFunction');
api.get('/profile').then((response) => { api.get('/profile').then((response) => {
console.log(`response= ${response}`) const data = response;
// const parsedData = JSON.parse(response.data);
// console.log(`response= ${parsedData}`)
const myJSON = JSON.stringify(data);
console.log(`response2= ${myJSON}`)
console.log(`response= ${data}`)
}); });
// alert("Le bouton a été cliqué !"); // alert("Le bouton a été cliqué !");
// var formulaire = document.getElementById("loginForm"); // var formulaire = document.getElementById("loginForm");

View File

@ -5,7 +5,7 @@ import './styles/index.css';
import App from './components/App'; import App from './components/App';
import Header from './components/Header'; import Header from './components/Header';
import Home from './components/Home'; import Home from './components/Home';
import Login42 from './components/Login42'; // import Login42 from './components/Login42';
import Head from './components/Head'; import Head from './components/Head';
import Field from './components/Field'; import Field from './components/Field';
import PlayButton from './components/PlayButton'; import PlayButton from './components/PlayButton';
@ -23,7 +23,7 @@ root.render(
<Route exact path="/" element={<Home/>}/> <Route exact path="/" element={<Home/>}/>
<Route exact path="/pong" element={<PlayButton />}/> <Route exact path="/pong" element={<PlayButton />}/>
<Route exact path="/pong/play" element={<Field />}/> <Route exact path="/pong/play" element={<Field />}/>
<Route exact path="/login42" element={<Login42 />}/> {/* <Route exact path="/login42" element={<Login42 />}/> */}
<Route exact path="/token" element={<SuccessToken />}/> <Route exact path="/token" element={<SuccessToken />}/>
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>

View File

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -7,15 +7,20 @@ import axios from 'axios';
function getToken() { function getToken() {
// your code to retrieve the token from localStorage or any other source // your code to retrieve the token from localStorage or any other source
const token = localStorage.getItem('token'); const token = localStorage.getItem('token');
if (typeof token === 'string') {
console.log("is a string !!!")
}
return token; return token;
} }
console.log(`getToken = ${getToken()}`) console.log(`getToken = ${getToken()}`)
console.log(`Bearer ${localStorage.getItem("token")}`)
const api = axios.create({ let api = axios.create({
baseURL: 'http://localhost/api', baseURL: 'http://localhost/api',
headers: { headers: {
Authorization: `Bearer ${getToken()}`, // Authorization: `Bearer ${getToken()}`,
Authorization : `Bearer ${localStorage.getItem("token")}`
}, },
withCredentials: true, withCredentials: true,
}); });

View File

@ -5,10 +5,11 @@ function SuccessToken() {
const location = useLocation(); const location = useLocation();
const { data } = queryString.parse(location.search); const { data } = queryString.parse(location.search);
// localStorage data.token; // localStorage data.token;
console.log(`prout token= ${data}`) const cleanData = data.slice(1, -1);
localStorage.setItem('token', `${data}`); // console.log(`prout token= ${cleanData}`)
localStorage.setItem('token', `${cleanData}`);
console.log(`prout token2= ${localStorage.getItem('token')}`) console.log(`prout token2= ${localStorage.getItem('token')}`)
// window.location.replace("http://localhost/pong"); window.location.replace("http://localhost/pong");
// return ( // return (
// <div> // <div>