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) {
const newUser = new User()
newUser.ftId = profile.id as number
newUser.username = profile.username as string
newUser.username = profile.username
newUser.avatar = `${ftId}.jpg`
void this.usersService.create(newUser)
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 { 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')
export class AuthController {
@Get('in')
@ -13,7 +22,7 @@ export class AuthController {
@Get('inReturn')
@UseGuards(FtOauthGuard)
@Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`)
@Redirect(`http://${frontHost}:${frontPort}`)
ftAuthCallback (
@Res({ passthrough: true }) response: Response,
@Req() request: Request
@ -29,7 +38,7 @@ export class AuthController {
}
@Get('out')
@Redirect(`http://${process.env.HOST}:${process.env.FRONT_PORT}`)
@Redirect(`http://${frontHost}:${frontPort}`)
logOut (@Req() req: Request): any {
req.logOut(function (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()
export class SessionSerializer extends PassportSerializer {
// useless constructor?
constructor () {
super()
}
serializeUser (
user: Profile,
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.rank = (await this.usersService.getRank(player.ftId)) + 1
player.results.push(result)
this.usersService.save(player)
await this.usersService.save(player)
}
async saveResult (players: Player[]): Promise<void> {

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

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

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

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

15
front/Dockerfile

@ -5,17 +5,4 @@ RUN apk update && apk upgrade && apk add npm
WORKDIR /var/www/html
COPY entrypoint.sh /tmp/entrypoint.sh
COPY ../.env .env
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;
ENTRYPOINT ["sh", "/tmp/entrypoint.sh"]

8
front/volume/src/App.svelte

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

21
front/volume/src/FakeLogin.svelte

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

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

@ -2,7 +2,7 @@
import { onMount } from "svelte";
import { Point, Rect } from "./utils";
import type { Map } from "./Map";
import { DEFAULT_BALL_SIZE, DEFAULT_MAP_SIZE } from "./constants";
import { DEFAULT_BALL_SIZE } from "./constants";
import { Ball } from "./Ball";
export let map: Map;
@ -49,7 +49,6 @@
}
function addWall(e: MouseEvent) {
const rect: any = gameCanvas.getBoundingClientRect();
const wall = new Rect(getMapXY(e), new Point(wallWidth, wallHeight));
const ballSpawnArea = new Rect(
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() {
if (!fakeUser)
await getUser();
if (!fakeUser) await getUser();
void logIn();
connected = true;
}

Loading…
Cancel
Save