Refactor code to use consistent tab spacing

Replaced mixed spaces and tabs with consistent tab spacing across multiple files for better code readability and maintenance. Adjusted import statements and string literals formatting to maintain coherence.
This commit is contained in:
Mathis H (Avnyr) 2024-10-15 16:51:12 +02:00
parent 6f9d25a58b
commit 3c31223293
Signed by: Mathis
GPG Key ID: DD9E0666A747D126
4 changed files with 213 additions and 215 deletions

View File

@ -1,14 +1,14 @@
import { import {
Body, Body,
Controller, Controller,
Delete, Delete,
Get, Get,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
Patch, Patch,
Post, Post,
UnauthorizedException, UnauthorizedException,
UseGuards, UseGuards,
} from "@nestjs/common"; } from "@nestjs/common";
import { SignInDto, SignUpDto } from "apps/backend/src/app/auth/auth.dto"; import { SignInDto, SignUpDto } from "apps/backend/src/app/auth/auth.dto";
import { AuthService } from "apps/backend/src/app/auth/auth.service"; import { AuthService } from "apps/backend/src/app/auth/auth.service";
@ -16,50 +16,50 @@ import { UserGuard } from "./auth.guard";
@Controller("auth") @Controller("auth")
export class AuthController { export class AuthController {
constructor(private readonly authService: AuthService) { } constructor(private readonly authService: AuthService) {}
//TODO Initial account validation for admin privileges //TODO Initial account validation for admin privileges
//POST signup //POST signup
@HttpCode(HttpStatus.CREATED) @HttpCode(HttpStatus.CREATED)
@Post("signup") @Post("signup")
async signUp(@Body() dto: SignUpDto) { async signUp(@Body() dto: SignUpDto) {
return this.authService.doRegister(dto); return this.authService.doRegister(dto);
} }
//POST signin //POST signin
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Post("signin") @Post("signin")
async signIn(@Body() dto: SignInDto) { async signIn(@Body() dto: SignInDto) {
return this.authService.doLogin(dto); return this.authService.doLogin(dto);
} }
//GET me -- Get current user data via jwt //GET me -- Get current user data via jwt
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Get("me") @Get("me")
@UseGuards(UserGuard) @UseGuards(UserGuard)
async getMe(@Body() body: object) { async getMe(@Body() body: object) {
// @ts-ignore // @ts-ignore
const targetId = body.sourceUserId; const targetId = body.sourceUserId;
const userData = await this.authService.fetchUserById(targetId); const userData = await this.authService.fetchUserById(targetId);
if (!userData) { if (!userData) {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
return userData; return userData;
} }
//DELETE me //DELETE me
@HttpCode(HttpStatus.FOUND) @HttpCode(HttpStatus.FOUND)
@Delete("me") @Delete("me")
@UseGuards(UserGuard) @UseGuards(UserGuard)
async deleteMe(@Body() body: object) { async deleteMe(@Body() body: object) {
// @ts-ignore // @ts-ignore
const targetId = body.sourceUserId; const targetId = body.sourceUserId;
try { try {
await this.authService.deleteUser(targetId); await this.authService.deleteUser(targetId);
} catch (err) { } catch (err) {
throw new UnauthorizedException(); throw new UnauthorizedException();
} }
} }
/* /*
//PATCH me //PATCH me
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Patch("me") @Patch("me")

View File

@ -1,7 +1,7 @@
import { import {
Injectable, Injectable,
OnModuleInit, OnModuleInit,
UnauthorizedException, UnauthorizedException,
} from "@nestjs/common"; } from "@nestjs/common";
import { SignInDto, SignUpDto } from "apps/backend/src/app/auth/auth.dto"; import { SignInDto, SignUpDto } from "apps/backend/src/app/auth/auth.dto";
import { CredentialsService } from "apps/backend/src/app/credentials/credentials.service"; import { CredentialsService } from "apps/backend/src/app/credentials/credentials.service";
@ -11,102 +11,102 @@ import { eq } from "drizzle-orm";
@Injectable() @Injectable()
export class AuthService implements OnModuleInit { export class AuthService implements OnModuleInit {
constructor( constructor(
private db: DbService, private db: DbService,
private credentials: CredentialsService, private credentials: CredentialsService,
) { } ) {}
//TODO Initial account validation for admin privileges //TODO Initial account validation for admin privileges
async doRegister(data: SignUpDto) { async doRegister(data: SignUpDto) {
const existingUser = await this.db const existingUser = await this.db
.use() .use()
.select() .select()
.from(UsersTable) .from(UsersTable)
.where(eq(UsersTable.email, data.email)) .where(eq(UsersTable.email, data.email))
.prepare("userByEmail") .prepare("userByEmail")
.execute(); .execute();
if (existingUser.length !== 0) if (existingUser.length !== 0)
throw new UnauthorizedException("Already exist"); throw new UnauthorizedException("Already exist");
const query = await this.db const query = await this.db
.use() .use()
.insert(UsersTable) .insert(UsersTable)
.values({ .values({
//firstName: data.firstName, //firstName: data.firstName,
//lastName: data.lastName, //lastName: data.lastName,
email: data.email, email: data.email,
hash: await this.credentials.hash(data.password), hash: await this.credentials.hash(data.password),
}) })
.returning() .returning()
.prepare("insertUser") .prepare("insertUser")
.execute() .execute()
.catch((err) => { .catch((err) => {
console.error(err); console.error(err);
throw new UnauthorizedException( throw new UnauthorizedException(
"Error occurred while inserting user", "Error occurred while inserting user",
err, err,
); );
}); });
return { return {
message: "User created, check your email for validation.", message: "User created, check your email for validation.",
token: await this.credentials.signAuthToken({ sub: query[0].uuid }), token: await this.credentials.signAuthToken({ sub: query[0].uuid }),
}; };
} }
async doLogin(data: SignInDto) { async doLogin(data: SignInDto) {
const user = await this.db const user = await this.db
.use() .use()
.select() .select()
.from(UsersTable) .from(UsersTable)
.where(eq(UsersTable.email, data.email)) .where(eq(UsersTable.email, data.email))
.prepare("userByEmail") .prepare("userByEmail")
.execute(); .execute();
if (user.length !== 1) if (user.length !== 1)
throw new UnauthorizedException("Invalid credentials"); throw new UnauthorizedException("Invalid credentials");
const passwordMatch = await this.credentials.check( const passwordMatch = await this.credentials.check(
data.password, data.password,
user[0].hash, user[0].hash,
); );
if (!passwordMatch) throw new UnauthorizedException("Invalid credentials"); if (!passwordMatch) throw new UnauthorizedException("Invalid credentials");
const token = await this.credentials.signAuthToken({ sub: user[0].uuid }); const token = await this.credentials.signAuthToken({ sub: user[0].uuid });
return { return {
message: "Login successful", message: "Login successful",
token: token, token: token,
}; };
} }
async fetchUserById(userId: string) { async fetchUserById(userId: string) {
const user = await this.db const user = await this.db
.use() .use()
.select() .select()
.from(UsersTable) .from(UsersTable)
.where(eq(UsersTable.uuid, userId)) .where(eq(UsersTable.uuid, userId))
.prepare("userById") .prepare("userById")
.execute(); .execute();
if (user.length !== 1) { if (user.length !== 1) {
throw new UnauthorizedException("User not found"); throw new UnauthorizedException("User not found");
} }
delete user[0].hash; delete user[0].hash;
//delete user[0].emailCode; //delete user[0].emailCode;
return user[0]; return user[0];
} }
async fetchUsers() { async fetchUsers() {
//TODO Pagination //TODO Pagination
const usersInDb = await this.db.use().select().from(UsersTable); const usersInDb = await this.db.use().select().from(UsersTable);
const result = { const result = {
total: usersInDb.length, total: usersInDb.length,
users: usersInDb.map((user) => { users: usersInDb.map((user) => {
delete user.hash; delete user.hash;
return { return {
...user, ...user,
}; };
}), }),
}; };
console.log(result); console.log(result);
return result; return result;
} }
/* /*
async updateUser(targetId: string, userData: IUserUpdateData) { async updateUser(targetId: string, userData: IUserUpdateData) {
const validationResult = UserUpdateSchema.safeParse(userData); const validationResult = UserUpdateSchema.safeParse(userData);
if (!validationResult.success) { if (!validationResult.success) {
@ -132,26 +132,26 @@ export class AuthService implements OnModuleInit {
} }
*/ */
async deleteUser(targetId: string) { async deleteUser(targetId: string) {
await this.db await this.db
.use() .use()
.delete(UsersTable) .delete(UsersTable)
.where(eq(UsersTable.uuid, targetId)) .where(eq(UsersTable.uuid, targetId))
.prepare("deleteUserById") .prepare("deleteUserById")
.execute() .execute()
.catch((err) => { .catch((err) => {
console.error(err); console.error(err);
throw new UnauthorizedException( throw new UnauthorizedException(
"Error occurred while deleting user", "Error occurred while deleting user",
err, err,
); );
}); });
return true; return true;
} }
async onModuleInit() { async onModuleInit() {
setTimeout(() => { setTimeout(() => {
this.fetchUsers(); this.fetchUsers();
}, 2000); }, 2000);
} }
} }

View File

@ -6,51 +6,51 @@ import { JWTPayload, generateSecret } from "jose";
@Injectable() @Injectable()
export class CredentialsService { export class CredentialsService {
constructor(private readonly configService: ConfigService) { } constructor(private readonly configService: ConfigService) {}
async hash(plaintextPassword: string) { async hash(plaintextPassword: string) {
if (plaintextPassword.length < 6) if (plaintextPassword.length < 6)
throw new BadRequestException("Password is not strong enough !"); throw new BadRequestException("Password is not strong enough !");
return argon.hash(plaintextPassword, { return argon.hash(plaintextPassword, {
secret: Buffer.from(this.configService.get("APP_HASH_SECRET")), secret: Buffer.from(this.configService.get("APP_HASH_SECRET")),
}); });
} }
async check(plaintextPassword: string, hashedPassword: string) { async check(plaintextPassword: string, hashedPassword: string) {
return argon.verify(hashedPassword, plaintextPassword, { return argon.verify(hashedPassword, plaintextPassword, {
secret: Buffer.from(this.configService.get("APP_HASH_SECRET")), secret: Buffer.from(this.configService.get("APP_HASH_SECRET")),
}); });
} }
async verifyAuthToken(token: string) { async verifyAuthToken(token: string) {
try { try {
const result = await jose.jwtVerify( const result = await jose.jwtVerify(
token, token,
Uint8Array.from(this.configService.get("APP_TOKEN_SECRET")), Uint8Array.from(this.configService.get("APP_TOKEN_SECRET")),
{ {
audience: "auth:user", audience: "auth:user",
issuer: "FabLab", issuer: "FabLab",
}, },
); );
console.log(result); console.log(result);
return result; return result;
} catch (error) { } catch (error) {
console.log(error); console.log(error);
throw new BadRequestException("Invalid token"); throw new BadRequestException("Invalid token");
} }
} }
async signAuthToken(payload: JWTPayload) { async signAuthToken(payload: JWTPayload) {
console.log(this.configService.get("APP_TOKEN_SECRET")); console.log(this.configService.get("APP_TOKEN_SECRET"));
const token = new jose.SignJWT(payload) const token = new jose.SignJWT(payload)
.setProtectedHeader({ alg: "HS512", enc: "A128CBC-HS512" }) .setProtectedHeader({ alg: "HS512", enc: "A128CBC-HS512" })
.setIssuedAt() .setIssuedAt()
.setExpirationTime("5 day") .setExpirationTime("5 day")
.setIssuer("FabLab") .setIssuer("FabLab")
.setAudience("auth:user"); .setAudience("auth:user");
console.log(token); console.log(token);
return await token.sign( return await token.sign(
Uint8Array.from(this.configService.get("APP_TOKEN_SECRET")), Uint8Array.from(this.configService.get("APP_TOKEN_SECRET")),
); );
} }
} }

View File

@ -1,17 +1,15 @@
import { Logger } from "@nestjs/common"; import { Logger } from "@nestjs/common";
import { NestFactory } from "@nestjs/core"; import { NestFactory } from "@nestjs/core";
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import helmet from "helmet"; import helmet from "helmet";
import { AppModule } from "./app/app.module"; import { AppModule } from "./app/app.module";
async function bootstrap() { async function bootstrap() {
const config = new DocumentBuilder() const config = new DocumentBuilder()
.setTitle('Fab Explorer') .setTitle("Fab Explorer")
.setDescription("Définition de l'api du FabLab Explorer") .setDescription("Définition de l'api du FabLab Explorer")
.setVersion('1.0') .setVersion("1.0")
.build(); .build();
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
@ -21,7 +19,7 @@ async function bootstrap() {
const port = process.env.PORT || 3000; const port = process.env.PORT || 3000;
const document = SwaggerModule.createDocument(app, config); const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document); SwaggerModule.setup("api", app, document);
await app.listen(port); await app.listen(port);
Logger.log( Logger.log(