Compare commits
5 Commits
0635c512cc
...
bc12f94e41
Author | SHA1 | Date | |
---|---|---|---|
bc12f94e41 | |||
df28d3aa52 | |||
3d5ea6ac30 | |||
2fb6cd6e83 | |||
34f028ef9f |
@ -397,6 +397,8 @@ async function getSelf(req: Request, res: Response) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.debug("\nController loaded.");
|
||||||
|
|
||||||
const AuthController = {
|
const AuthController = {
|
||||||
register: registerUser,
|
register: registerUser,
|
||||||
login: loginUser,
|
login: loginUser,
|
||||||
|
@ -171,6 +171,8 @@ async function deleteBrand(req: Request, res: Response): Promise<Response> {
|
|||||||
|
|
||||||
//TODO get models of the brand
|
//TODO get models of the brand
|
||||||
|
|
||||||
|
logger.debug("\nController loaded.");
|
||||||
|
|
||||||
const BrandController = {
|
const BrandController = {
|
||||||
create: createBrand,
|
create: createBrand,
|
||||||
update: updateBrand,
|
update: updateBrand,
|
||||||
|
@ -177,6 +177,8 @@ async function getBySlugCategory(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
logger.debug("\nController loaded.");
|
||||||
|
|
||||||
const CategoryController = {
|
const CategoryController = {
|
||||||
create: createCategory,
|
create: createCategory,
|
||||||
update: updateCategory,
|
update: updateCategory,
|
||||||
|
@ -131,6 +131,8 @@ async function deleteModel(req: Request, res: Response): Promise<Response> {
|
|||||||
|
|
||||||
//TODO get model with vehicle available.
|
//TODO get model with vehicle available.
|
||||||
|
|
||||||
|
logger.debug("\nController loaded.");
|
||||||
|
|
||||||
const ModelController = {
|
const ModelController = {
|
||||||
create: createModel,
|
create: createModel,
|
||||||
update: updateModel,
|
update: updateModel,
|
||||||
|
48
src/interfaces/database/IDbFactorize.ts
Normal file
48
src/interfaces/database/IDbFactorize.ts
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
/**
|
||||||
|
* Represents the output of the factorization function.
|
||||||
|
*/
|
||||||
|
export interface IDbFactorizeOutput {
|
||||||
|
/**
|
||||||
|
* Description: The variable `_valuesArray` is an array that can contain values of type `string`, `boolean`, `number`, or `Date`.
|
||||||
|
* (The value associated with the keys of `_keysTemplate`)
|
||||||
|
*
|
||||||
|
* @type {Array<string | boolean | number | Date>}
|
||||||
|
*/
|
||||||
|
_valuesArray: Array<string | boolean | number | Date>;
|
||||||
|
/**
|
||||||
|
* Represents the SQL Query template for the keys.
|
||||||
|
* @type {string}
|
||||||
|
*/
|
||||||
|
_keysTemplate: string;
|
||||||
|
/**
|
||||||
|
* The total number of fields.
|
||||||
|
*
|
||||||
|
* @type {number}
|
||||||
|
*/
|
||||||
|
totalFields: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface IDbFactorizeInput represents the input required to factorize a SQL query.
|
||||||
|
*/
|
||||||
|
export interface IDbFactorizeInput {
|
||||||
|
/**
|
||||||
|
* An object containing values that will be in a SQL Query.
|
||||||
|
*
|
||||||
|
* @type {Array<string | boolean | number | Date>}
|
||||||
|
*/
|
||||||
|
values: object;
|
||||||
|
/**
|
||||||
|
* Represents the name of the action that will result of the prepared SQL Query.
|
||||||
|
*
|
||||||
|
* @type {string}
|
||||||
|
*/
|
||||||
|
actionName: string;
|
||||||
|
/**
|
||||||
|
* Indicates whether an error should be thrown when encountering an error.
|
||||||
|
* If set to true, an error will be thrown. If set to false or not provided, the error will not be thrown.
|
||||||
|
*
|
||||||
|
* @type {boolean}
|
||||||
|
*/
|
||||||
|
throwOnError?: true;
|
||||||
|
}
|
8
src/interfaces/services/IUserUpdate.ts
Normal file
8
src/interfaces/services/IUserUpdate.ts
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
export interface IUserUpdate {
|
||||||
|
id?: string;
|
||||||
|
username?: string;
|
||||||
|
firstname?: string;
|
||||||
|
lastname?: string;
|
||||||
|
dob?: Date;
|
||||||
|
gdpr?: Date;
|
||||||
|
}
|
@ -168,7 +168,7 @@ async function deleteBrand(brandId: string): Promise<boolean> {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug("Service loaded.");
|
logger.debug("\nService loaded.");
|
||||||
|
|
||||||
const BrandService = {
|
const BrandService = {
|
||||||
create: createBrand,
|
create: createBrand,
|
||||||
|
@ -127,7 +127,7 @@ async function deleteCategory(id: string): Promise<unknown> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug("Service loaded.");
|
logger.debug("\nService loaded.");
|
||||||
|
|
||||||
const CategoryService = {
|
const CategoryService = {
|
||||||
create: createCategory,
|
create: createCategory,
|
||||||
|
@ -64,7 +64,7 @@ async function JwtSignService(
|
|||||||
.sign(new TextEncoder().encode(`${process.env["JWT_SECRET"]}`));
|
.sign(new TextEncoder().encode(`${process.env["JWT_SECRET"]}`));
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug("Service loaded.");
|
logger.debug("\nService loaded.");
|
||||||
|
|
||||||
const JwtService = {
|
const JwtService = {
|
||||||
verify: JwtVerifyService,
|
verify: JwtVerifyService,
|
||||||
|
@ -135,7 +135,7 @@ async function getAllModels(): Promise<IDbModel[] | null> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug("Service loaded.");
|
logger.debug("\nService loaded.");
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* ModelService is responsible for managing models.
|
* ModelService is responsible for managing models.
|
||||||
|
@ -7,6 +7,8 @@ import type { IDbUser } from "@interfaces/database/IDbUser";
|
|||||||
import type { IDbVehicle } from "@interfaces/database/IDbVehicle";
|
import type { IDbVehicle } from "@interfaces/database/IDbVehicle";
|
||||||
import mysql, { type Connection, type ConnectionOptions } from "mysql2";
|
import mysql, { type Connection, type ConnectionOptions } from "mysql2";
|
||||||
import { Logger } from "tslog";
|
import { Logger } from "tslog";
|
||||||
|
import {IUserUpdate} from "@interfaces/services/IUserUpdate";
|
||||||
|
import {IDbFactorizeInput, IDbFactorizeOutput} from "@interfaces/database/IDbFactorize";
|
||||||
|
|
||||||
const access: ConnectionOptions = {
|
const access: ConnectionOptions = {
|
||||||
host: `${process.env["MYSQL_HOST"]}`,
|
host: `${process.env["MYSQL_HOST"]}`,
|
||||||
@ -32,7 +34,7 @@ class MysqlHandler {
|
|||||||
this.Logger.error(`Error connecting to MySQL: ${err}`);
|
this.Logger.error(`Error connecting to MySQL: ${err}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
this.Logger.info(`Connected to MySQL database (${access.database})`);
|
this.Logger.info(`\n\n> Connected to MySQL database (${access.database})\n`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
closeConnection() {
|
closeConnection() {
|
||||||
@ -52,6 +54,40 @@ class MysqlHandler {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factorize the input data values into a database query.
|
||||||
|
*
|
||||||
|
* @param {IDbFactorizeInput} data - The input data containing values to factorize.
|
||||||
|
* @return {Promise<IDbFactorizeOutput>} - A promise resolving to the factorized output.
|
||||||
|
*/
|
||||||
|
factorize(data: IDbFactorizeInput): Promise<IDbFactorizeOutput> {
|
||||||
|
return new Promise((resolve, reject)=>{
|
||||||
|
try {
|
||||||
|
const _sqlQueryKeys = Object.keys(data.values).map((key: string) => `\'${key}\' = ?`)
|
||||||
|
const values = Object.values(data.values).map((val)=>val)
|
||||||
|
this.Logger.debug(`\n\n>-> Factorized ${_sqlQueryKeys.length} keys for a prepare Query.\n>-> Action: ${data.actionName}\n`)
|
||||||
|
const sqlQueryKeys = _sqlQueryKeys.join(', ')
|
||||||
|
|
||||||
|
const factorizedOutput: IDbFactorizeOutput = {
|
||||||
|
_keysTemplate: sqlQueryKeys,
|
||||||
|
totalFields: _sqlQueryKeys.length,
|
||||||
|
_valuesArray: values
|
||||||
|
}
|
||||||
|
resolve(factorizedOutput);
|
||||||
|
} catch (err) {
|
||||||
|
if (data.throwOnError) throw new Error(`${err}`)
|
||||||
|
this.Logger.error(`\n|\n${err}\n|`)
|
||||||
|
reject(`${err}`)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes a query using the provided queryString and values.
|
||||||
|
* @param {string} queryString - The SQL query string to execute.
|
||||||
|
* @param {Array<string | boolean | Date | number>} values - The values to be inserted into the query.
|
||||||
|
* @returns {Promise<unknown>} - A promise that resolves with the query results or rejects with an error.
|
||||||
|
*/
|
||||||
execute(
|
execute(
|
||||||
queryString: string,
|
queryString: string,
|
||||||
values: Array<string | boolean | Date | number>,
|
values: Array<string | boolean | Date | number>,
|
||||||
@ -138,38 +174,25 @@ const MySqlService = {
|
|||||||
/**
|
/**
|
||||||
* Updates a user in the database.
|
* Updates a user in the database.
|
||||||
* @param {MysqlHandler} handler - The MySQL handler object.
|
* @param {MysqlHandler} handler - The MySQL handler object.
|
||||||
* @param {IDbUser} data - The updated user data.
|
* @param {IUserUpdate} data - The updated user data.
|
||||||
* @returns {Promise<IDbStatusResult>} - A promise that resolves to the result of the update operation.
|
* @returns {Promise<IDbStatusResult>} - A promise that resolves to the result of the update operation.
|
||||||
* @throws {Error} If an error occurs during the update operation.
|
* @throws {Error} If an error occurs during the update operation.
|
||||||
*/
|
*/
|
||||||
update(handler: MysqlHandler, data: IDbUser): Promise<IDbStatusResult> {
|
update(handler: MysqlHandler, data: IUserUpdate): Promise<IDbStatusResult> {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if (!data.id) return reject("Id is undefined");
|
if (!data.id) return reject("Id is undefined");
|
||||||
if (data.id.length !== 36) return reject("Id invalid");
|
if (data.id.length !== 36) return reject("Id invalid");
|
||||||
|
if (data.gdpr && typeof data.gdpr !== typeof Date) {
|
||||||
|
return reject("Invalid gdpr date.")
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
|
const _values = [];
|
||||||
const _template = `
|
const _template = `
|
||||||
${data.username ? "`username` = ?," : null}
|
${data.username ? "`username` = ?," && _values.push(data.username) as unknown as void : null}
|
||||||
${data.firstname ? "`firstname` = ?," : null}
|
${data.firstname ? "`firstname` = ?," : null}
|
||||||
${data.lastname ? "`lastname` = ?," : null}
|
${data.lastname ? "`lastname` = ?," : null}
|
||||||
${data.dob ? "`dob` = ?," : null}
|
${data.dob ? "`dob` = ?," : null}
|
||||||
${data.email ? "`email` = ?," : null}
|
${data.gdpr ? "`gdpr` = ?," : null}`
|
||||||
${data.is_mail_verified ? "`is_mail_verified` = ?," : null}
|
|
||||||
${data.is_admin ? "`is_admin` = ?," : null}
|
|
||||||
${data.gdpr ? "`gdpr` = ?," : null}
|
|
||||||
${data.hash ? "`hash` = ?" : null}`;
|
|
||||||
const _values = [
|
|
||||||
data.username,
|
|
||||||
data.firstname,
|
|
||||||
data.lastname,
|
|
||||||
data.dob,
|
|
||||||
data.email,
|
|
||||||
data.is_mail_verified,
|
|
||||||
data.is_admin,
|
|
||||||
data.gdpr,
|
|
||||||
data.hash,
|
|
||||||
data.id,
|
|
||||||
];
|
|
||||||
|
|
||||||
const _sql = `UPDATE "users" SET ${_template} WHERE 'id' = ?`;
|
const _sql = `UPDATE "users" SET ${_template} WHERE 'id' = ?`;
|
||||||
handler.execute(_sql, _values).then((result) => {
|
handler.execute(_sql, _values).then((result) => {
|
||||||
|
@ -5,7 +5,6 @@ import { ErrorType, type ISError } from "@interfaces/services/ISError";
|
|||||||
import CredentialService from "@services/credential.service";
|
import CredentialService from "@services/credential.service";
|
||||||
import JwtService from "@services/jwt.service";
|
import JwtService from "@services/jwt.service";
|
||||||
import MySqlService from "@services/mysql.service";
|
import MySqlService from "@services/mysql.service";
|
||||||
import MysqlService from "@services/mysql.service";
|
|
||||||
import { Logger } from "tslog";
|
import { Logger } from "tslog";
|
||||||
import { v4 } from "uuid";
|
import { v4 } from "uuid";
|
||||||
|
|
||||||
@ -28,7 +27,7 @@ async function getUserByEmail(targetEmail: string): Promise<IDbUser | ISError> {
|
|||||||
try {
|
try {
|
||||||
const dbUser = await MySqlService.User.getByEmail(DbHandler, targetEmail);
|
const dbUser = await MySqlService.User.getByEmail(DbHandler, targetEmail);
|
||||||
if (dbUser === undefined) {
|
if (dbUser === undefined) {
|
||||||
logger.info(`User not found (${targetEmail})`);
|
logger.info(`\n\n> User not found (${targetEmail})\n`);
|
||||||
return {
|
return {
|
||||||
error: ErrorType.NotFound,
|
error: ErrorType.NotFound,
|
||||||
message: "The user was not fund.",
|
message: "The user was not fund.",
|
||||||
@ -53,7 +52,7 @@ async function getUserByEmail(targetEmail: string): Promise<IDbUser | ISError> {
|
|||||||
async function getUserFromIdService(id: string): Promise<IDbUser | ISError> {
|
async function getUserFromIdService(id: string): Promise<IDbUser | ISError> {
|
||||||
try {
|
try {
|
||||||
if (!id || id.length !== 36) {
|
if (!id || id.length !== 36) {
|
||||||
logger.info(`Invalid ID (${id})`);
|
logger.info(`\n\n> Invalid ID (${id})\n`);
|
||||||
return {
|
return {
|
||||||
error: ErrorType.InvalidData,
|
error: ErrorType.InvalidData,
|
||||||
message: "Invalid ID length.",
|
message: "Invalid ID length.",
|
||||||
@ -76,194 +75,201 @@ async function getUserFromIdService(id: string): Promise<IDbUser | ISError> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//ToTest
|
||||||
|
/**
|
||||||
|
* Registers a new user.
|
||||||
|
*
|
||||||
|
* @param {IReqRegister} inputData - The input data for registration.
|
||||||
|
* @return {Promise<ISError | string>} - A Promise that resolves to either an error or a token.
|
||||||
|
*/
|
||||||
async function register(inputData: IReqRegister): Promise<ISError | string> {
|
async function register(inputData: IReqRegister): Promise<ISError | string> {
|
||||||
if (inputData.password.length < 6) {
|
try {
|
||||||
return {
|
if (inputData.password.length < 6) {
|
||||||
error: ErrorType.InvalidData,
|
return {
|
||||||
message: "Password must be at least 6 characters long.",
|
error: ErrorType.InvalidData,
|
||||||
};
|
message: "Password must be at least 6 characters long.",
|
||||||
}
|
};
|
||||||
//TODO check Object content keys
|
}
|
||||||
const passwordHash = await CredentialService.hash(`${inputData.password}`);
|
|
||||||
|
|
||||||
// Does the new user has accepted GDPR ?
|
const passwordHash = await CredentialService.hash(`${inputData.password}`);
|
||||||
if (inputData.gdpr !== true) {
|
|
||||||
return {
|
|
||||||
error: ErrorType.InvalidData,
|
|
||||||
message: "GDPR acceptance is required.",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const currentDate = new Date();
|
|
||||||
|
|
||||||
// Check if exist and return
|
// Does the new user has accepted GDPR ?
|
||||||
const dbUserIfExist: IDbUser | ISError = await getUserByEmail(
|
if (inputData.gdpr !== true) {
|
||||||
inputData.email,
|
return {
|
||||||
);
|
error: ErrorType.InvalidData,
|
||||||
if ("error" in dbUserIfExist) {
|
message: "GDPR acceptance is required.",
|
||||||
return {
|
};
|
||||||
error: dbUserIfExist.error,
|
}
|
||||||
message: dbUserIfExist.message,
|
const currentDate = new Date();
|
||||||
};
|
|
||||||
}
|
// Check if exist and return
|
||||||
if (dbUserIfExist.id) {
|
const dbUserIfExist: IDbUser | ISError = await getUserByEmail(
|
||||||
logger.info(
|
inputData.email,
|
||||||
`User already exist for email "${inputData.email}".\n(${dbUserIfExist.username}::${dbUserIfExist.id})\n`,
|
|
||||||
);
|
);
|
||||||
return {
|
if ("error" in dbUserIfExist) {
|
||||||
error: ErrorType.UnAuthorized,
|
return {
|
||||||
message: "User already exists.",
|
error: dbUserIfExist.error,
|
||||||
};
|
message: dbUserIfExist.message,
|
||||||
}
|
};
|
||||||
const currentId = v4();
|
}
|
||||||
const NewUser = await MySqlService.User.insert(DbHandler, {
|
if (dbUserIfExist.id) {
|
||||||
id: currentId,
|
logger.info(
|
||||||
email: inputData.email,
|
`\n\n> User already exist for email "${inputData.email}".\n(${dbUserIfExist.username}::${dbUserIfExist.id})\n`,
|
||||||
username: inputData.username,
|
);
|
||||||
firstname: inputData.firstName,
|
return {
|
||||||
lastname: inputData.lastName,
|
error: ErrorType.UnAuthorized,
|
||||||
dob: inputData.dob,
|
message: "User already exists.",
|
||||||
hash: passwordHash,
|
};
|
||||||
gdpr: currentDate,
|
}
|
||||||
is_admin: false,
|
const currentId = v4();
|
||||||
is_mail_verified: false,
|
const NewUser = await MySqlService.User.insert(DbHandler, {
|
||||||
});
|
id: currentId,
|
||||||
if ("error" in NewUser || NewUser.affectedRows === 0) {
|
email: inputData.email,
|
||||||
|
username: inputData.username,
|
||||||
|
firstname: inputData.firstName,
|
||||||
|
lastname: inputData.lastName,
|
||||||
|
dob: inputData.dob,
|
||||||
|
hash: passwordHash,
|
||||||
|
gdpr: currentDate,
|
||||||
|
is_admin: false,
|
||||||
|
is_mail_verified: false,
|
||||||
|
});
|
||||||
|
if ("error" in NewUser || NewUser.affectedRows === 0) {
|
||||||
|
return {
|
||||||
|
error: ErrorType.DatabaseError,
|
||||||
|
message: "Error when inserting user in database.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
logger.info(`\n\n> New user created ! (${inputData.username}::${currentId})\n`);
|
||||||
|
|
||||||
|
// JWT
|
||||||
|
const token = await JwtService.sign(
|
||||||
|
{
|
||||||
|
sub: currentId,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
alg: "HS512",
|
||||||
|
},
|
||||||
|
"1d",
|
||||||
|
"user",
|
||||||
|
);
|
||||||
|
return token;
|
||||||
|
} catch (err) {
|
||||||
|
logger.error(`\n\n${err}\n`);
|
||||||
return {
|
return {
|
||||||
error: ErrorType.DatabaseError,
|
error: ErrorType.DatabaseError,
|
||||||
message: "Error when inserting user in database.",
|
message: "An unknown error occurred.",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
logger.info(`New user created ! (${inputData.username}::${currentId})`);
|
|
||||||
|
|
||||||
// JWT
|
|
||||||
const token = await JwtService.sign(
|
|
||||||
{
|
|
||||||
sub: NewUser.id,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
alg: "HS512",
|
|
||||||
},
|
|
||||||
"1d",
|
|
||||||
"user",
|
|
||||||
);
|
|
||||||
return token;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function login(ReqData: IReqLogin) {
|
//ToTest
|
||||||
//const passwordHash = await getHashFromPassword(sanitizedData.password);
|
/**
|
||||||
const dbUser = await MysqlService.User.getByUsername(
|
* Logs in a user with the provided input data.
|
||||||
DbHandler,
|
*
|
||||||
ReqData.username,
|
* @param inputData - The input data for the login operation.
|
||||||
);
|
* @property email - The email of the user.
|
||||||
if (!dbUser) {
|
* @property password - The password of the user.
|
||||||
console.log(`LoginService :> User does not exist (${ReqData.username})`);
|
* @returns A promise that resolves to either an error or a token string.
|
||||||
|
* @throws {ISError} - If an error occurs in the login process.
|
||||||
|
* @throws {string} - If the login was successful, returns a token string.
|
||||||
|
*/
|
||||||
|
async function login(inputData: IReqLogin): Promise<ISError | string> {
|
||||||
|
try {
|
||||||
|
const dbUser = await getUserByEmail(inputData.email);
|
||||||
|
if ("error" in dbUser) {
|
||||||
|
return {
|
||||||
|
error: dbUser.error,
|
||||||
|
message: dbUser.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!dbUser.id) {
|
||||||
|
return {
|
||||||
|
error: ErrorType.NotFound,
|
||||||
|
message: "User not found.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const isPasswordValid = await CredentialService.compare(
|
||||||
|
inputData.password,
|
||||||
|
dbUser.hash
|
||||||
|
);
|
||||||
|
if (!isPasswordValid) {
|
||||||
|
return {
|
||||||
|
error: ErrorType.UnAuthorized,
|
||||||
|
message: "Invalid password.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const token = await JwtService.sign(
|
||||||
|
{
|
||||||
|
sub: dbUser.id,
|
||||||
|
p: [{
|
||||||
|
isAdmin: dbUser.is_admin,
|
||||||
|
gdpr: dbUser.gdpr
|
||||||
|
}]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
alg: "HS512",
|
||||||
|
},
|
||||||
|
"1d",
|
||||||
|
"user"
|
||||||
|
);
|
||||||
|
return token;
|
||||||
|
} catch (err) {
|
||||||
|
logger.error(`\n\n${err}\n`);
|
||||||
return {
|
return {
|
||||||
error: "userNotFound",
|
error: ErrorType.DatabaseError,
|
||||||
|
message: "An unknown error occurred.",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (ReqData.password.length < 6) {
|
|
||||||
console.log("X");
|
|
||||||
console.log(`LoginService :> Invalid password (${ReqData.username})`);
|
|
||||||
return {
|
|
||||||
error: "invalidPassword",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
const isPasswordValid = await CredentialService.compare(
|
|
||||||
ReqData.password,
|
|
||||||
dbUser.hash,
|
|
||||||
);
|
|
||||||
if (!isPasswordValid) {
|
|
||||||
console.log(isPasswordValid);
|
|
||||||
console.log(`LoginService :> Invalid password (${ReqData.username})`);
|
|
||||||
return {
|
|
||||||
error: "invalidPassword",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
// biome-ignore lint/style/useConst: <explanation>
|
|
||||||
let userData = {
|
|
||||||
error: "none",
|
|
||||||
jwt: "",
|
|
||||||
user: {
|
|
||||||
id: dbUser.id,
|
|
||||||
username: dbUser.username,
|
|
||||||
displayName: dbUser.displayName,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
userData.jwt = await JwtService.sign(
|
|
||||||
{
|
|
||||||
sub: dbUser.id,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
alg: "HS512",
|
|
||||||
},
|
|
||||||
"7d",
|
|
||||||
"user",
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log("USERDATA :>");
|
|
||||||
console.log(userData);
|
|
||||||
return userData;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//TOTest
|
||||||
/**
|
/**
|
||||||
* Retrieves all users from the database.
|
* Retrieves all users from the database.
|
||||||
*
|
*
|
||||||
* @async
|
* @returns {Promise<Array<IDbUser> | ISError>} The list of users, or an error object if an error occurred.
|
||||||
* @function getAllUsersService
|
|
||||||
* @returns {Promise<{iat: number, users: Array<user>, length: number}>} - The response object containing the users array and its length.
|
|
||||||
*/
|
*/
|
||||||
async function getAllUsersService() {
|
async function getAllUsersService(): Promise<Array<IDbUser> | ISError> {
|
||||||
const users = await Db.collection("users").find().toArray();
|
try {
|
||||||
// biome-ignore lint/complexity/noForEach: <explanation>
|
const allUsers = await MySqlService.User.getAll(DbHandler);
|
||||||
users.forEach((user) => {
|
if (allUsers === undefined) {
|
||||||
delete user.passwordHash;
|
logger.error(`Error retrieving all users.`);
|
||||||
delete user._id;
|
return {
|
||||||
delete user.gdpr;
|
error: ErrorType.DatabaseError,
|
||||||
});
|
message: "An unknown error occurred.",
|
||||||
logger.info(`Query ${users.length} user(s)`);
|
};
|
||||||
return {
|
}
|
||||||
iat: Date.now(),
|
return allUsers;
|
||||||
users: users,
|
} catch (err) {
|
||||||
length: users.length,
|
logger.error(`\n\n${err}\n`);
|
||||||
};
|
return {
|
||||||
|
error: ErrorType.DatabaseError,
|
||||||
|
message: "An unknown error occurred.",
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
async function editUserService(targetId, inputData: IDbUser): Promise<ISError | boolean> {
|
||||||
* Edits a user in the database.
|
if (!targetId || targetId.length !== 36) {
|
||||||
*
|
logger.info(`\n\n> Invalid ID (${targetId})\n`);
|
||||||
* @param {string} targetId - The ID of the user to be edited.
|
return {
|
||||||
* @param {object} sanitizedData - The sanitized data to update the user with.
|
error: ErrorType.InvalidData,
|
||||||
* @returns {object} - An object indicating the result of the operation.
|
message: "Invalid ID length.",
|
||||||
* If the user is not found, the error property will be a string "userNotFound".
|
};
|
||||||
* Otherwise, the error property will be a string "none".
|
}
|
||||||
*/
|
const dbUser = await MySqlService.User.getById(DbHandler, targetId)
|
||||||
async function editUserService(targetId, sanitizedData) {
|
if (!dbUser.id) {
|
||||||
if (sanitizedData.password) {
|
|
||||||
const passwordHash = await getHashFromPassword(sanitizedData.password);
|
|
||||||
delete sanitizedData.password;
|
|
||||||
logger.info(`Changing password for user "${targetId}"`);
|
|
||||||
sanitizedData.passwordHash = passwordHash;
|
|
||||||
}
|
|
||||||
const updatedUserResult = await Db.collection("users").updateOne(
|
|
||||||
{
|
|
||||||
id: targetId,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
$set: sanitizedData,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (updatedUserResult.modifiedCount === 0) {
|
|
||||||
logger.info(`EDIT :> User not found (${targetId})`);
|
|
||||||
return {
|
return {
|
||||||
error: "userNotFound",
|
error: ErrorType.NotFound,
|
||||||
};
|
message: "User not found.",
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
const result = await MySqlService.User.update(DbHandler, {
|
||||||
logger.info(`EDIT :> User updated (${targetId})`);
|
username: inputData.username,
|
||||||
return {
|
firstname: inputData.firstname,
|
||||||
error: "none",
|
lastname: inputData.lastname,
|
||||||
};
|
dob: inputData.dob,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -285,7 +291,8 @@ async function deleteUserService(targetId) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.debug("Service loaded.");
|
logger.debug("\nService loaded.");
|
||||||
|
|
||||||
const UserService = {
|
const UserService = {
|
||||||
register: register,
|
register: register,
|
||||||
login: login,
|
login: login,
|
||||||
|
Loading…
x
Reference in New Issue
Block a user