add chat entity and win and loss controller, add commented route in react for the chat

This commit is contained in:
kinou-p 2023-05-10 03:22:59 +02:00
parent c0f402455c
commit a4f79c56e1
18 changed files with 239 additions and 254 deletions

View File

@ -1,18 +1,22 @@
import { Controller, Request, Req, Get, Post, UseGuards, Redirect } from '@nestjs/common'; import { Controller, Request, Req, Get, Post, UseGuards, Redirect, Res } from '@nestjs/common';
import { JwtAuthGuard } from './auth/jwt-auth.guard'; import { JwtAuthGuard } from './auth/jwt-auth.guard';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth/auth.service'; import { AuthService } from './auth/auth.service';
// import { Login42 } from './auth/login42'
import { loginClass } from './auth/login42' import { loginClass } from './auth/login42'
import { ChatService } from './chat/chat.service';
import { UsersService } from './users/users.service';
// import { AuthGuard } from '@nestjs/passport';
// import { Login42 } from './auth/login42'
// import { loginClass } from './auth/test' // import { loginClass } from './auth/test'
@Controller('/api') @Controller('/api')
export class AppController { export class AppController {
constructor(private authService: AuthService, constructor(private authService: AuthService,
private loginClass: loginClass ) {} private loginClass: loginClass,
private chatService: ChatService,
private userService: UsersService, ) {}
// @Post('auth/login') // @Post('auth/login')
// async login() { // async login() {
@ -30,7 +34,7 @@ export class AppController {
console.log(`all data in api = ${data}`) console.log(`all data in api = ${data}`)
const myJSON = JSON.stringify(data); const myJSON = JSON.stringify(data);
console.log(`response2= ${myJSON}`) console.log(`all data json version= ${myJSON}`)
console.log(`data in api = ${(await data).access_token}`) console.log(`data in api = ${(await data).access_token}`)
const token = (await data).access_token; const token = (await data).access_token;
@ -48,9 +52,9 @@ export class AppController {
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Get('profile') @Get('profile')
getProfile(@Request() req) { getProfile(@Request() req) {
// const myJSON = JSON.stringify(req.user); const myJSON = JSON.stringify(req.user);
// console.log(`req user api= ${req.user}`) console.log(`req user api= ${req.user}`)
// console.log(`json user api= ${myJSON}`) console.log(`json user api= ${myJSON}`)
return req.user; return req.user;
// const user = req.user; // const user = req.user;
// const returned = { // const returned = {
@ -61,8 +65,31 @@ export class AppController {
// return returned; // return returned;
} }
@Get(`conversation/:id`) @UseGuards(JwtAuthGuard)
getConv(){ @Post('/win')
async addWin(@Request() req) {
const user = await this.userService.findOne(req.user.username);
user.win++;
this.userService.save(user);
}
@UseGuards(JwtAuthGuard)
@Post('/loss')
async addLoss(@Request() req) {
const user = await this.userService.findOne(req.user.username);
user.loss++;
this.userService.save(user);
}
// @UseGuards(JwtAuthGuard)
// @Post('/api/victory')
// addVictory() {
// this.userService.findOneBy()
// }
@Get('/api/chat')
async Chat(@Res() res) {
const messages = await this.chatService.getMessages();
res.json(messages);
} }
} }

View File

@ -6,20 +6,23 @@ import { AuthModule } from './auth/auth.module';
import { loginClass } from './auth/login42'; import { loginClass } from './auth/login42';
// import { UsersService } from './users/users.service'; // in add // import { UsersService } from './users/users.service'; // in add
import { TypeOrmModule } from '@nestjs/typeorm'; // import { TypeOrmModule } from '@nestjs/typeorm';
import { getTypeOrmConfig } from './config/config.service'; // import { getTypeOrmConfig } from './config/config.service';
import { User } from './model/item.entity'; // import { User } from './model/item.entity';
// import { UsersService } from './users/users.service'; // import { UsersService } from './users/users.service';
import { UsersModule } from './users/users.module'; import { UsersModule } from './users/users.module';
// import { ChatService } from './chat/chat.service';
import { ChatModule } from './chat/chat.module';
@Module({ @Module({
imports: imports:
[ [
AuthModule, AuthModule,
UsersModule, UsersModule,
ChatModule,
], ],
controllers: [AppController], controllers: [AppController],
providers: [AppService, loginClass], providers: [AppService, loginClass,],
// providers: [AppService, UsersService],//in add // providers: [AppService, UsersService],//in add
}) })

View File

@ -20,12 +20,13 @@ export class AuthService {
} }
async login(user: any) { async login(user: any) {
console.log(`in login user= ${user.username}`) const myJSON = JSON.stringify(user);
// console.log(`in login all user= ${myJSON}`)
// 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 name= ${payload.username}`)
console.log(`in login payload sub= ${payload.sub}`) // 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,8 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
} }
async validate(payload: any) { async validate(payload: any) {
return { userId: payload.userId, username: payload.nickname }; console.log("in validate function")
console.log(`userid= ${payload.sub} nickname= ${payload.username}`)
return { userId: payload.sub, username: payload.username };
} }
} }

View File

@ -5,7 +5,7 @@ import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
import { User } from '../model/item.entity'; import { User } from '../model/user.entity';
@Injectable() @Injectable()
export class loginClass { export class loginClass {
@ -14,7 +14,7 @@ export class loginClass {
async Login42(url: string) async Login42(url: string)
{ {
let token = null; let token = null;
let userId = 0; let userId = null;
let userName = null; let userName = null;
// let = null; // let = null;
@ -40,7 +40,10 @@ export class loginClass {
} }
}); });
userName = response2.data.login; userName = response2.data.login;
console.log(`all user data= ${response2.data}`) userId = parseInt(response2.data.id, 10);
// console.log(`all user data= ${response2.data}`)
// const myJSON = JSON.stringify(response2.data);
// console.log(`json version= ${myJSON}`)
} }
catch(error) catch(error)
{ {
@ -48,28 +51,30 @@ export class loginClass {
return ; return ;
} }
console.log(`username before serach= ${userName}`) console.log(`username before serach= ${userName}`)
console.log(`ID before serach= ${userId}`)
let user = await this.usersService.findOne(userName); let user = await this.usersService.findOne(userName);
if (!user) { if (!user) {
console.log(`no user, creating one`) console.log(`no user, creating one`);
user = { user = {
name: null, // name: null,
description: null, // description: null,
id: null, id: null,
password: null, password: null,
username: userName, username: userName,
nickname: userName, nickname: userName,
win: 0, win: 0,
loose: 0, loss: 0,
rank: 0, rank: 1200,
userId: userId, userId: userId,
}; };
await this.usersService.create(user); await this.usersService.create(user);
} }
console.log(`in login42 user= ${user}`) // console.log(`in login42 user= ${user}`)
const myJSON = JSON.stringify(user); const myJSON = JSON.stringify(user);
console.log(`in login42 user2= ${myJSON}`) console.log(`in login42 user= ${myJSON}`)
console.log("end of login"); console.log("end of login");
return (await this.usersService.findOne(userName)); return (user);
// return (await this.usersService.findOne(userName));
} }
} }

View File

@ -1,95 +0,0 @@
// 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

@ -0,0 +1,23 @@
// import { Module } from '@nestjs/common';
// @Module({})
// export class ChatModule {}
import { Module } from '@nestjs/common';
import { ChatService} from './chat.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { getTypeOrmConfig } from '../config/config.service';
import { Chat } from '../model/chat.entity';
@Module({
imports:
[
TypeOrmModule.forRoot(getTypeOrmConfig()),
TypeOrmModule.forFeature([Chat]),
// TypeOrmModule.forFeature([UserRepository]),
],
providers:[ChatService],
exports: [ChatService],
})
export class ChatModule {}

View File

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

View File

@ -0,0 +1,22 @@
// import { Injectable } from '@nestjs/common';
// @Injectable()
// export class ChatService {}
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Chat } from '../model/chat.entity';
@Injectable()
export class ChatService {
constructor(@InjectRepository(Chat) private chatRepository: Repository<Chat>,) {}
async createMessage(chat: Chat): Promise<Chat> {
return await this.chatRepository.save(chat);
}
async getMessages(): Promise<Chat[]> {
return await this.chatRepository.find();
}
}

View File

@ -1,89 +0,0 @@
// // import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
// import {Entity, PrimaryGeneratedColumn, Column} from 'typeorm';
// @Entity()
// export class User {
// @PrimaryGeneratedColumn()
// id: number;
// @Column()
// nickName: string;
// @Column()
// Password: string;
// @Column()
// email: string;
// @Column()
// password: string;
// @Column()
// win: number;
// @Column()
// loose: number;
// // friend
// // joined chat
// // jsp
// // prout
// }
// base.entity.ts
// @PrimaryGeneratedColumn('uuid')
// id: string;
// @Column({ type: 'boolean', default: true })
// isActive: boolean;
// @Column({ type: 'boolean', default: false })
// isArchived: boolean;
// @CreateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
// createDateTime: Date;
// @Column({ type: 'varchar', length: 300 })
// createdBy: string;
// @UpdateDateColumn({ type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
// lastChangedDateTime: Date;
// @Column({ type: 'varchar', length: 300 })
// lastChangedBy: string;
// @Column({ type: 'varchar', length: 300, nullable: true })
// internalComment: string | null;
import { PrimaryGeneratedColumn, Column, UpdateDateColumn, CreateDateColumn } from 'typeorm';
export abstract class BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ nullable: true })
nickname: string;
@Column({ nullable: true })
username: string;
@Column({ nullable: true })
password: string;
// @Column({ nullable: true })
// email: string;
// @Column({ nullable: true })
// password: string;
@Column({ default: 0 })
win: number;
@Column({ default: 0 })
loose: number;
@Column({ default: 0 })
rank: number;
@Column({ default: 0 })
userId: number;
}

View File

@ -0,0 +1,19 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, BaseEntity } from 'typeorm';
@Entity()
// export class Chat extends BaseEntity {
export class Chat{
@PrimaryGeneratedColumn('uuid')
id: number;
@Column()
email: string;
@Column({ unique: true })
text: string;
@CreateDateColumn()
createdAt: Date;
}

View File

@ -1,13 +0,0 @@
// item.entity.ts
import { Entity, Column } from 'typeorm';
import { BaseEntity } from './base.entity';
@Entity({ name: 'User' })
export class User extends BaseEntity {
@Column({ type: 'varchar', length: 300 , nullable: true})
name: string;
@Column({ type: 'varchar', length: 300 , nullable: true})
description: string;
}

View File

@ -0,0 +1,43 @@
// item.entity.ts
import { Entity, Column, PrimaryGeneratedColumn, BaseEntity } from 'typeorm';
// import { BaseEntity } from './base.entity';
// @Column({ type: 'varchar', length: 300 , nullable: true})
// name: string;
// @Column({ type: 'varchar', length: 300 , nullable: true})
// description: string;
@Entity({ name: 'User' })
// export class User extends BaseEntity {
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({ nullable: true })
nickname: string;
@Column({ nullable: true })
username: string;
@Column({ nullable: true })
password: string;
// @Column({ nullable: true })
// email: string;
// @Column({ nullable: true })
// password: string;
@Column({ default: 0 })
win: number;
@Column({ default: 0 })
loss: number;
@Column({ default: 0 })
rank: number;
@Column({ default: 0 })
userId: number;
}

View File

@ -3,7 +3,7 @@ import { UsersService} from './users.service';
import { TypeOrmModule } from '@nestjs/typeorm'; import { TypeOrmModule } from '@nestjs/typeorm';
import { getTypeOrmConfig } from '../config/config.service'; import { getTypeOrmConfig } from '../config/config.service';
import { User } from '../model/item.entity'; import { User } from '../model/user.entity';
@Module({ @Module({
imports: imports:

View File

@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm'; import { Repository } from 'typeorm';
import { User } from '../model/item.entity'; import { User } from '../model/user.entity';
@Injectable() @Injectable()
@ -24,7 +24,11 @@ export class UsersService {
} }
async findOne(username: string): Promise<User> { async findOne(username: string): Promise<User> {
return await this.userRepository.findOneBy({nickname: username}); return await this.userRepository.findOneBy({username: username});
}
async save(user: User): Promise<User> {
return await this.userRepository.save(user);
} }
} }

View File

@ -113,23 +113,23 @@ networks:
driver: bridge driver: bridge
volumes: volumes:
front_files: # front_files:
driver: local # driver: local
driver_opts: # driver_opts:
type: none # type: none
o: 'bind' # o: 'bind'
device: '/frontend' # device: '/frontend'
dbdata: # dbdata:
driver: local # driver: local
driver_opts: # driver_opts:
type: none # type: none
o: 'bind' # o: 'bind'
device: '/home/apommier/data/mariadb' # device: '/home/apommier/data/mariadb'
back: # back:
driver: local # driver: local
driver_opts: # driver_opts:
type: none # type: none
o: 'bind' # o: 'bind'
device: '/backend' # device: '/backend'
db: db:
driver: local driver: local

View File

@ -18,9 +18,9 @@ function Home()
// const parsedData = JSON.parse(response.data); // const parsedData = JSON.parse(response.data);
// console.log(`response= ${parsedData}`) // console.log(`response= ${parsedData}`)
const myJSON = JSON.stringify(data); const myJSON = JSON.stringify(response.data);
console.log(`response2= ${myJSON}`) console.log(`data response= ${myJSON}`)
console.log(`response= ${data}`) // console.log(`response= ${data}`)
}); });
// alert("Le bouton a été cliqué !"); // alert("Le bouton a été cliqué !");
@ -42,6 +42,12 @@ function Home()
<div className ="loginForm"> <div className ="loginForm">
<button className="submit" onClick={login2}>test button</button> <button className="submit" onClick={login2}>test button</button>
</div> </div>
<div className ="loginForm">
<button className="submit" onClick={() => api.post('/win')}>add win</button>
</div>
<div className ="loginForm">
<button className="submit" onClick={() => api.post('/loss')}>add loss</button>
</div>
</div> </div>
// href="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2Flocalhost%3A80%2Fapi%2Fauth%2Flogin&response_type=code"> // href="https://api.intra.42.fr/oauth/authorize?client_id=u-s4t2ud-6d29dfa49ba7146577ffd8bf595ae8d9e5aaa3e0a9615df18777171ebf836a41&redirect_uri=http%3A%2F%2Flocalhost%3A80%2Fapi%2Fauth%2Flogin&response_type=code">
// console.log('simple login button clicked'); // console.log('simple login button clicked');

View File

@ -23,8 +23,15 @@ 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="/token" element={<SuccessToken />}/> <Route exact path="/token" element={<SuccessToken />}/>
{/* ------- ROUTE FOR CHAT APP HERE --------- */}
{/* <Route exact path="/chat" element={<NOM DU COMPONENT == index dans le tuto/>}/> */}
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>
</> </>
@ -34,3 +41,5 @@ root.render(
// to log results (for example: reportWebVitals(console.log)) // to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(); reportWebVitals();
{/* <Route exact path="/login42" element={<Login42 />}/> */}