Browse Source

all linted (not chat as outdated)

master
nicolas-arnaud 2 years ago
parent
commit
f814e3b912
  1. 2
      back/volume/src/auth/42.strategy.ts
  2. 13
      back/volume/src/auth/auth.controller.ts
  3. 5
      back/volume/src/auth/session.serializer.ts
  4. 2
      back/volume/src/pong/pong.service.ts
  5. 5
      back/volume/src/types.d.ts
  6. 24
      back/volume/src/users/users.controller.ts
  7. 46
      back/volume/src/users/users.service.ts
  8. 15
      front/Dockerfile
  9. 8
      front/volume/src/App.svelte
  10. 21
      front/volume/src/FakeLogin.svelte
  11. 3
      front/volume/src/components/Pong/MapCustomization.svelte
  12. 3
      front/volume/src/components/Pong/Pong.svelte

2
back/volume/src/auth/42.strategy.ts

@ -36,7 +36,7 @@ export class FtStrategy extends PassportStrategy(Strategy, '42') {
if ((await this.usersService.findUser(ftId)) === null) { if ((await this.usersService.findUser(ftId)) === null) {
const newUser = new User() const newUser = new User()
newUser.ftId = profile.id as number newUser.ftId = profile.id as number
newUser.username = profile.username as string newUser.username = profile.username
newUser.avatar = `${ftId}.jpg` newUser.avatar = `${ftId}.jpg`
void this.usersService.create(newUser) void this.usersService.create(newUser)
const file = createWriteStream(`avatars/${ftId}.jpg`) const file = createWriteStream(`avatars/${ftId}.jpg`)

13
back/volume/src/auth/auth.controller.ts

@ -5,6 +5,15 @@ import { Profile } from 'passport-42'
import { FtOauthGuard, AuthenticatedGuard } from './42-auth.guard' import { FtOauthGuard, AuthenticatedGuard } from './42-auth.guard'
import { FtUser } from './42.decorator' import { FtUser } from './42.decorator'
const frontHost =
process.env.HOST !== undefined && process.env.HOST !== ''
? process.env.HOST
: 'localhost'
const frontPort =
process.env.PORT !== undefined && process.env.HOST !== ''
? process.env.PORT
: '80'
@Controller('log') @Controller('log')
export class AuthController { export class AuthController {
@Get('in') @Get('in')
@ -13,7 +22,7 @@ export class AuthController {
@Get('inReturn') @Get('inReturn')
@UseGuards(FtOauthGuard) @UseGuards(FtOauthGuard)
@Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`) @Redirect(`http://${frontHost}:${frontPort}`)
ftAuthCallback ( ftAuthCallback (
@Res({ passthrough: true }) response: Response, @Res({ passthrough: true }) response: Response,
@Req() request: Request @Req() request: Request
@ -29,7 +38,7 @@ export class AuthController {
} }
@Get('out') @Get('out')
@Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`) @Redirect(`http://${frontHost}:${frontPort}`)
logOut (@Req() req: Request): any { logOut (@Req() req: Request): any {
req.logOut(function (err) { req.logOut(function (err) {
if (err != null) return err if (err != null) return err

5
back/volume/src/auth/session.serializer.ts

@ -4,11 +4,6 @@ import { type Profile } from 'passport-42'
@Injectable() @Injectable()
export class SessionSerializer extends PassportSerializer { export class SessionSerializer extends PassportSerializer {
// useless constructor?
constructor () {
super()
}
serializeUser ( serializeUser (
user: Profile, user: Profile,
done: (err: Error | null, user: Profile) => void done: (err: Error | null, user: Profile) => void

2
back/volume/src/pong/pong.service.ts

@ -23,7 +23,7 @@ export class PongService {
player.winrate = (100 * player.wins) / player.matchs player.winrate = (100 * player.wins) / player.matchs
player.rank = (await this.usersService.getRank(player.ftId)) + 1 player.rank = (await this.usersService.getRank(player.ftId)) + 1
player.results.push(result) player.results.push(result)
this.usersService.save(player) await this.usersService.save(player)
} }
async saveResult (players: Player[]): Promise<void> { async saveResult (players: Player[]): Promise<void> {

5
back/volume/src/types.d.ts

@ -1,5 +1,8 @@
declare module 'passport-42' { declare module 'passport-42' {
export type Profile = any export type Profile = any
export type VerifyCallback = any export type VerifyCallback = any
export class Strategy {} export class Strategy {
constructor (options: any, verify: any)
authenticate (req: any, options: any): any
}
} }

24
back/volume/src/users/users.controller.ts

@ -11,8 +11,7 @@ import {
Res, Res,
StreamableFile, StreamableFile,
BadRequestException, BadRequestException,
Redirect, Redirect
type NotFoundException
} from '@nestjs/common' } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express' import { FileInterceptor } from '@nestjs/platform-express'
@ -136,14 +135,14 @@ export class UsersController {
async invitUser ( async invitUser (
@FtUser() profile: Profile, @FtUser() profile: Profile,
@Param('username') username: string @Param('username') username: string
): Promise<NotFoundException | null | undefined> { ): Promise<BadRequestException | null> {
const target = (await this.usersService.findUserByName(username))! const target: User | null = await this.usersService.findUserByName(
username
if (!target) throw new BadRequestException('Target unknown.') )
if (target == null) throw new BadRequestException('Target unknown.')
if (profile.id === target.ftId) { if (profile.id === target.ftId) {
throw new BadRequestException("You can't invit yourself.") throw new BadRequestException("You can't invit yourself.")
} }
return await this.usersService.invit(profile.id, target.id) return await this.usersService.invit(profile.id, target.id)
} }
@ -172,12 +171,12 @@ export class UsersController {
@Post(':id') @Post(':id')
@UseGuards(AuthenticatedGuard) @UseGuards(AuthenticatedGuard)
async createById (@Body() payload: UserDto): Promise<User | null> { async createById (@Body() payload: UserDto): Promise<void> {
const user = await this.usersService.findUser(payload.ftId) const user = await this.usersService.findUser(payload.ftId)
if (user != null) { if (user != null) {
return await this.usersService.update(user, payload) await this.usersService.update(user, payload)
} else { } else {
return await this.usersService.create(payload) await this.usersService.create(payload)
} }
} }
@ -192,8 +191,9 @@ export class UsersController {
async updateUser ( async updateUser (
@Body() payload: UserDto, @Body() payload: UserDto,
@FtUser() profile: Profile @FtUser() profile: Profile
): Promise<User | null> { ): Promise<BadRequestException | User | null> {
const user = (await this.usersService.findUser(profile.id))! const user = await this.usersService.findUser(profile.id)
if (user == null) throw new BadRequestException('User not found.')
return await this.usersService.update(user, payload) return await this.usersService.update(user, payload)
} }
} }

46
back/volume/src/users/users.service.ts

@ -1,9 +1,4 @@
import { import { BadRequestException, Catch, Injectable } from '@nestjs/common'
BadRequestException,
Catch,
Injectable,
NotFoundException
} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm' import { InjectRepository } from '@nestjs/typeorm'
import { EntityNotFoundError, QueryFailedError, Repository } from 'typeorm' import { EntityNotFoundError, QueryFailedError, Repository } from 'typeorm'
import { User } from './entity/user.entity' import { User } from './entity/user.entity'
@ -19,8 +14,8 @@ export class UsersService {
@InjectRepository(User) private readonly usersRepository: Repository<User> @InjectRepository(User) private readonly usersRepository: Repository<User>
) {} ) {}
save (user: User) { async save (user: User): Promise<void> {
this.usersRepository.save(user) await this.usersRepository.save(user)
} }
async findUsers (): Promise<User[]> { async findUsers (): Promise<User[]> {
@ -36,12 +31,14 @@ export class UsersService {
} }
@Cron('0 * * * * *') @Cron('0 * * * * *')
async updateStatus () { async updateStatus (): Promise<void> {
const users = await this.usersRepository.find({}) const users = await this.usersRepository.find({})
users.forEach((usr) => { users.forEach((usr) => {
if (Date.now() - usr.lastAccess > 60000) { if (Date.now() - usr.lastAccess > 60000) {
usr.status = 'offline' usr.status = 'offline'
this.usersRepository.save(usr) this.usersRepository.save(usr).catch((err) => {
console.log(err)
})
} }
}) })
} }
@ -51,7 +48,7 @@ export class UsersService {
if (user == null) return null if (user == null) return null
user.lastAccess = Date.now() user.lastAccess = Date.now()
user.status = 'online' user.status = 'online'
this.usersRepository.save(user) await this.usersRepository.save(user)
return user return user
} }
@ -59,12 +56,12 @@ export class UsersService {
return await this.usersRepository.find({ where: { status: 'online' } }) return await this.usersRepository.find({ where: { status: 'online' } })
} }
async create (userData: UserDto) { async create (userData: UserDto): Promise<BadRequestException | User> {
try { try {
const newUser = this.usersRepository.create(userData) const newUser = this.usersRepository.create(userData)
return await this.usersRepository.save(newUser) return await this.usersRepository.save(newUser)
} catch (err) { } catch (err) {
throw new Error(`Error creating user ${err}`) throw new BadRequestException('User already exists.')
} }
} }
@ -81,21 +78,14 @@ export class UsersService {
return await this.usersRepository.save(user) return await this.usersRepository.save(user)
} }
async addAvatar (ftId: number, filename: string) { async addAvatar (ftId: number, filename: string): Promise<void> {
return await this.usersRepository.update( await this.usersRepository.update({ ftId }, { avatar: filename })
{ ftId },
{
avatar: filename
}
)
} }
async getFriends (ftId: number): Promise<User[]> { async getFriends (ftId: number): Promise<User[]> {
const user = await this.usersRepository.findOne({ const user = await this.usersRepository.findOne({
where: { ftId }, where: { ftId },
relations: { relations: { friends: true }
friends: true
}
}) })
if (user != null) return user.friends if (user != null) return user.friends
return [] return []
@ -139,23 +129,25 @@ export class UsersService {
} }
async invit (ftId: number, targetFtId: number): Promise<any> { async invit (ftId: number, targetFtId: number): Promise<any> {
const user: User = (await this.usersRepository.findOne({ const user: User | null = await this.usersRepository.findOne({
where: { ftId }, where: { ftId },
relations: { relations: {
followers: true, followers: true,
friends: true friends: true
} }
}))! })
if (user == null) throw new BadRequestException('User not found.')
if (user.friends.findIndex((friend) => friend.ftId === targetFtId) !== -1) { if (user.friends.findIndex((friend) => friend.ftId === targetFtId) !== -1) {
return new BadRequestException('You are already friends.') return new BadRequestException('You are already friends.')
} }
const target = (await this.usersRepository.findOne({ const target: User | null = await this.usersRepository.findOne({
where: { ftId: targetFtId }, where: { ftId: targetFtId },
relations: { relations: {
followers: true, followers: true,
friends: true friends: true
} }
}))! })
if (target == null) throw new BadRequestException('Target not found.')
const id = user.followers.findIndex( const id = user.followers.findIndex(
(follower) => follower.ftId === targetFtId (follower) => follower.ftId === targetFtId
) )

15
front/Dockerfile

@ -5,17 +5,4 @@ RUN apk update && apk upgrade && apk add npm
WORKDIR /var/www/html WORKDIR /var/www/html
COPY entrypoint.sh /tmp/entrypoint.sh COPY entrypoint.sh /tmp/entrypoint.sh
COPY ../.env .env ENTRYPOINT ["sh", "/tmp/entrypoint.sh"]
ENTRYPOINT npm install; \
if [[ $NODE_ENV == "production" ]]; then \
npm run build && npm run preview; \
elif [[ $NODE_ENV == "development" ]]; then \
npm run dev; \
elif [[ $NODE_ENV == "debug" ]]; then \
npm run dev; \
elif [[ $NODE_ENV == "check" ]]; then \
npm run format && npm run check; echo "=== FINISH ===" \
else echo "Nothing to do for that NODE_ENV context."; \
fi;

8
front/volume/src/App.svelte

@ -159,9 +159,9 @@
username: "test", username: "test",
socketKey: "42", socketKey: "42",
}; };
store.set(user) store.set(user);
fakeUser = true fakeUser = true;
fakemenu = false fakemenu = false;
} }
</script> </script>
@ -259,7 +259,7 @@
{#if fakemenu} {#if fakemenu}
<FakeLogin username={usernameFake} ftId={ftIdFake} /> <FakeLogin username={usernameFake} ftId={ftIdFake} />
<button on:click={impersonate}>Impersonate</button> <button on:click={impersonate}>Impersonate</button>
<button on:click={() => fakemenu = false}>No impersonate</button> <button on:click={() => (fakemenu = false)}>No impersonate</button>
{:else} {:else}
<Pong bind:this={pong} {fakeUser} /> <Pong bind:this={pong} {fakeUser} />
{/if} {/if}

21
front/volume/src/FakeLogin.svelte

@ -6,24 +6,24 @@
let result = null; let result = null;
async function doPost() { async function doPost() {
const res = await fetch(API_URL + "/" + ftId, { const res = await fetch(API_URL + "/" + ftId, {
method: "POST", method: "POST",
credentials: "include", credentials: "include",
mode: "cors", mode: "cors",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
body: JSON.stringify({ body: JSON.stringify({
ftId, ftId,
username, username,
socketKey: "42", socketKey: "42",
avatar: "no avatar", avatar: "no avatar",
}), }),
}); });
const json = await res.json(); const json = await res.json();
result = JSON.stringify(json); result = JSON.stringify(json);
console.log(result); console.log(result);
} }
</script> </script>
@ -33,4 +33,3 @@
<button type="button" on:click={doPost}> Post it. </button> <button type="button" on:click={doPost}> Post it. </button>
<p>Result: {result}</p> <p>Result: {result}</p>
</div> </div>

3
front/volume/src/components/Pong/MapCustomization.svelte

@ -2,7 +2,7 @@
import { onMount } from "svelte"; import { onMount } from "svelte";
import { Point, Rect } from "./utils"; import { Point, Rect } from "./utils";
import type { Map } from "./Map"; import type { Map } from "./Map";
import { DEFAULT_BALL_SIZE, DEFAULT_MAP_SIZE } from "./constants"; import { DEFAULT_BALL_SIZE } from "./constants";
import { Ball } from "./Ball"; import { Ball } from "./Ball";
export let map: Map; export let map: Map;
@ -49,7 +49,6 @@
} }
function addWall(e: MouseEvent) { function addWall(e: MouseEvent) {
const rect: any = gameCanvas.getBoundingClientRect();
const wall = new Rect(getMapXY(e), new Point(wallWidth, wallHeight)); const wall = new Rect(getMapXY(e), new Point(wallWidth, wallHeight));
const ballSpawnArea = new Rect( const ballSpawnArea = new Rect(
new Point(map.size.x / 2, map.size.y / 2), new Point(map.size.x / 2, map.size.y / 2),

3
front/volume/src/components/Pong/Pong.svelte

@ -108,8 +108,7 @@
} }
async function onSocketOpen() { async function onSocketOpen() {
if (!fakeUser) if (!fakeUser) await getUser();
await getUser();
void logIn(); void logIn();
connected = true; connected = true;
} }

Loading…
Cancel
Save