From a4f79c56e1cbac11f27e56b22e8d27b69e49b1d4 Mon Sep 17 00:00:00 2001 From: kinou-p Date: Wed, 10 May 2023 03:22:59 +0200 Subject: [PATCH] add chat entity and win and loss controller, add commented route in react for the chat --- api/src/app.controller.ts | 51 +++++++++++++---- api/src/app.module.ts | 11 ++-- api/src/auth/auth.service.ts | 9 +-- api/src/auth/jwt.strategy.ts | 4 +- api/src/auth/login42.ts | 27 +++++---- api/src/auth/login42old.ts | 95 ------------------------------- api/src/chat/chat.module.ts | 23 ++++++++ api/src/chat/chat.service.spec.ts | 18 ++++++ api/src/chat/chat.service.ts | 22 +++++++ api/src/model/base.entity.ts | 89 ----------------------------- api/src/model/chat.entity.ts | 19 +++++++ api/src/model/item.entity.ts | 13 ----- api/src/model/user.entity.ts | 43 ++++++++++++++ api/src/users/users.module.ts | 2 +- api/src/users/users.service.ts | 8 ++- docker-compose.yml | 36 ++++++------ react/src/components/Home.js | 12 +++- react/src/index.js | 11 +++- 18 files changed, 239 insertions(+), 254 deletions(-) delete mode 100644 api/src/auth/login42old.ts create mode 100644 api/src/chat/chat.module.ts create mode 100644 api/src/chat/chat.service.spec.ts create mode 100644 api/src/chat/chat.service.ts delete mode 100644 api/src/model/base.entity.ts create mode 100644 api/src/model/chat.entity.ts delete mode 100644 api/src/model/item.entity.ts create mode 100644 api/src/model/user.entity.ts diff --git a/api/src/app.controller.ts b/api/src/app.controller.ts index 7f7c1675..d6100fbb 100644 --- a/api/src/app.controller.ts +++ b/api/src/app.controller.ts @@ -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 { AuthGuard } from '@nestjs/passport'; import { AuthService } from './auth/auth.service'; - -// import { Login42 } 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' @Controller('/api') export class AppController { constructor(private authService: AuthService, - private loginClass: loginClass ) {} + private loginClass: loginClass, + private chatService: ChatService, + private userService: UsersService, ) {} // @Post('auth/login') // async login() { @@ -30,7 +34,7 @@ export class AppController { console.log(`all data in api = ${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}`) const token = (await data).access_token; @@ -48,9 +52,9 @@ export class AppController { @UseGuards(JwtAuthGuard) @Get('profile') getProfile(@Request() req) { - // const myJSON = JSON.stringify(req.user); - // console.log(`req user api= ${req.user}`) - // console.log(`json user api= ${myJSON}`) + const myJSON = JSON.stringify(req.user); + console.log(`req user api= ${req.user}`) + console.log(`json user api= ${myJSON}`) return req.user; // const user = req.user; // const returned = { @@ -61,8 +65,31 @@ export class AppController { // return returned; } - @Get(`conversation/:id`) - getConv(){ - + @UseGuards(JwtAuthGuard) + @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); } } \ No newline at end of file diff --git a/api/src/app.module.ts b/api/src/app.module.ts index 056012e8..85bb5def 100644 --- a/api/src/app.module.ts +++ b/api/src/app.module.ts @@ -6,20 +6,23 @@ import { AuthModule } from './auth/auth.module'; import { loginClass } from './auth/login42'; // import { UsersService } from './users/users.service'; // in add -import { TypeOrmModule } from '@nestjs/typeorm'; -import { getTypeOrmConfig } from './config/config.service'; -import { User } from './model/item.entity'; +// import { TypeOrmModule } from '@nestjs/typeorm'; +// import { getTypeOrmConfig } from './config/config.service'; +// import { User } from './model/item.entity'; // import { UsersService } from './users/users.service'; import { UsersModule } from './users/users.module'; +// import { ChatService } from './chat/chat.service'; +import { ChatModule } from './chat/chat.module'; @Module({ imports: [ AuthModule, UsersModule, + ChatModule, ], controllers: [AppController], -providers: [AppService, loginClass], +providers: [AppService, loginClass,], // providers: [AppService, UsersService],//in add }) diff --git a/api/src/auth/auth.service.ts b/api/src/auth/auth.service.ts index ab5aeb47..7bfd5524 100644 --- a/api/src/auth/auth.service.ts +++ b/api/src/auth/auth.service.ts @@ -20,12 +20,13 @@ export class AuthService { } 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 }; - console.log(`in login payload name= ${payload.username}`) - console.log(`in login payload sub= ${payload.sub}`) + // console.log(`in login payload name= ${payload.username}`) + // console.log(`in login payload sub= ${payload.sub}`) return { - username: user.username, access_token: this.jwtService.sign(payload), }; } diff --git a/api/src/auth/jwt.strategy.ts b/api/src/auth/jwt.strategy.ts index 695b0c58..6abae744 100644 --- a/api/src/auth/jwt.strategy.ts +++ b/api/src/auth/jwt.strategy.ts @@ -14,6 +14,8 @@ export class JwtStrategy extends PassportStrategy(Strategy) { } 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 }; } } \ No newline at end of file diff --git a/api/src/auth/login42.ts b/api/src/auth/login42.ts index 5cfd4003..19e1de13 100644 --- a/api/src/auth/login42.ts +++ b/api/src/auth/login42.ts @@ -5,7 +5,7 @@ import { Injectable } from '@nestjs/common'; import { Repository } from 'typeorm'; -import { User } from '../model/item.entity'; +import { User } from '../model/user.entity'; @Injectable() export class loginClass { @@ -14,7 +14,7 @@ export class loginClass { async Login42(url: string) { let token = null; - let userId = 0; + let userId = null; let userName = null; // let = null; @@ -40,7 +40,10 @@ export class loginClass { } }); 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) { @@ -48,28 +51,30 @@ export class loginClass { return ; } console.log(`username before serach= ${userName}`) + console.log(`ID before serach= ${userId}`) let user = await this.usersService.findOne(userName); if (!user) { - console.log(`no user, creating one`) + console.log(`no user, creating one`); user = { - name: null, - description: null, + // name: null, + // description: null, id: null, password: null, username: userName, nickname: userName, win: 0, - loose: 0, - rank: 0, + loss: 0, + rank: 1200, userId: userId, }; await this.usersService.create(user); } - console.log(`in login42 user= ${user}`) + // console.log(`in login42 user= ${user}`) const myJSON = JSON.stringify(user); - console.log(`in login42 user2= ${myJSON}`) + console.log(`in login42 user= ${myJSON}`) console.log("end of login"); - return (await this.usersService.findOne(userName)); + return (user); + // return (await this.usersService.findOne(userName)); } } \ No newline at end of file diff --git a/api/src/auth/login42old.ts b/api/src/auth/login42old.ts deleted file mode 100644 index 32f9bdb4..00000000 --- a/api/src/auth/login42old.ts +++ /dev/null @@ -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)); - } -} \ No newline at end of file diff --git a/api/src/chat/chat.module.ts b/api/src/chat/chat.module.ts new file mode 100644 index 00000000..9b333237 --- /dev/null +++ b/api/src/chat/chat.module.ts @@ -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 {} diff --git a/api/src/chat/chat.service.spec.ts b/api/src/chat/chat.service.spec.ts new file mode 100644 index 00000000..110cd7d3 --- /dev/null +++ b/api/src/chat/chat.service.spec.ts @@ -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); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/api/src/chat/chat.service.ts b/api/src/chat/chat.service.ts new file mode 100644 index 00000000..8d375f80 --- /dev/null +++ b/api/src/chat/chat.service.ts @@ -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,) {} + + async createMessage(chat: Chat): Promise { + return await this.chatRepository.save(chat); + } + + async getMessages(): Promise { + return await this.chatRepository.find(); + } +} diff --git a/api/src/model/base.entity.ts b/api/src/model/base.entity.ts deleted file mode 100644 index e2036017..00000000 --- a/api/src/model/base.entity.ts +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/api/src/model/chat.entity.ts b/api/src/model/chat.entity.ts new file mode 100644 index 00000000..865e162c --- /dev/null +++ b/api/src/model/chat.entity.ts @@ -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; + + + } \ No newline at end of file diff --git a/api/src/model/item.entity.ts b/api/src/model/item.entity.ts deleted file mode 100644 index 37395bde..00000000 --- a/api/src/model/item.entity.ts +++ /dev/null @@ -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; -} \ No newline at end of file diff --git a/api/src/model/user.entity.ts b/api/src/model/user.entity.ts new file mode 100644 index 00000000..3e895e4e --- /dev/null +++ b/api/src/model/user.entity.ts @@ -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; +} \ No newline at end of file diff --git a/api/src/users/users.module.ts b/api/src/users/users.module.ts index 74fc84f4..eae169d5 100644 --- a/api/src/users/users.module.ts +++ b/api/src/users/users.module.ts @@ -3,7 +3,7 @@ import { UsersService} from './users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import { getTypeOrmConfig } from '../config/config.service'; -import { User } from '../model/item.entity'; +import { User } from '../model/user.entity'; @Module({ imports: diff --git a/api/src/users/users.service.ts b/api/src/users/users.service.ts index 166e54ce..c27f3986 100644 --- a/api/src/users/users.service.ts +++ b/api/src/users/users.service.ts @@ -2,7 +2,7 @@ import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; -import { User } from '../model/item.entity'; +import { User } from '../model/user.entity'; @Injectable() @@ -24,7 +24,11 @@ export class UsersService { } async findOne(username: string): Promise { - return await this.userRepository.findOneBy({nickname: username}); + return await this.userRepository.findOneBy({username: username}); + } + + async save(user: User): Promise { + return await this.userRepository.save(user); } } diff --git a/docker-compose.yml b/docker-compose.yml index 2c717c58..1f56fa37 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -113,23 +113,23 @@ networks: driver: bridge volumes: - front_files: - driver: local - driver_opts: - type: none - o: 'bind' - device: '/frontend' - dbdata: - driver: local - driver_opts: - type: none - o: 'bind' - device: '/home/apommier/data/mariadb' - back: - driver: local - driver_opts: - type: none - o: 'bind' - device: '/backend' + # front_files: + # driver: local + # driver_opts: + # type: none + # o: 'bind' + # device: '/frontend' + # dbdata: + # driver: local + # driver_opts: + # type: none + # o: 'bind' + # device: '/home/apommier/data/mariadb' + # back: + # driver: local + # driver_opts: + # type: none + # o: 'bind' + # device: '/backend' db: driver: local \ No newline at end of file diff --git a/react/src/components/Home.js b/react/src/components/Home.js index bce60857..dba8e770 100644 --- a/react/src/components/Home.js +++ b/react/src/components/Home.js @@ -18,9 +18,9 @@ function Home() // const parsedData = JSON.parse(response.data); // console.log(`response= ${parsedData}`) - const myJSON = JSON.stringify(data); - console.log(`response2= ${myJSON}`) - console.log(`response= ${data}`) + const myJSON = JSON.stringify(response.data); + console.log(`data response= ${myJSON}`) + // console.log(`response= ${data}`) }); // alert("Le bouton a été cliqué !"); @@ -42,6 +42,12 @@ function Home()
+
+ +
+
+ +
// 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'); diff --git a/react/src/index.js b/react/src/index.js index 49703533..12b8f130 100644 --- a/react/src/index.js +++ b/react/src/index.js @@ -23,8 +23,15 @@ root.render( }/> }/> }/> - {/* }/> */} }/> + + + + {/* ------- ROUTE FOR CHAT APP HERE --------- */} + {/* }/> */} + + + @@ -34,3 +41,5 @@ root.render( // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals(); + +{/* }/> */} \ No newline at end of file