Normalize quote usage in imports

Standardized the quote style to double quotes across all TypeScript files for consistency. This includes ".ts" and ".dto" files.
This commit is contained in:
Mathis H (Avnyr) 2024-11-12 13:37:29 +01:00
parent 2fdc16e003
commit 8ea217fe9f
Signed by: Mathis
GPG Key ID: DD9E0666A747D126
52 changed files with 1475 additions and 1486 deletions

View File

@ -1,22 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing'; import { Test, TestingModule } from "@nestjs/testing";
import { AppController } from './app.controller'; import { AppController } from "./app.controller";
import { AppService } from './app.service'; import { AppService } from "./app.service";
describe('AppController', () => { describe("AppController", () => {
let appController: AppController; let appController: AppController;
beforeEach(async () => { beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({ const app: TestingModule = await Test.createTestingModule({
controllers: [AppController], controllers: [AppController],
providers: [AppService], providers: [AppService],
}).compile(); }).compile();
appController = app.get<AppController>(AppController); appController = app.get<AppController>(AppController);
}); });
describe('root', () => { describe("root", () => {
it('should return "Hello World!"', () => { it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!'); expect(appController.getHello()).toBe("Hello World!");
}); });
}); });
}); });

View File

@ -1,12 +1,12 @@
import { Controller, Get } from '@nestjs/common'; import { Controller, Get } from "@nestjs/common";
import { AppService } from './app.service'; import { AppService } from "./app.service";
@Controller() @Controller()
export class AppController { export class AppController {
constructor(private readonly appService: AppService) {} constructor(private readonly appService: AppService) {}
@Get() @Get()
getHello(): string { getHello(): string {
return 'Hello'; return "Hello";
} }
} }

View File

@ -1,38 +1,38 @@
import { Module } from '@nestjs/common'; import { AppController } from "@/app.controller";
import { AppController } from '@/app.controller'; import { AppService } from "@/app.service";
import { AppService } from '@/app.service'; import { AuthModule } from "@/auth/auth.module";
import { ConfigModule } from '@nestjs/config'; import { CryptoModule } from "@/crypto/crypto.module";
import { AuthModule } from '@/auth/auth.module'; import { OfferModule } from "@/offer/offer.module";
import { PrismaModule } from '@/prisma/prisma.module'; import { PrismaModule } from "@/prisma/prisma.module";
import { RoleModule } from '@/role/role.module'; import { PromoCodeModule } from "@/promoCode/promoCode.module";
import { PromoCodeModule } from '@/promoCode/promoCode.module'; import { RoleModule } from "@/role/role.module";
import { CryptoModule } from '@/crypto/crypto.module'; import { TradeModule } from "@/trade/trade.module";
import { TradeModule } from '@/trade/trade.module'; import { UserModule } from "@/user/user.module";
import { OfferModule } from '@/offer/offer.module'; import { Module } from "@nestjs/common";
import { UserModule } from '@/user/user.module'; import { ConfigModule } from "@nestjs/config";
import { ThrottlerModule } from '@nestjs/throttler'; import { ThrottlerModule } from "@nestjs/throttler";
@Module({ @Module({
imports: [ imports: [
ConfigModule.forRoot({ ConfigModule.forRoot({
isGlobal: true, isGlobal: true,
}), }),
AuthModule, AuthModule,
PrismaModule, PrismaModule,
RoleModule, RoleModule,
PromoCodeModule, PromoCodeModule,
CryptoModule, CryptoModule,
TradeModule, TradeModule,
OfferModule, OfferModule,
UserModule, UserModule,
ThrottlerModule.forRoot([ ThrottlerModule.forRoot([
{ {
ttl: 60000, ttl: 60000,
limit: 40, limit: 40,
}, },
]), ]),
], ],
controllers: [AppController], controllers: [AppController],
providers: [AppService], providers: [AppService],
}) })
export class AppModule {} export class AppModule {}

View File

@ -1,8 +1,8 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
@Injectable() @Injectable()
export class AppService { export class AppService {
getHello(): string { getHello(): string {
return 'Hello World!'; return "Hello World!";
} }
} }

View File

@ -1,21 +1,21 @@
import { Body, Controller, HttpCode, HttpStatus, Post } from '@nestjs/common'; import { Body, Controller, HttpCode, HttpStatus, Post } from "@nestjs/common";
import { AuthService } from './auth.service'; import { ApiTags } from "@nestjs/swagger";
import { AuthLoginDto, AuthRegisterDto } from './dto'; import { AuthService } from "./auth.service";
import { ApiTags } from '@nestjs/swagger'; import { AuthLoginDto, AuthRegisterDto } from "./dto";
@ApiTags('auth') @ApiTags("auth")
@Controller('auth') @Controller("auth")
export class AuthController { export class AuthController {
constructor(private authService: AuthService) {} constructor(private authService: AuthService) {}
@Post('sign-up') @Post("sign-up")
signUp(@Body() dto: AuthRegisterDto) { signUp(@Body() dto: AuthRegisterDto) {
return this.authService.signup(dto); return this.authService.signup(dto);
} }
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Post('sign-in') @Post("sign-in")
signIn(@Body() dto: AuthLoginDto) { signIn(@Body() dto: AuthLoginDto) {
return this.authService.signin(dto); return this.authService.signin(dto);
} }
} }

View File

@ -1,12 +1,12 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { JwtModule } from '@nestjs/jwt'; import { JwtModule } from "@nestjs/jwt";
import { AuthController } from './auth.controller'; import { AuthController } from "./auth.controller";
import { AuthService } from './auth.service'; import { AuthService } from "./auth.service";
import { JwtStrategy } from './strategy'; import { JwtStrategy } from "./strategy";
@Module({ @Module({
imports: [JwtModule.register({})], imports: [JwtModule.register({})],
controllers: [AuthController], controllers: [AuthController],
providers: [AuthService, JwtStrategy], providers: [AuthService, JwtStrategy],
}) })
export class AuthModule {} export class AuthModule {}

View File

@ -1,108 +1,113 @@
import { ForbiddenException, Injectable } from '@nestjs/common'; import { ForbiddenException, Injectable } from "@nestjs/common";
import { PrismaService } from '../prisma/prisma.service'; import { ConfigService } from "@nestjs/config";
import { AuthLoginDto, AuthRegisterDto } from './dto'; import { JwtService } from "@nestjs/jwt";
import * as argon from 'argon2'; import { Prisma, User } from "@prisma/client";
import { Prisma, User } from '@prisma/client'; import * as argon from "argon2";
import { JwtService } from '@nestjs/jwt'; import { PrismaService } from "../prisma/prisma.service";
import { ConfigService } from '@nestjs/config'; import { AuthLoginDto, AuthRegisterDto } from "./dto";
@Injectable() @Injectable()
export class AuthService { export class AuthService {
private readonly initialBalance = 1000; private readonly initialBalance = 1000;
constructor( constructor(
private prisma: PrismaService, private prisma: PrismaService,
private jwt: JwtService, private jwt: JwtService,
private config: ConfigService, private config: ConfigService,
) {} ) {}
async signup(dto: AuthRegisterDto) { async signup(dto: AuthRegisterDto) {
const hash = await argon.hash(dto.password); const hash = await argon.hash(dto.password);
const promoCode = await this.getPromoCode(dto.promoCode); const promoCode = await this.getPromoCode(dto.promoCode);
const userRole = await this.getUserRole('user'); const userRole = await this.getUserRole("user");
const balance = this.calculateBalance(promoCode); const balance = this.calculateBalance(promoCode);
try { try {
const user = await this.createUser(dto, hash, userRole.id, balance); const user = await this.createUser(dto, hash, userRole.id, balance);
return this.signToken(user); return this.signToken(user);
} catch (error) { } catch (error) {
this.handleSignupError(error); this.handleSignupError(error);
} }
} }
private async getPromoCode(promoCode: string) { private async getPromoCode(promoCode: string) {
return this.prisma.promoCode.findFirst({ return this.prisma.promoCode.findFirst({
where: {name: promoCode}, where: { name: promoCode },
}); });
} }
private async getUserRole(roleName: string) { private async getUserRole(roleName: string) {
return this.prisma.role.findFirst({ return this.prisma.role.findFirst({
where: {name: roleName}, where: { name: roleName },
}); });
} }
private calculateBalance(promoCode: any) { private calculateBalance(promoCode: any) {
let balance = this.initialBalance; let balance = this.initialBalance;
if (promoCode && promoCode.value) { if (promoCode && promoCode.value) {
balance += promoCode.value; balance += promoCode.value;
} }
return balance; return balance;
} }
private async createUser(dto: AuthRegisterDto, hash: string, roleId: string, balance: number) { private async createUser(
return this.prisma.user.create({ dto: AuthRegisterDto,
data: { hash: string,
firstName: dto.firstName, roleId: string,
lastName: dto.lastName, balance: number,
pseudo: dto.pseudo, ) {
email: dto.email, return this.prisma.user.create({
hash, data: {
roleId, firstName: dto.firstName,
isActive: true, lastName: dto.lastName,
dollarAvailables: balance, pseudo: dto.pseudo,
}, email: dto.email,
}); hash,
} roleId,
isActive: true,
dollarAvailables: balance,
},
});
}
private handleSignupError(error: any) { private handleSignupError(error: any) {
if (error instanceof Prisma.PrismaClientKnownRequestError) { if (error instanceof Prisma.PrismaClientKnownRequestError) {
if (error.code === 'P2002') { if (error.code === "P2002") {
throw new ForbiddenException('Credentials taken'); throw new ForbiddenException("Credentials taken");
} }
} }
throw error; throw error;
} }
async signin(dto: AuthLoginDto) { async signin(dto: AuthLoginDto) {
const userDatas = await this.prisma.user.findUnique({ const userDatas = await this.prisma.user.findUnique({
where: { email: dto.email }, where: { email: dto.email },
include: { include: {
UserHasCrypto: { include: { Crypto: true } }, UserHasCrypto: { include: { Crypto: true } },
Role: true, Role: true,
}, },
}); });
if (!userDatas) throw new ForbiddenException('Credentials incorrect'); if (!userDatas) throw new ForbiddenException("Credentials incorrect");
const pwMatches = await argon.verify(userDatas.hash, dto.password); const pwMatches = await argon.verify(userDatas.hash, dto.password);
if (!pwMatches) throw new ForbiddenException('Credentials incorrect'); if (!pwMatches) throw new ForbiddenException("Credentials incorrect");
return this.signToken(userDatas); return this.signToken(userDatas);
} }
async signToken(user: any): Promise<{ access_token: string; user: User }> { async signToken(user: any): Promise<{ access_token: string; user: User }> {
const payload = { sub: user.id, email: user.email }; const payload = { sub: user.id, email: user.email };
user.hash = null; user.hash = null;
const secret = this.config.get('JWT_SECRET'); const secret = this.config.get("JWT_SECRET");
const token = await this.jwt.signAsync(payload, { const token = await this.jwt.signAsync(payload, {
expiresIn: '30d', expiresIn: "30d",
secret: secret, secret: secret,
}); });
return { return {
access_token: token, access_token: token,
user, user,
}; };
} }
} }

View File

@ -1,11 +1,11 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common'; import { ExecutionContext, createParamDecorator } from "@nestjs/common";
export const GetUser = createParamDecorator( export const GetUser = createParamDecorator(
(data: string | undefined, ctx: ExecutionContext) => { (data: string | undefined, ctx: ExecutionContext) => {
const request: Express.Request = ctx.switchToHttp().getRequest(); const request: Express.Request = ctx.switchToHttp().getRequest();
if (data) { if (data) {
return request.user[data]; return request.user[data];
} }
return request.user; return request.user;
}, },
); );

View File

@ -1 +1 @@
export * from './get-user.decorator'; export * from "./get-user.decorator";

View File

@ -1,13 +1,13 @@
import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; import { ApiProperty } from "@nestjs/swagger";
import { ApiProperty } from '@nestjs/swagger'; import { IsEmail, IsNotEmpty, IsString } from "class-validator";
export class AuthLoginDto { export class AuthLoginDto {
@IsEmail() @IsEmail()
@IsNotEmpty() @IsNotEmpty()
@ApiProperty({ type: String, description: 'email' }) @ApiProperty({ type: String, description: "email" })
email: string; email: string;
@ApiProperty({ type: String, description: 'password' }) @ApiProperty({ type: String, description: "password" })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
password: string; password: string;
} }

View File

@ -1,73 +1,73 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from "@nestjs/swagger";
import { import {
IsEmail, IsEmail,
IsInt, IsInt,
IsNotEmpty, IsNotEmpty,
IsOptional, IsOptional,
IsString, IsString,
Max, Max,
MaxLength, MaxLength,
Min, Min,
MinLength, MinLength,
} from 'class-validator'; } from "class-validator";
export class AuthRegisterDto { export class AuthRegisterDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'FirstName', description: "FirstName",
example: 'Thomas', example: "Thomas",
}) })
@MinLength(1) @MinLength(1)
@MaxLength(50) @MaxLength(50)
@IsNotEmpty() @IsNotEmpty()
@IsString() @IsString()
firstName: string; firstName: string;
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Last Name', description: "Last Name",
example: 'Anderson', example: "Anderson",
}) })
@MinLength(1) @MinLength(1)
@MaxLength(50) @MaxLength(50)
@IsNotEmpty() @IsNotEmpty()
@IsString() @IsString()
lastName: string; lastName: string;
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Pseudo', description: "Pseudo",
example: 'Néo', example: "Néo",
}) })
@MinLength(1) @MinLength(1)
@MaxLength(50) @MaxLength(50)
@IsNotEmpty() @IsNotEmpty()
@IsString() @IsString()
pseudo: string; pseudo: string;
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'email', description: "email",
example: 'neo@matrix.fr', example: "neo@matrix.fr",
}) })
@MaxLength(255) @MaxLength(255)
@IsEmail() @IsEmail()
@IsNotEmpty() @IsNotEmpty()
email: string; email: string;
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'password', description: "password",
example: 'AAaa11&&&&', example: "AAaa11&&&&",
}) })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
password: string; password: string;
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'promoCode', description: "promoCode",
example: 'FILOU20', example: "FILOU20",
}) })
@IsOptional() @IsOptional()
promoCode: string; promoCode: string;
} }

View File

@ -1,2 +1,2 @@
export * from './auth.register.dto'; export * from "./auth.register.dto";
export * from './auth.login.dto'; export * from "./auth.login.dto";

View File

@ -1 +1 @@
export * from './jwt.guard'; export * from "./jwt.guard";

View File

@ -1,7 +1,7 @@
import { AuthGuard } from '@nestjs/passport'; import { AuthGuard } from "@nestjs/passport";
export class JwtGuard extends AuthGuard('jwt') { export class JwtGuard extends AuthGuard("jwt") {
constructor() { constructor() {
super(); super();
} }
} }

View File

@ -1 +1 @@
export * from './jwt.strategy'; export * from "./jwt.strategy";

View File

@ -1,28 +1,28 @@
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PrismaService } from "@/prisma/prisma.service"; import { PrismaService } from "@/prisma/prisma.service";
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
@Injectable() @Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') { export class JwtStrategy extends PassportStrategy(Strategy, "jwt") {
constructor( constructor(
config: ConfigService, config: ConfigService,
private prisma: PrismaService, private prisma: PrismaService,
) { ) {
super({ super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: config.get('JWT_SECRET'), secretOrKey: config.get("JWT_SECRET"),
}); });
} }
async validate(payload: { sub: string; email: string }) { async validate(payload: { sub: string; email: string }) {
const user = await this.prisma.user.findUnique({ const user = await this.prisma.user.findUnique({
where: { where: {
id: payload.sub, id: payload.sub,
}, },
}); });
delete user.hash; delete user.hash;
return user; return user;
} }
} }

View File

@ -1,73 +1,73 @@
import { import {
Body, Body,
Controller, Controller,
Delete, Delete,
Get, Get,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Param, Param,
Patch, Patch,
Post, Post,
UseGuards, UseGuards,
} from '@nestjs/common'; } from "@nestjs/common";
import { GetUser } from '../auth/decorator'; import { ApiTags } from "@nestjs/swagger";
import { ApiTags } from '@nestjs/swagger'; import { User } from "@prisma/client";
import { User } from '@prisma/client'; import { JwtGuard } from "src/auth/guard";
import { CryptoService } from './crypto.service'; import { GetUser } from "../auth/decorator";
import { CryptoDto } from './dto'; import { CryptoService } from "./crypto.service";
import { JwtGuard } from 'src/auth/guard'; import { CryptoDto } from "./dto";
import { BuyCryptoDto } from './dto/buy.crypto.dto'; import { BuyCryptoDto } from "./dto/buy.crypto.dto";
@UseGuards(JwtGuard) @UseGuards(JwtGuard)
@ApiTags('crypto') @ApiTags("crypto")
@Controller('crypto') @Controller("crypto")
export class CryptoController { export class CryptoController {
constructor(private cryptoService: CryptoService) {} constructor(private cryptoService: CryptoService) {}
@Get('/all') @Get("/all")
getAllPromoCodes(@GetUser() user: User) { getAllPromoCodes(@GetUser() user: User) {
return this.cryptoService.getCryptos(user.id); return this.cryptoService.getCryptos(user.id);
} }
@Get('/search/:name') @Get("/search/:name")
searchCrypto(@GetUser() user: User, @Param('name') cryptoName: string) { searchCrypto(@GetUser() user: User, @Param("name") cryptoName: string) {
return this.cryptoService.searchCryptos(user.id, cryptoName); return this.cryptoService.searchCryptos(user.id, cryptoName);
} }
@Get('/history/:id') @Get("/history/:id")
CryptoHistory(@GetUser() user: User, @Param('id') cryptoId: string) { CryptoHistory(@GetUser() user: User, @Param("id") cryptoId: string) {
return this.cryptoService.getCryptoHistory(user.id, cryptoId); return this.cryptoService.getCryptoHistory(user.id, cryptoId);
} }
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@Post('/create') @Post("/create")
createPromoCode( createPromoCode(
@Body() @Body()
dto: CryptoDto, dto: CryptoDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.cryptoService.createCrypto(user.id, dto); return this.cryptoService.createCrypto(user.id, dto);
} }
@Post('/buy') @Post("/buy")
buyCrypto( buyCrypto(
@Body() @Body()
dto: BuyCryptoDto, dto: BuyCryptoDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.cryptoService.buyCrypto(user.id, dto); return this.cryptoService.buyCrypto(user.id, dto);
} }
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Patch('/update/:id') @Patch("/update/:id")
editCryptoById( editCryptoById(
@Param('id') cryptoId: string, @Param("id") cryptoId: string,
@Body() dto: CryptoDto, @Body() dto: CryptoDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.cryptoService.editCryptoById(user.id, cryptoId, dto); return this.cryptoService.editCryptoById(user.id, cryptoId, dto);
} }
@HttpCode(HttpStatus.NO_CONTENT) @HttpCode(HttpStatus.NO_CONTENT)
@Delete('/delete/:id') @Delete("/delete/:id")
deleteOfferById(@Param('id') roleId: string, @GetUser() user: User) { deleteOfferById(@Param("id") roleId: string, @GetUser() user: User) {
return this.cryptoService.deleteCryptoById(user.id, roleId); return this.cryptoService.deleteCryptoById(user.id, roleId);
} }
} }

View File

@ -1,9 +1,9 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { CryptoService } from './crypto.service'; import { CryptoController } from "./crypto.controller";
import { CryptoController } from './crypto.controller'; import { CryptoService } from "./crypto.service";
@Module({ @Module({
providers: [CryptoService], providers: [CryptoService],
controllers: [CryptoController], controllers: [CryptoController],
}) })
export class CryptoModule {} export class CryptoModule {}

View File

@ -1,192 +1,192 @@
import { ForbiddenException, Injectable } from '@nestjs/common'; import { ForbiddenException, Injectable } from "@nestjs/common";
import { PrismaService } from '../prisma/prisma.service'; import { checkUserHasAccount, checkUserIsAdmin } from "src/utils/checkUser";
import { checkUserHasAccount, checkUserIsAdmin } from 'src/utils/checkUser'; import { PrismaService } from "../prisma/prisma.service";
import { CryptoDto } from './dto'; import { CryptoDto } from "./dto";
import { BuyCryptoDto } from './dto/buy.crypto.dto'; import { BuyCryptoDto } from "./dto/buy.crypto.dto";
@Injectable() @Injectable()
export class CryptoService { export class CryptoService {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async getCryptos(userId: string) { async getCryptos(userId: string) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
return this.prisma.crypto.findMany({ return this.prisma.crypto.findMany({
orderBy: { orderBy: {
name: 'asc', name: "asc",
}, },
}); });
} }
async searchCryptos(userId: string, cryptoName: string) { async searchCryptos(userId: string, cryptoName: string) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
return this.prisma.crypto.findMany({ return this.prisma.crypto.findMany({
where: { where: {
name: { name: {
contains: cryptoName, contains: cryptoName,
mode: 'insensitive', mode: "insensitive",
}, },
}, },
orderBy: { orderBy: {
name: 'asc', name: "asc",
}, },
}); });
} }
async getCryptoHistory(userId: string, cryptoId: string) { async getCryptoHistory(userId: string, cryptoId: string) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
if (cryptoId) { if (cryptoId) {
return this.prisma.crypto.findMany({ return this.prisma.crypto.findMany({
where: { where: {
id: cryptoId, id: cryptoId,
}, },
orderBy: { orderBy: {
created_at: 'desc', created_at: "desc",
}, },
take: 50, take: 50,
}); });
} }
throw new ForbiddenException('Crypto UUID required'); throw new ForbiddenException("Crypto UUID required");
} }
async createCrypto(userId: string, dto: CryptoDto) { async createCrypto(userId: string, dto: CryptoDto) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const existingCryptosWithSameName = await this.prisma.crypto.findMany({ const existingCryptosWithSameName = await this.prisma.crypto.findMany({
where: { where: {
name: dto.name, name: dto.name,
}, },
}); });
if (existingCryptosWithSameName.length > 0) { if (existingCryptosWithSameName.length > 0) {
throw new ForbiddenException('Name already taken'); throw new ForbiddenException("Name already taken");
} }
const crypto = await this.prisma.crypto.create({ const crypto = await this.prisma.crypto.create({
data: { data: {
name: dto.name, name: dto.name,
image: dto.image, image: dto.image,
value: dto.value, value: dto.value,
quantity: dto.quantity, quantity: dto.quantity,
}, },
}); });
return crypto; return crypto;
} }
async buyCrypto(userId: string, dto: BuyCryptoDto) { async buyCrypto(userId: string, dto: BuyCryptoDto) {
const crypto = await this.prisma.crypto.findFirst({ const crypto = await this.prisma.crypto.findFirst({
where: { where: {
id: dto.id_crypto, id: dto.id_crypto,
}, },
}); });
const user = await this.prisma.user.findFirst({ const user = await this.prisma.user.findFirst({
where: { where: {
id: userId, id: userId,
}, },
}); });
if (crypto.quantity < dto.amount) { if (crypto.quantity < dto.amount) {
throw new ForbiddenException('No more tokens available'); throw new ForbiddenException("No more tokens available");
} }
const necessaryAmount = crypto.value * dto.amount; const necessaryAmount = crypto.value * dto.amount;
console.log(necessaryAmount, user.dollarAvailables); console.log(necessaryAmount, user.dollarAvailables);
if (necessaryAmount > user.dollarAvailables) { if (necessaryAmount > user.dollarAvailables) {
throw new ForbiddenException('Make money first :) '); throw new ForbiddenException("Make money first :) ");
} }
const userAsset = await this.prisma.userHasCrypto.findFirst({ const userAsset = await this.prisma.userHasCrypto.findFirst({
where: { where: {
id_crypto: dto.id_crypto, id_crypto: dto.id_crypto,
id_user: userId, id_user: userId,
}, },
}); });
const newBalance = user.dollarAvailables - necessaryAmount; const newBalance = user.dollarAvailables - necessaryAmount;
console.log(newBalance); console.log(newBalance);
await this.prisma.user.update({ await this.prisma.user.update({
where: { where: {
id: user.id, id: user.id,
}, },
data: { data: {
dollarAvailables: newBalance, dollarAvailables: newBalance,
}, },
}); });
if (userAsset) { if (userAsset) {
const newBalance = userAsset.amount + dto.amount; const newBalance = userAsset.amount + dto.amount;
await this.prisma.userHasCrypto.update({ await this.prisma.userHasCrypto.update({
where: { where: {
id: userAsset.id, id: userAsset.id,
}, },
data: { data: {
amount: newBalance, amount: newBalance,
}, },
}); });
} else { } else {
await this.prisma.userHasCrypto.create({ await this.prisma.userHasCrypto.create({
data: { data: {
id_crypto: dto.id_crypto, id_crypto: dto.id_crypto,
id_user: userId, id_user: userId,
amount: dto.amount, amount: dto.amount,
}, },
}); });
} }
const newCryptoValue = crypto.value * 1.1; const newCryptoValue = crypto.value * 1.1;
await this.prisma.cryptoHistory.create({ await this.prisma.cryptoHistory.create({
data: { data: {
id_crypto: crypto.id, id_crypto: crypto.id,
value: newCryptoValue, value: newCryptoValue,
}, },
}); });
const newQuantity = (crypto.quantity -= dto.amount); const newQuantity = (crypto.quantity -= dto.amount);
return this.prisma.crypto.update({ return this.prisma.crypto.update({
where: { where: {
id: dto.id_crypto, id: dto.id_crypto,
}, },
data: { data: {
value: newCryptoValue, value: newCryptoValue,
quantity: newQuantity, quantity: newQuantity,
}, },
}); });
} }
async editCryptoById(userId: string, cryptoId: string, dto: CryptoDto) { async editCryptoById(userId: string, cryptoId: string, dto: CryptoDto) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const crypto = await this.prisma.crypto.findUnique({ const crypto = await this.prisma.crypto.findUnique({
where: { where: {
id: cryptoId, id: cryptoId,
}, },
}); });
if (!crypto || crypto.id !== cryptoId) if (!crypto || crypto.id !== cryptoId)
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
return this.prisma.crypto.update({ return this.prisma.crypto.update({
where: { where: {
id: crypto.id, id: crypto.id,
}, },
data: { data: {
...dto, ...dto,
}, },
}); });
} }
async deleteCryptoById(userId: string, id: string) { async deleteCryptoById(userId: string, id: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const crypto = await this.prisma.crypto.findUnique({ const crypto = await this.prisma.crypto.findUnique({
where: { where: {
id: id, id: id,
}, },
}); });
if (!crypto || crypto.id !== id) if (!crypto || crypto.id !== id)
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
await this.prisma.crypto.delete({ await this.prisma.crypto.delete({
where: { where: {
id: crypto.id, id: crypto.id,
}, },
}); });
} }
} }

View File

@ -1,32 +1,32 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from "@nestjs/swagger";
import { import {
IsNumber, IsNumber,
IsString, IsString,
IsUUID, IsUUID,
Max, Max,
MaxLength, MaxLength,
Min, Min,
MinLength, MinLength,
} from 'class-validator'; } from "class-validator";
export class BuyCryptoDto { export class BuyCryptoDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Cryptocurrency UUID', description: "Cryptocurrency UUID",
example: '12121-DSZD-E221212-2121221', example: "12121-DSZD-E221212-2121221",
}) })
@MinLength(1) @MinLength(1)
@MaxLength(50) @MaxLength(50)
@IsString() @IsString()
@IsUUID() @IsUUID()
id_crypto: string; id_crypto: string;
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: 'Amount of token traded', description: "Amount of token traded",
example: 2, example: 2,
}) })
@Min(1) @Min(1)
@Max(1000) @Max(1000)
@IsNumber() @IsNumber()
amount: number; amount: number;
} }

View File

@ -1,54 +1,54 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from "@nestjs/swagger";
import { import {
IsNumber, IsNumber,
IsPositive, IsPositive,
IsString, IsString,
IsUrl, IsUrl,
Max, Max,
MaxLength, MaxLength,
Min, Min,
MinLength, MinLength,
} from 'class-validator'; } from "class-validator";
export class CryptoDto { export class CryptoDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Cryptocurrency name', description: "Cryptocurrency name",
example: 'BTC', example: "BTC",
}) })
@MaxLength(50) @MaxLength(50)
@MinLength(1) @MinLength(1)
@IsString() @IsString()
name: string; name: string;
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: 'Value for the cryptocurrency in $', description: "Value for the cryptocurrency in $",
example: 1, example: 1,
}) })
@Min(1) @Min(1)
@Max(10000) @Max(10000)
@IsPositive() @IsPositive()
@IsNumber() @IsNumber()
value: number; value: number;
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: 'Quantity of tokens available on the platform', description: "Quantity of tokens available on the platform",
example: 100, example: 100,
}) })
@Min(1) @Min(1)
@Max(10000) @Max(10000)
@IsPositive() @IsPositive()
@IsNumber() @IsNumber()
quantity: number; quantity: number;
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Image for the cryptocurrency in ', description: "Image for the cryptocurrency in ",
example: 'https://myImage/com', example: "https://myImage/com",
}) })
@MaxLength(255) @MaxLength(255)
@IsUrl() @IsUrl()
@IsString() @IsString()
image: string; image: string;
} }

View File

@ -1 +1 @@
export * from './crypto.dto'; export * from "./crypto.dto";

View File

@ -1,26 +1,26 @@
import { NestFactory } from '@nestjs/core'; import { ValidationPipe } from "@nestjs/common";
import { AppModule } from './app.module'; import { NestFactory } from "@nestjs/core";
import { ValidationPipe } from '@nestjs/common'; import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { AppModule } from "./app.module";
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
app.enableCors(); app.enableCors();
const config = new DocumentBuilder() const config = new DocumentBuilder()
.setTitle('Neptune API') .setTitle("Neptune API")
.setDescription('A fictive app') .setDescription("A fictive app")
.setVersion('1.0') .setVersion("1.0")
.build(); .build();
const document = SwaggerModule.createDocument(app, config); const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document); SwaggerModule.setup("api", app, document);
app.useGlobalPipes( app.useGlobalPipes(
new ValidationPipe({ new ValidationPipe({
whitelist: true, whitelist: true,
}), }),
); );
await app.listen(process.env.PORT || 3000); await app.listen(process.env.PORT || 3000);
} }
bootstrap(); bootstrap();

View File

@ -1 +1 @@
export * from './offer.dto'; export * from "./offer.dto";

View File

@ -1,33 +1,32 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from "@nestjs/swagger";
import { import {
IsNumber, IsNumber,
IsPositive, IsPositive,
IsString, IsString,
IsUUID, IsUUID,
Max, Max,
MaxLength, MaxLength,
Min, Min,
} from 'class-validator'; } from "class-validator";
export class OfferDto { export class OfferDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Cryptocurrency UUID', description: "Cryptocurrency UUID",
example: '12121-DSZD-E221212-6227933', example: "12121-DSZD-E221212-6227933",
}) })
@IsString() @IsString()
@IsUUID() @IsUUID()
id_crypto: string; id_crypto: string;
@ApiProperty({ @ApiProperty({
type: 'number', type: "number",
description: 'Amount traded ', description: "Amount traded ",
example: 21, example: 21,
}) })
@Min(1) @Min(1)
@Max(1000) @Max(1000)
@IsNumber() @IsNumber()
@IsPositive() @IsPositive()
amount: number; amount: number;
} }

View File

@ -1,58 +1,58 @@
import { import {
Body, Body,
Controller, Controller,
Delete, Delete,
Get, Get,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Param, Param,
Patch, Patch,
Post, Post,
UseGuards, UseGuards,
// UseGuards, // UseGuards,
} from '@nestjs/common'; } from "@nestjs/common";
import { GetUser } from '../auth/decorator';
// import { JwtGuard } from '../auth/guard'; // import { JwtGuard } from '../auth/guard';
import { ApiTags } from '@nestjs/swagger'; import { ApiTags } from "@nestjs/swagger";
import { User } from '@prisma/client'; import { User } from "@prisma/client";
import { JwtGuard } from 'src/auth/guard'; import { JwtGuard } from "src/auth/guard";
import { OfferService } from './offer.service'; import { GetUser } from "../auth/decorator";
import { OfferDto } from './dto'; import { OfferDto } from "./dto";
import { OfferService } from "./offer.service";
@UseGuards(JwtGuard) @UseGuards(JwtGuard)
@ApiTags('offer') @ApiTags("offer")
@Controller('offer') @Controller("offer")
export class OfferController { export class OfferController {
constructor(private offerService: OfferService) {} constructor(private offerService: OfferService) {}
@Get('/all') @Get("/all")
getAllRoles(@GetUser() user: User) { getAllRoles(@GetUser() user: User) {
return this.offerService.getOffers(user.id); return this.offerService.getOffers(user.id);
} }
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@Post('/create') @Post("/create")
createRole( createRole(
@Body() @Body()
dto: OfferDto, dto: OfferDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.offerService.createOffer(user.id, dto); return this.offerService.createOffer(user.id, dto);
} }
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Patch('/update/:id') @Patch("/update/:id")
editOfferById( editOfferById(
@Param('id') offerId: string, @Param("id") offerId: string,
@Body() dto: OfferDto, @Body() dto: OfferDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.offerService.editOfferById(user.id, offerId, dto); return this.offerService.editOfferById(user.id, offerId, dto);
} }
@HttpCode(HttpStatus.NO_CONTENT) @HttpCode(HttpStatus.NO_CONTENT)
@Delete('/delete/:id') @Delete("/delete/:id")
deleteOfferById(@Param('id') roleId: string, @GetUser() user: User) { deleteOfferById(@Param("id") roleId: string, @GetUser() user: User) {
return this.offerService.deleteOfferById(user.id, roleId); return this.offerService.deleteOfferById(user.id, roleId);
} }
} }

View File

@ -1,9 +1,9 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { OfferService } from './offer.service'; import { OfferController } from "./offer.controller";
import { OfferController } from './offer.controller'; import { OfferService } from "./offer.service";
@Module({ @Module({
providers: [OfferService], providers: [OfferService],
controllers: [OfferController], controllers: [OfferController],
}) })
export class OfferModule {} export class OfferModule {}

View File

@ -1,88 +1,84 @@
import {ForbiddenException, Injectable} from "@nestjs/common"; import { PrismaService } from "@/prisma/prisma.service";
import {PrismaService} from "@/prisma/prisma.service"; import { ForbiddenException, Injectable } from "@nestjs/common";
import {checkUserHasAccount, checkUserIsAdmin} from "src/utils/checkUser"; import { checkUserHasAccount, checkUserIsAdmin } from "src/utils/checkUser";
import {OfferDto} from "./dto"; import { OfferDto } from "./dto";
@Injectable() @Injectable()
export class OfferService { export class OfferService {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async getOffers(userId: string) { async getOffers(userId: string) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
return this.prisma.offer.findMany({ return this.prisma.offer.findMany({
orderBy: { orderBy: {
created_at: 'desc', created_at: "desc",
}, },
select: { select: {
amount: true, amount: true,
created_at: true, created_at: true,
id_user: true, id_user: true,
Crypto: true, Crypto: true,
}, },
}); });
} }
async createOffer(userId: string, dto: OfferDto) { async createOffer(userId: string, dto: OfferDto) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
return this.prisma.offer.create({ return this.prisma.offer.create({
data: { data: {
id_crypto: dto.id_crypto, id_crypto: dto.id_crypto,
id_user: userId, id_user: userId,
amount: dto.amount, amount: dto.amount,
}, },
}); });
} }
async editOfferById(userId: string, offerId: string, dto: OfferDto) { async editOfferById(userId: string, offerId: string, dto: OfferDto) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
const offer = await this.prisma.offer.findUnique({ const offer = await this.prisma.offer.findUnique({
where: { where: {
id: offerId, id: offerId,
}, },
}); });
const crypto = await this.prisma.crypto.findUnique({ const crypto = await this.prisma.crypto.findUnique({
where: { where: {
id: dto.id_crypto, id: dto.id_crypto,
}, },
}); });
if (!crypto || !crypto.id) { if (!crypto || !crypto.id) {
throw new ForbiddenException('Crypto doesnt exist'); throw new ForbiddenException("Crypto doesnt exist");
} }
if (!offer || offer.id !== offerId) if (!offer || offer.id !== offerId)
throw new ForbiddenException('Offer id mandatory'); throw new ForbiddenException("Offer id mandatory");
return this.prisma.offer.update({ return this.prisma.offer.update({
where: { where: {
id: offerId, id: offerId,
}, },
data: { data: {
...dto, ...dto,
}, },
}); });
} }
async deleteOfferById(userId: string, id: string) { async deleteOfferById(userId: string, id: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const offer = await this.prisma.offer.findUnique({ const offer = await this.prisma.offer.findUnique({
where: { where: {
id: id, id: id,
}, },
}); });
if (!offer || offer.id !== id) if (!offer || offer.id !== id)
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
await this.prisma.offer.delete({ await this.prisma.offer.delete({
where: { where: {
id: id, id: id,
}, },
}); });
} }
} }

View File

@ -1,9 +1,9 @@
import { Global, Module } from '@nestjs/common'; import { Global, Module } from "@nestjs/common";
import { PrismaService } from './prisma.service'; import { PrismaService } from "./prisma.service";
@Global() @Global()
@Module({ @Module({
providers: [PrismaService], providers: [PrismaService],
exports: [PrismaService], exports: [PrismaService],
}) })
export class PrismaModule {} export class PrismaModule {}

View File

@ -1,18 +1,17 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from "@nestjs/common";
// biome-ignore lint/style/useImportType: // biome-ignore lint/style/useImportType:
import { ConfigService } from '@nestjs/config'; import { ConfigService } from "@nestjs/config";
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from "@prisma/client";
@Injectable() @Injectable()
export class PrismaService extends PrismaClient { export class PrismaService extends PrismaClient {
constructor(config: ConfigService) { constructor(config: ConfigService) {
super({ super({
datasources: { datasources: {
db: { db: {
url: config.get('DATABASE_URL'), url: config.get("DATABASE_URL"),
}, },
}, },
}); });
} }
} }

View File

@ -1 +1 @@
export * from './promoCode.dto'; export * from "./promoCode.dto";

View File

@ -1,32 +1,32 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from "@nestjs/swagger";
import { import {
IsNumber, IsNumber,
IsPositive, IsPositive,
IsString, IsString,
Max, Max,
MaxLength, MaxLength,
Min, Min,
MinLength, MinLength,
} from 'class-validator'; } from "class-validator";
export class PromoCodeDto { export class PromoCodeDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Name of the PromoCOde', description: "Name of the PromoCOde",
example: 'FILOU10', example: "FILOU10",
}) })
@MinLength(1) @MinLength(1)
@MaxLength(50) @MaxLength(50)
@IsString() @IsString()
name: string; name: string;
@ApiProperty({ @ApiProperty({
type: Number, type: Number,
description: 'Dollars given for account creation when promoCode applied', description: "Dollars given for account creation when promoCode applied",
example: 100, example: 100,
}) })
@IsPositive() @IsPositive()
@Min(1) @Min(1)
@Max(3000) @Max(3000)
@IsNumber() @IsNumber()
value: number; value: number;
} }

View File

@ -1,57 +1,57 @@
import { import {
Body, Body,
Controller, Controller,
Delete, Delete,
Get, Get,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Param, Param,
Patch, Patch,
Post, Post,
UseGuards, UseGuards,
} from '@nestjs/common'; } from "@nestjs/common";
import { GetUser } from '../auth/decorator'; import { ApiTags } from "@nestjs/swagger";
import { ApiTags } from '@nestjs/swagger'; import { User } from "@prisma/client";
import { User } from '@prisma/client'; import { JwtGuard } from "src/auth/guard";
import { PromoCodeDto } from './dto'; import { GetUser } from "../auth/decorator";
import { PromoCodeService } from './promoCode.service'; import { PromoCodeDto } from "./dto";
import { JwtGuard } from 'src/auth/guard'; import { PromoCodeService } from "./promoCode.service";
@UseGuards(JwtGuard) @UseGuards(JwtGuard)
@ApiTags('promoCode') @ApiTags("promoCode")
@Controller('promoCode') @Controller("promoCode")
export class PromoCodeController { export class PromoCodeController {
constructor(private promoService: PromoCodeService) {} constructor(private promoService: PromoCodeService) {}
@Get('/all') @Get("/all")
getAllPromoCodes(@GetUser() user: User) { getAllPromoCodes(@GetUser() user: User) {
return this.promoService.getPromoCodes(user.id); return this.promoService.getPromoCodes(user.id);
} }
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@Post('/create') @Post("/create")
createPromoCode( createPromoCode(
// @GetUser() user: User, // @GetUser() user: User,
@Body() @Body()
dto: PromoCodeDto, dto: PromoCodeDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.promoService.createPromoCode(user.id, dto); return this.promoService.createPromoCode(user.id, dto);
} }
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Patch('/update/:id') @Patch("/update/:id")
editPromoCodeById( editPromoCodeById(
@Param('id') promoCodeId: string, @Param("id") promoCodeId: string,
@Body() dto: PromoCodeDto, @Body() dto: PromoCodeDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.promoService.editPromoCodeById(user.id, promoCodeId, dto); return this.promoService.editPromoCodeById(user.id, promoCodeId, dto);
} }
@HttpCode(HttpStatus.NO_CONTENT) @HttpCode(HttpStatus.NO_CONTENT)
@Delete('/delete/:id') @Delete("/delete/:id")
deletePromoCodeById(@Param('id') promoCodeId: string, @GetUser() user: User) { deletePromoCodeById(@Param("id") promoCodeId: string, @GetUser() user: User) {
return this.promoService.deletePromoCodeById(user.id, promoCodeId); return this.promoService.deletePromoCodeById(user.id, promoCodeId);
} }
} }

View File

@ -1,9 +1,9 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { PromoCodeController } from './promoCode.controller'; import { PromoCodeController } from "./promoCode.controller";
import { PromoCodeService } from './promoCode.service'; import { PromoCodeService } from "./promoCode.service";
@Module({ @Module({
providers: [PromoCodeService], providers: [PromoCodeService],
controllers: [PromoCodeController], controllers: [PromoCodeController],
}) })
export class PromoCodeModule {} export class PromoCodeModule {}

View File

@ -1,13 +1,13 @@
import { ForbiddenException } from '@nestjs/common';
// biome-ignore lint/style/useImportType:
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from "@/prisma/prisma.service"; import { PrismaService } from "@/prisma/prisma.service";
import { PromoCodeService } from './promoCode.service';
import { checkUserIsAdmin } from "@/utils/checkUser"; import { checkUserIsAdmin } from "@/utils/checkUser";
import { ForbiddenException } from "@nestjs/common";
// biome-ignore lint/style/useImportType:
import { Test, TestingModule } from "@nestjs/testing";
import { PromoCodeService } from "./promoCode.service";
jest.mock('../utils/checkUser'); jest.mock("../utils/checkUser");
describe('PromoCodeService', () => { describe("PromoCodeService", () => {
let service: PromoCodeService; let service: PromoCodeService;
let prisma: PrismaService; let prisma: PrismaService;
@ -37,35 +37,34 @@ describe('PromoCodeService', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
describe('getPromoCodes', () => { describe("getPromoCodes", () => {
it('should get promo codes if user is admin', async () => { it("should get promo codes if user is admin", async () => {
(checkUserIsAdmin as jest.Mock).mockResolvedValue(true); (checkUserIsAdmin as jest.Mock).mockResolvedValue(true);
const mockPromoCodes = [ const mockPromoCodes = [
{ id: '1', name: 'PROMO10', value: 10 }, { id: "1", name: "PROMO10", value: 10 },
{ id: '2', name: 'PROMO20', value: 20 }, { id: "2", name: "PROMO20", value: 20 },
]; ];
mockPrismaService.promoCode.findMany.mockResolvedValue(mockPromoCodes); mockPrismaService.promoCode.findMany.mockResolvedValue(mockPromoCodes);
const result = await service.getPromoCodes('user-id'); const result = await service.getPromoCodes("user-id");
expect(checkUserIsAdmin).toHaveBeenCalledWith('user-id'); expect(checkUserIsAdmin).toHaveBeenCalledWith("user-id");
expect(prisma.promoCode.findMany).toHaveBeenCalledWith({ expect(prisma.promoCode.findMany).toHaveBeenCalledWith({
orderBy: { name: 'asc' }, orderBy: { name: "asc" },
select: { id: true, name: true, value: true }, select: { id: true, name: true, value: true },
}); });
expect(result).toEqual(mockPromoCodes); expect(result).toEqual(mockPromoCodes);
}); });
it('should throw ForbiddenException if user is not admin', async () => { it("should throw ForbiddenException if user is not admin", async () => {
(checkUserIsAdmin as jest.Mock).mockRejectedValue(new ForbiddenException('Not an admin')); (checkUserIsAdmin as jest.Mock).mockRejectedValue(
new ForbiddenException("Not an admin"),
await expect(service.getPromoCodes('user-id')).rejects.toThrow(
ForbiddenException,
); );
expect(checkUserIsAdmin).toHaveBeenCalledWith('user-id'); await expect(service.getPromoCodes("user-id")).rejects.toThrow(ForbiddenException);
expect(checkUserIsAdmin).toHaveBeenCalledWith("user-id");
expect(prisma.promoCode.findMany).not.toHaveBeenCalled(); expect(prisma.promoCode.findMany).not.toHaveBeenCalled();
}); });
}); });
}); });

View File

@ -1,79 +1,75 @@
import { ForbiddenException, Injectable } from '@nestjs/common'; import { ForbiddenException, Injectable } from "@nestjs/common";
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from "../prisma/prisma.service";
import { PromoCodeDto } from './dto'; import { checkUserIsAdmin } from "../utils/checkUser";
import { checkUserIsAdmin } from '../utils/checkUser'; import { PromoCodeDto } from "./dto";
@Injectable() @Injectable()
export class PromoCodeService { export class PromoCodeService {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async getPromoCodes(userId: string) { async getPromoCodes(userId: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
return this.prisma.promoCode.findMany({ return this.prisma.promoCode.findMany({
orderBy: { orderBy: {
name: 'asc', name: "asc",
}, },
select: { select: {
id: true, id: true,
name: true, name: true,
value: true, value: true,
}, },
}); });
} }
async createPromoCode(userId: string, dto: PromoCodeDto) { async createPromoCode(userId: string, dto: PromoCodeDto) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const promoCode = await this.prisma.promoCode.create({ const promoCode = await this.prisma.promoCode.create({
data: { data: {
name: dto.name, name: dto.name,
value: dto.value, value: dto.value,
}, },
}); });
return promoCode; return promoCode;
} }
async editPromoCodeById( async editPromoCodeById(userId: string, promoCodeId: string, dto: PromoCodeDto) {
userId: string, await checkUserIsAdmin(userId);
promoCodeId: string,
dto: PromoCodeDto,
) {
await checkUserIsAdmin(userId);
const promoCode = await this.prisma.promoCode.findUnique({ const promoCode = await this.prisma.promoCode.findUnique({
where: { where: {
id: promoCodeId, id: promoCodeId,
}, },
}); });
if (!promoCode || promoCode.id !== promoCodeId) if (!promoCode || promoCode.id !== promoCodeId)
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
return this.prisma.promoCode.update({ return this.prisma.promoCode.update({
where: { where: {
id: promoCode.id, id: promoCode.id,
}, },
data: { data: {
...dto, ...dto,
}, },
}); });
} }
async deletePromoCodeById(userId: string, id: string) { async deletePromoCodeById(userId: string, id: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const promoCode = await this.prisma.promoCode.findUnique({ const promoCode = await this.prisma.promoCode.findUnique({
where: { where: {
id: id, id: id,
}, },
}); });
if (!promoCode || promoCode.id !== id) if (!promoCode || promoCode.id !== id)
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
await this.prisma.promoCode.delete({ await this.prisma.promoCode.delete({
where: { where: {
id: promoCode.id, id: promoCode.id,
}, },
}); });
} }
} }

View File

@ -1 +1 @@
export * from './role.dto'; export * from "./role.dto";

View File

@ -1,13 +1,13 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from "@nestjs/swagger";
import { IsString, MaxLength, MinLength } from 'class-validator'; import { IsString, MaxLength, MinLength } from "class-validator";
export class RoleDto { export class RoleDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Role Name', description: "Role Name",
example: 'user', example: "user",
}) })
@MinLength(1) @MinLength(1)
@MaxLength(50) @MaxLength(50)
@IsString() @IsString()
name: string; name: string;
} }

View File

@ -1,63 +1,59 @@
import { import {
Body, Body,
Controller, Controller,
Delete, Delete,
Get, Get,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Param, Param,
Patch, Patch,
Post, Post,
UseGuards, UseGuards,
// UseGuards, // UseGuards,
} from '@nestjs/common'; } from "@nestjs/common";
import { GetUser } from '../auth/decorator'; import { ApiTags } from "@nestjs/swagger";
import { User } from "@prisma/client";
import { JwtGuard } from "src/auth/guard";
import { GetUser } from "../auth/decorator";
// import { JwtGuard } from '../auth/guard'; // import { JwtGuard } from '../auth/guard';
import { RoleDto } from './dto'; import { RoleDto } from "./dto";
import { RoleService } from './role.service'; import { RoleService } from "./role.service";
import { ApiTags } from '@nestjs/swagger';
import { User } from '@prisma/client';
import { JwtGuard } from 'src/auth/guard';
@UseGuards(JwtGuard) @UseGuards(JwtGuard)
@ApiTags('role') @ApiTags("role")
@Controller('role') @Controller("role")
export class RoleController { export class RoleController {
constructor(private roleService: RoleService) {} constructor(private roleService: RoleService) {}
@Get('/all') @Get("/all")
getAllRoles(@GetUser() user: User) { getAllRoles(@GetUser() user: User) {
return this.roleService.getRolesAdmin(user.id); return this.roleService.getRolesAdmin(user.id);
} }
// @Get('/cm/all') // @Get('/cm/all')
// getRolesCm(@GetUser() user: User) { // getRolesCm(@GetUser() user: User) {
// return this.roleService.getRolesCm(user) // return this.roleService.getRolesCm(user)
// } // }
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@Post('/create') @Post("/create")
createRole( createRole(
// @GetUser() user: User, // @GetUser() user: User,
@Body() @Body()
dto: RoleDto, dto: RoleDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.roleService.createRole(user.id, dto); return this.roleService.createRole(user.id, dto);
} }
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Patch('/update/:id') @Patch("/update/:id")
editRoleById( editRoleById(@Param("id") roleId: string, @Body() dto: RoleDto, @GetUser() user: User) {
@Param('id') roleId: string, return this.roleService.editRoleById(user.id, roleId, dto);
@Body() dto: RoleDto, }
@GetUser() user: User,
) {
return this.roleService.editRoleById(user.id, roleId, dto);
}
@HttpCode(HttpStatus.NO_CONTENT) @HttpCode(HttpStatus.NO_CONTENT)
@Delete('/delete/:id') @Delete("/delete/:id")
deleteRoleById(@Param('id') roleId: string, @GetUser() user: User) { deleteRoleById(@Param("id") roleId: string, @GetUser() user: User) {
return this.roleService.deleteRoleById(user.id, roleId); return this.roleService.deleteRoleById(user.id, roleId);
} }
} }

View File

@ -1,8 +1,8 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { RoleController } from './role.controller'; import { RoleController } from "./role.controller";
import { RoleService } from './role.service'; import { RoleService } from "./role.service";
@Module({ @Module({
providers: [RoleService], providers: [RoleService],
controllers: [RoleController], controllers: [RoleController],
}) })
export class RoleModule {} export class RoleModule {}

View File

@ -1,72 +1,72 @@
import { ForbiddenException, Injectable } from '@nestjs/common'; import { ForbiddenException, Injectable } from "@nestjs/common";
import { PrismaService } from '../prisma/prisma.service'; import { checkUserIsAdmin } from "src/utils/checkUser";
import { RoleDto } from './dto'; import { PrismaService } from "../prisma/prisma.service";
import { checkUserIsAdmin } from 'src/utils/checkUser'; import { RoleDto } from "./dto";
// import { checkRoleLevel, checkUserIsStaff } from 'src/utils/checkUser'; // import { checkRoleLevel, checkUserIsStaff } from 'src/utils/checkUser';
@Injectable() @Injectable()
export class RoleService { export class RoleService {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async getRolesAdmin(userId: string) { async getRolesAdmin(userId: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
return this.prisma.role.findMany({ return this.prisma.role.findMany({
orderBy: { orderBy: {
name: 'asc', name: "asc",
}, },
select: { select: {
id: true, id: true,
name: true, name: true,
}, },
}); });
} }
async createRole(userId: string, dto: RoleDto) { async createRole(userId: string, dto: RoleDto) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const role = await this.prisma.role.create({ const role = await this.prisma.role.create({
data: { data: {
name: dto.name, name: dto.name,
}, },
}); });
return role; return role;
} }
async editRoleById(userId: string, roleId: string, dto: RoleDto) { async editRoleById(userId: string, roleId: string, dto: RoleDto) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const role = await this.prisma.role.findUnique({ const role = await this.prisma.role.findUnique({
where: { where: {
id: roleId, id: roleId,
}, },
}); });
if (!role || role.id !== roleId) if (!role || role.id !== roleId)
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
return this.prisma.role.update({ return this.prisma.role.update({
where: { where: {
id: roleId, id: roleId,
}, },
data: { data: {
...dto, ...dto,
}, },
}); });
} }
async deleteRoleById(userId: string, id: string) { async deleteRoleById(userId: string, id: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
const role = await this.prisma.role.findUnique({ const role = await this.prisma.role.findUnique({
where: { where: {
id: id, id: id,
}, },
}); });
if (!role || role.id !== id) if (!role || role.id !== id)
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
await this.prisma.role.delete({ await this.prisma.role.delete({
where: { where: {
id: id, id: id,
}, },
}); });
} }
} }

View File

@ -1 +1 @@
export * from './trade.dto'; export * from "./trade.dto";

View File

@ -1,13 +1,13 @@
import { ApiProperty } from '@nestjs/swagger'; import { ApiProperty } from "@nestjs/swagger";
import { IsNotEmpty, IsString, IsUUID } from 'class-validator'; import { IsNotEmpty, IsString, IsUUID } from "class-validator";
export class TradeDto { export class TradeDto {
@ApiProperty({ @ApiProperty({
type: String, type: String,
description: 'Offer UUID ', description: "Offer UUID ",
example: '121212-DSDZ1-21212DJDZ-31313', example: "121212-DSDZ1-21212DJDZ-31313",
}) })
@IsUUID() @IsUUID()
@IsNotEmpty() @IsNotEmpty()
@IsString() @IsString()
id_offer: string; id_offer: string;
} }

View File

@ -1,38 +1,38 @@
import { import {
Body, Body,
Controller, Controller,
Get, Get,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Post, Post,
UseGuards, UseGuards,
} from '@nestjs/common'; } from "@nestjs/common";
import { GetUser } from '../auth/decorator'; import { ApiTags } from "@nestjs/swagger";
import { ApiTags } from '@nestjs/swagger'; import { User } from "@prisma/client";
import { User } from '@prisma/client'; import { JwtGuard } from "src/auth/guard";
import { TradeService } from './trade.service'; import { GetUser } from "../auth/decorator";
import { TradeDto } from './dto'; import { TradeDto } from "./dto";
import { JwtGuard } from 'src/auth/guard'; import { TradeService } from "./trade.service";
@UseGuards(JwtGuard) @UseGuards(JwtGuard)
@ApiTags('trade') @ApiTags("trade")
@Controller('trade') @Controller("trade")
export class TradeController { export class TradeController {
constructor(private tradeService: TradeService) {} constructor(private tradeService: TradeService) {}
@Get('/all') @Get("/all")
getAllPromoCodes(@GetUser() user: User) { getAllPromoCodes(@GetUser() user: User) {
return this.tradeService.getTrades(user.id); return this.tradeService.getTrades(user.id);
} }
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@Post('/create') @Post("/create")
createPromoCode( createPromoCode(
// @GetUser() user: User, // @GetUser() user: User,
@Body() @Body()
dto: TradeDto, dto: TradeDto,
@GetUser() user: User, @GetUser() user: User,
) { ) {
return this.tradeService.createTrade(user.id, dto); return this.tradeService.createTrade(user.id, dto);
} }
} }

View File

@ -1,9 +1,9 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { TradeService } from './trade.service'; import { TradeController } from "./trade.controller";
import { TradeController } from './trade.controller'; import { TradeService } from "./trade.service";
@Module({ @Module({
providers: [TradeService], providers: [TradeService],
controllers: [TradeController], controllers: [TradeController],
}) })
export class TradeModule {} export class TradeModule {}

View File

@ -1,173 +1,173 @@
import { ForbiddenException, Injectable } from '@nestjs/common'; import { ForbiddenException, Injectable } from "@nestjs/common";
import { PrismaService } from '../prisma/prisma.service'; import { checkUserHasAccount, checkUserIsAdmin } from "src/utils/checkUser";
import { checkUserHasAccount, checkUserIsAdmin } from 'src/utils/checkUser'; import { PrismaService } from "../prisma/prisma.service";
import { TradeDto } from './dto'; import { TradeDto } from "./dto";
@Injectable() @Injectable()
export class TradeService { export class TradeService {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async getTrades(userId: string) { async getTrades(userId: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
return this.prisma.trade.findMany({ return this.prisma.trade.findMany({
orderBy: { orderBy: {
created_at: 'desc', created_at: "desc",
}, },
// include: { // include: {
// Giver: true, // Giver: true,
// Receiver: true, // Receiver: true,
// Crypto: true, // Crypto: true,
// }, // },
select: { select: {
Giver: { Giver: {
select: { select: {
firstName: true, firstName: true,
lastName: true, lastName: true,
pseudo: true, pseudo: true,
dollarAvailables: true, dollarAvailables: true,
}, },
}, },
Receiver: { Receiver: {
select: { select: {
firstName: true, firstName: true,
lastName: true, lastName: true,
pseudo: true, pseudo: true,
dollarAvailables: true, dollarAvailables: true,
}, },
}, },
Crypto: true, Crypto: true,
}, },
}); });
} }
async getLastTrades() { async getLastTrades() {
return this.prisma.trade.findMany({ return this.prisma.trade.findMany({
orderBy: { orderBy: {
created_at: 'desc', created_at: "desc",
}, },
select: { select: {
amount_traded: true, amount_traded: true,
Crypto: true, Crypto: true,
}, },
}); });
} }
async createTrade(userId: string, dto: TradeDto) { async createTrade(userId: string, dto: TradeDto) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
const offer = await this.prisma.offer.findUnique({ const offer = await this.prisma.offer.findUnique({
where: { where: {
id: dto.id_offer, id: dto.id_offer,
}, },
}); });
const crypto = await this.prisma.crypto.findFirst({ const crypto = await this.prisma.crypto.findFirst({
where: { where: {
id: offer.id_crypto, id: offer.id_crypto,
}, },
}); });
const buyer = await this.prisma.user.findFirst({ const buyer = await this.prisma.user.findFirst({
where: { where: {
id: offer.id_user, id: offer.id_user,
}, },
}); });
const price = crypto.value * offer.amount; const price = crypto.value * offer.amount;
if (buyer.dollarAvailables < price) { if (buyer.dollarAvailables < price) {
throw new ForbiddenException( throw new ForbiddenException(
`Acqueror ${buyer.pseudo} doesnt have enough money to make this trade`, `Acqueror ${buyer.pseudo} doesnt have enough money to make this trade`,
); );
} }
const asset = await this.prisma.userHasCrypto.findFirst({ const asset = await this.prisma.userHasCrypto.findFirst({
where: { where: {
id_crypto: offer.id_crypto, id_crypto: offer.id_crypto,
id_user: offer.id_user, id_user: offer.id_user,
}, },
}); });
if (!asset || asset.amount < offer.amount) { if (!asset || asset.amount < offer.amount) {
throw new ForbiddenException(`Seller doesnt have enough ${crypto.name} `); throw new ForbiddenException(`Seller doesnt have enough ${crypto.name} `);
} }
const trade = await this.prisma.trade.create({ const trade = await this.prisma.trade.create({
data: { data: {
id_giver: offer.id_user, id_giver: offer.id_user,
id_receiver: userId, id_receiver: userId,
id_crypto: offer.id_crypto, id_crypto: offer.id_crypto,
amount_traded: offer.amount, amount_traded: offer.amount,
}, },
}); });
const newBalanceGiver = (asset.amount -= offer.amount); const newBalanceGiver = (asset.amount -= offer.amount);
await this.prisma.userHasCrypto.update({ await this.prisma.userHasCrypto.update({
where: { where: {
id: asset.id, id: asset.id,
}, },
data: { data: {
amount: newBalanceGiver, amount: newBalanceGiver,
}, },
}); });
const receiverAssets = await this.prisma.userHasCrypto.findFirst({ const receiverAssets = await this.prisma.userHasCrypto.findFirst({
where: { where: {
id_user: userId, id_user: userId,
id_crypto: offer.id_crypto, id_crypto: offer.id_crypto,
}, },
}); });
if (!receiverAssets) { if (!receiverAssets) {
await this.prisma.userHasCrypto.create({ await this.prisma.userHasCrypto.create({
data: { data: {
id_user: userId, id_user: userId,
id_crypto: offer.id_crypto, id_crypto: offer.id_crypto,
amount: offer.amount, amount: offer.amount,
createdAt: new Date(), createdAt: new Date(),
}, },
}); });
} else { } else {
const newBalanceReceiver = receiverAssets.amount + offer.amount; const newBalanceReceiver = receiverAssets.amount + offer.amount;
await this.prisma.userHasCrypto.update({ await this.prisma.userHasCrypto.update({
where: { where: {
id: receiverAssets.id, id: receiverAssets.id,
}, },
data: { data: {
amount: newBalanceReceiver, amount: newBalanceReceiver,
}, },
}); });
} }
const newValue = crypto.value * 1.1; const newValue = crypto.value * 1.1;
await this.prisma.cryptoHistory.create({ await this.prisma.cryptoHistory.create({
data: { data: {
id_crypto: crypto.id, id_crypto: crypto.id,
value: newValue, value: newValue,
}, },
}); });
await this.prisma.crypto.update({ await this.prisma.crypto.update({
where: { where: {
id: crypto.id, id: crypto.id,
}, },
data: { data: {
value: newValue, value: newValue,
}, },
}); });
const prevAmount = buyer.dollarAvailables; const prevAmount = buyer.dollarAvailables;
await this.prisma.user.update({ await this.prisma.user.update({
where: { where: {
id: userId, id: userId,
}, },
data: { data: {
dollarAvailables: prevAmount - price, dollarAvailables: prevAmount - price,
}, },
}); });
await this.prisma.offer.delete({ await this.prisma.offer.delete({
where: { where: {
id: offer.id, id: offer.id,
}, },
}); });
return trade; return trade;
} }
} }

View File

@ -1,36 +1,36 @@
import { Controller, Get, UseGuards } from '@nestjs/common'; import { Controller, Get, UseGuards } from "@nestjs/common";
import { GetUser } from '../auth/decorator'; import { ApiTags } from "@nestjs/swagger";
import { JwtGuard } from '../auth/guard'; import { User } from "@prisma/client";
import { ApiTags } from '@nestjs/swagger'; import { GetUser } from "../auth/decorator";
import { UserService } from './user.service'; import { JwtGuard } from "../auth/guard";
import { User } from '@prisma/client'; import { UserService } from "./user.service";
@ApiTags('user') @ApiTags("user")
@UseGuards(JwtGuard) @UseGuards(JwtGuard)
@Controller('user') @Controller("user")
export class UserController { export class UserController {
constructor(private userService: UserService) {} constructor(private userService: UserService) {}
@Get('/my-assets') @Get("/my-assets")
GetMyAssets( GetMyAssets(
@GetUser() @GetUser()
user: User, user: User,
) { ) {
return this.userService.getMyAssets(user.id); return this.userService.getMyAssets(user.id);
} }
@Get('/users-assets') @Get("/users-assets")
GetAlLAssets( GetAlLAssets(
@GetUser() @GetUser()
user: User, user: User,
) { ) {
return this.userService.getUsersAssets(user.id); return this.userService.getUsersAssets(user.id);
} }
@Get('/my-trades') @Get("/my-trades")
GetMyTrades( GetMyTrades(
@GetUser() @GetUser()
user: User, user: User,
) { ) {
return this.userService.getMyTrades(user.id); return this.userService.getMyTrades(user.id);
} }
} }

View File

@ -1,8 +1,8 @@
import { Module } from '@nestjs/common'; import { Module } from "@nestjs/common";
import { UserService } from './user.service'; import { UserController } from "./user.controller";
import { UserController } from './user.controller'; import { UserService } from "./user.service";
@Module({ @Module({
providers: [UserService], providers: [UserService],
controllers: [UserController], controllers: [UserController],
}) })
export class UserModule {} export class UserModule {}

View File

@ -1,81 +1,80 @@
import {Injectable} from "@nestjs/common"; import { PrismaService } from "@/prisma/prisma.service";
import {PrismaService} from "@/prisma/prisma.service"; import { Injectable } from "@nestjs/common";
import {checkUserHasAccount, checkUserIsAdmin} from "src/utils/checkUser"; import { checkUserHasAccount, checkUserIsAdmin } from "src/utils/checkUser";
@Injectable() @Injectable()
export class UserService { export class UserService {
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
/** /**
* Retrieves the assets of a given user, including their first name, last name, available dollars, * Retrieves the assets of a given user, including their first name, last name, available dollars,
* pseudo, and associated cryptocurrencies. * pseudo, and associated cryptocurrencies.
* *
* @param {string} userId - The unique identifier of the user whose assets are being retrieved. * @param {string} userId - The unique identifier of the user whose assets are being retrieved.
* @return A promise that resolves to an object containing the user's assets and associated data. * @return A promise that resolves to an object containing the user's assets and associated data.
*/ */
async getMyAssets(userId: string) { async getMyAssets(userId: string) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
return this.prisma.user.findUnique({ return this.prisma.user.findUnique({
where: { where: {
id: userId, id: userId,
}, },
select: { select: {
firstName: true, firstName: true,
lastName: true, lastName: true,
dollarAvailables: true, dollarAvailables: true,
pseudo: true, pseudo: true,
UserHasCrypto: { UserHasCrypto: {
select: { select: {
Crypto: true, Crypto: true,
}, },
}, },
}, },
}); });
} }
/** /**
* Retrieves the assets of users based on user ID. * Retrieves the assets of users based on user ID.
* *
* @param {string} userId - The ID of the user requesting the assets. * @param {string} userId - The ID of the user requesting the assets.
* @return A promise that resolves to an array of user assets. * @return A promise that resolves to an array of user assets.
*/ */
async getUsersAssets(userId: string) { async getUsersAssets(userId: string) {
await checkUserIsAdmin(userId); await checkUserIsAdmin(userId);
return this.prisma.user.findMany({ return this.prisma.user.findMany({
select: { select: {
firstName: true, firstName: true,
lastName: true, lastName: true,
pseudo: true, pseudo: true,
dollarAvailables: true, dollarAvailables: true,
UserHasCrypto: { UserHasCrypto: {
select: { select: {
Crypto: true, Crypto: true,
amount: true, amount: true,
}, },
}, },
}, },
take: 20, take: 20,
}); });
} }
/** /**
* Fetches all trades associated with a given user. * Fetches all trades associated with a given user.
* *
* @param {string} userId - The unique identifier of the user. * @param {string} userId - The unique identifier of the user.
* @return A promise that resolves to an array of trade objects. * @return A promise that resolves to an array of trade objects.
*/ */
async getMyTrades(userId: string) { async getMyTrades(userId: string) {
await checkUserHasAccount(userId); await checkUserHasAccount(userId);
return this.prisma.trade.findMany({ return this.prisma.trade.findMany({
where: { where: {
OR: [{id_giver: userId}, {id_receiver: userId}], OR: [{ id_giver: userId }, { id_receiver: userId }],
}, },
include: { include: {
Crypto: true, Crypto: true,
}, },
}); });
} }
} }

View File

@ -1,86 +1,86 @@
import { ForbiddenException } from '@nestjs/common'; import { ForbiddenException } from "@nestjs/common";
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from "@prisma/client";
import { Roles } from './const/const'; import { Roles } from "./const/const";
const prisma = new PrismaClient(); const prisma = new PrismaClient();
export async function checkRoleLevel(userId: string, level: string) { export async function checkRoleLevel(userId: string, level: string) {
if (!userId || !level) { if (!userId || !level) {
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
} }
checkRoleExist(level); checkRoleExist(level);
const user = await prisma.user.findUnique({ const user = await prisma.user.findUnique({
where: { where: {
id: userId, id: userId,
}, },
}); });
if (user?.roleId) { if (user?.roleId) {
const role = await prisma.role.findFirst({ const role = await prisma.role.findFirst({
where: { where: {
id: user.roleId, id: user.roleId,
}, },
}); });
if (role?.id) { if (role?.id) {
checkRoleExist(role.name); checkRoleExist(role.name);
if (level === Roles.ADMIN && role.name !== Roles.ADMIN) { if (level === Roles.ADMIN && role.name !== Roles.ADMIN) {
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
} }
} else { } else {
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
} }
} else { } else {
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
} }
} }
function checkRoleExist(role: string) { function checkRoleExist(role: string) {
switch (role) { switch (role) {
case Roles.ADMIN: case Roles.ADMIN:
case Roles.USER: case Roles.USER:
break; break;
default: default:
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
} }
} }
export async function checkUserHasAccount(jwtId: string) { export async function checkUserHasAccount(jwtId: string) {
if (jwtId) { if (jwtId) {
const user = await prisma.user.findUnique({ const user = await prisma.user.findUnique({
where: { where: {
id: jwtId, id: jwtId,
isActive: true, isActive: true,
}, },
}); });
if (!user || !user.id) { if (!user || !user.id) {
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
} }
} else { } else {
throw new ForbiddenException('Access to resources denied'); throw new ForbiddenException("Access to resources denied");
} }
} }
export async function checkUserIsAdmin(jwtId: string) { export async function checkUserIsAdmin(jwtId: string) {
if (jwtId) { if (jwtId) {
const user = await prisma.user.findUnique({ const user = await prisma.user.findUnique({
where: { where: {
id: jwtId, id: jwtId,
isActive: true, isActive: true,
}, },
include: { include: {
Role: true, Role: true,
}, },
}); });
if (!user || !user.id) { if (!user || !user.id) {
throw new ForbiddenException('Access to resources denied2'); throw new ForbiddenException("Access to resources denied2");
} }
if (user.Role.name !== Roles.ADMIN) { if (user.Role.name !== Roles.ADMIN) {
throw new ForbiddenException('Access to resources denied3'); throw new ForbiddenException("Access to resources denied3");
} }
} else { } else {
throw new ForbiddenException('Access to resources denied4'); throw new ForbiddenException("Access to resources denied4");
} }
} }

View File

@ -1,4 +1,4 @@
export const Roles = { export const Roles = {
ADMIN: 'admin', ADMIN: "admin",
USER: 'user', USER: "user",
}; };

View File

@ -1,16 +1,16 @@
// auth/test/mocks.ts // auth/test/mocks.ts
import { User } from '@prisma/client'; import { User } from "@prisma/client";
export const getMockUser = (): User => ({ export const getMockUser = (): User => ({
id: 'user-id', id: "user-id",
email: 'test@example.com', email: "test@example.com",
firstName: 'Test User', firstName: "Test User",
lastName: 'Test', lastName: "Test",
hash: 'test-hash', hash: "test-hash",
pseudo: 'test-pseudo', pseudo: "test-pseudo",
isActive: true, isActive: true,
created_at: new Date(), created_at: new Date(),
updated_at: new Date(), updated_at: new Date(),
roleId: 'user', roleId: "user",
dollarAvailables: 1000, dollarAvailables: 1000,
}); });