Compare commits
No commits in common. "355cb0ec908e15a99cea5ed8f2409ca0290a1948" and "28671146d10497451856840388bb554d1869d176" have entirely different histories.
355cb0ec90
...
28671146d1
@ -28,6 +28,6 @@
|
||||
"formatter": {
|
||||
"indentStyle": "tab",
|
||||
"indentWidth": 2,
|
||||
"lineWidth": 80
|
||||
"lineWidth": 64
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -22,7 +22,10 @@ const logger = new Logger({
|
||||
* - error: "exist" if the user already exists
|
||||
* - Otherwise, the registered user data
|
||||
*/
|
||||
async function registerUser(req: Request, res: Response): Promise<unknown> {
|
||||
async function registerUser(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<unknown> {
|
||||
const body = req.body;
|
||||
if (!body) {
|
||||
logger.warn(`Invalid input data (${req.ip})`);
|
||||
@ -56,7 +59,8 @@ async function registerUser(req: Request, res: Response): Promise<unknown> {
|
||||
lastName: `${body.lastName}`,
|
||||
};
|
||||
|
||||
const RegisterServiceResult = await UserService.register(sanitizeData);
|
||||
const RegisterServiceResult =
|
||||
await UserService.register(sanitizeData);
|
||||
|
||||
if (RegisterServiceResult.error === "gdprNotApproved") {
|
||||
logger.warn(`GDPR not approved (${req.ip})`);
|
||||
@ -75,7 +79,10 @@ async function registerUser(req: Request, res: Response): Promise<unknown> {
|
||||
|
||||
// SUCCESS
|
||||
logger.info(`User registered successfully (${req.ip})`);
|
||||
return res.type("application/json").status(201).json(RegisterServiceResult);
|
||||
return res
|
||||
.type("application/json")
|
||||
.status(201)
|
||||
.json(RegisterServiceResult);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -86,7 +93,10 @@ async function registerUser(req: Request, res: Response): Promise<unknown> {
|
||||
*
|
||||
* @return {Promise<void>} A promise that resolves when the user is logged in or rejects with an error.
|
||||
*/
|
||||
async function loginUser(req: Request, res: Response): Promise<void> {
|
||||
async function loginUser(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<void> {
|
||||
const body = req.body;
|
||||
if (!body) {
|
||||
res.type("application/json").status(400).json({
|
||||
@ -121,7 +131,10 @@ async function loginUser(req: Request, res: Response): Promise<void> {
|
||||
message: "Invalid password.",
|
||||
});
|
||||
}
|
||||
res.type("application/json").status(200).json(LoginServiceResult);
|
||||
res
|
||||
.type("application/json")
|
||||
.status(200)
|
||||
.json(LoginServiceResult);
|
||||
}
|
||||
|
||||
async function getAllUsers(req: Request, res: Response) {
|
||||
@ -157,7 +170,10 @@ async function getAllUsers(req: Request, res: Response) {
|
||||
error: "Internal server error",
|
||||
});
|
||||
}
|
||||
return res.type("application/json").status(200).json(AllUserResponse);
|
||||
return res
|
||||
.type("application/json")
|
||||
.status(200)
|
||||
.json(AllUserResponse);
|
||||
}
|
||||
|
||||
async function getUser(req: Request, res: Response) {
|
||||
@ -251,11 +267,14 @@ async function editUser(req: Request, res: Response) {
|
||||
//TODO Interface
|
||||
const modifiedData = {};
|
||||
//@ts-ignore
|
||||
if (body.firstName) modifiedData.firstName = `${body.firstName}`;
|
||||
if (body.firstName)
|
||||
modifiedData.firstName = `${body.firstName}`;
|
||||
//@ts-ignore
|
||||
if (body.lastName) modifiedData.lastName = `${body.lastName}`;
|
||||
if (body.lastName)
|
||||
modifiedData.lastName = `${body.lastName}`;
|
||||
//@ts-ignore
|
||||
if (body.displayName) modifiedData.displayName = `${body.displayName}`;
|
||||
if (body.displayName)
|
||||
modifiedData.displayName = `${body.displayName}`;
|
||||
//TODO Case handled with hashing by the service.
|
||||
//if (body.password) modifiedData.password = `${body.password}`;
|
||||
|
||||
@ -271,21 +290,31 @@ async function editUser(req: Request, res: Response) {
|
||||
});
|
||||
}
|
||||
if (EditUserServiceResult.error !== "none") {
|
||||
logger.error(`Error occurred during user edit (${req.ip})`);
|
||||
logger.error(
|
||||
`Error occurred during user edit (${req.ip})`,
|
||||
);
|
||||
return res.type("application/json").status(500).json({
|
||||
error: "Internal server error",
|
||||
});
|
||||
}
|
||||
return res.type("application/json").status(200).json(EditUserServiceResult);
|
||||
return res
|
||||
.type("application/json")
|
||||
.status(200)
|
||||
.json(EditUserServiceResult);
|
||||
}
|
||||
//Not itself or
|
||||
logger.warn(`Unauthorized access attempt, not self or admin (${req.ip})`);
|
||||
logger.warn(
|
||||
`Unauthorized access attempt, not self or admin (${req.ip})`,
|
||||
);
|
||||
return res.type("application/json").status(403).json({
|
||||
error: "Unauthorized",
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteUser(req: Request, res: Response): Promise<Response> {
|
||||
async function deleteUser(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const authHeader = req.headers.authorization;
|
||||
const bearerToken = authHeader?.split(" ")[1];
|
||||
if (!bearerToken) {
|
||||
@ -311,9 +340,13 @@ async function deleteUser(req: Request, res: Response): Promise<Response> {
|
||||
});
|
||||
}
|
||||
if (sourceUser.is_admin || sourceUser.id === payload.sub) {
|
||||
const deleteUserServiceResult = await UserService.delete(`${targetUserId}`);
|
||||
const deleteUserServiceResult = await UserService.delete(
|
||||
`${targetUserId}`,
|
||||
);
|
||||
if (!deleteUserServiceResult) {
|
||||
logger.error(`Error occurred during user delete (${req.ip})`);
|
||||
logger.error(
|
||||
`Error occurred during user delete (${req.ip})`,
|
||||
);
|
||||
return res.type("application/json").status(500).json({
|
||||
error: "Internal server error",
|
||||
});
|
||||
|
@ -17,9 +17,14 @@ const logger = new Logger({
|
||||
*
|
||||
* @returns A Promise that resolves to the response object with a status code and a JSON message indicating the success or failure of brand creation.
|
||||
*/
|
||||
async function createBrand(req: Request, res: Response): Promise<Response> {
|
||||
async function createBrand(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const body: IDbBrand = req.body;
|
||||
const doesExist = await BrandService.getBySlug(`${body.slug_name}`);
|
||||
const doesExist = await BrandService.getBySlug(
|
||||
`${body.slug_name}`,
|
||||
);
|
||||
if (doesExist) {
|
||||
logger.error("Brand already exists");
|
||||
return res.status(400).json({
|
||||
@ -37,7 +42,9 @@ async function createBrand(req: Request, res: Response): Promise<Response> {
|
||||
error: "Failed to create brand",
|
||||
});
|
||||
}
|
||||
logger.info(`Brand created successfully ! (${body.slug_name})`);
|
||||
logger.info(
|
||||
`Brand created successfully ! (${body.slug_name})`,
|
||||
);
|
||||
return res.status(201).json({
|
||||
message: "Brand created successfully",
|
||||
});
|
||||
@ -50,7 +57,10 @@ async function createBrand(req: Request, res: Response): Promise<Response> {
|
||||
* @param {Response} res - The HTTP response object.
|
||||
* @return {Promise<Response>} A promise that resolves with the HTTP response.
|
||||
*/
|
||||
async function updateBrand(req: Request, res: Response): Promise<Response> {
|
||||
async function updateBrand(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const body: IDbBrand = req.body;
|
||||
const brandSlug = req.params["brandSlug"];
|
||||
if (!brandSlug) {
|
||||
@ -90,7 +100,10 @@ async function updateBrand(req: Request, res: Response): Promise<Response> {
|
||||
* @param {Response} res - The response object to send the result.
|
||||
* @returns {Promise<Response>} - A promise that resolves to the response with the retrieved brand.
|
||||
*/
|
||||
async function getBySlugBrand(req: Request, res: Response): Promise<Response> {
|
||||
async function getBySlugBrand(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const brandSlug = req.params["brandSlug"];
|
||||
if (!brandSlug) {
|
||||
logger.error("Brand slug is missing");
|
||||
@ -116,7 +129,10 @@ async function getBySlugBrand(req: Request, res: Response): Promise<Response> {
|
||||
* @param {Response} res - The response object.
|
||||
* @returns {Promise<Response>} - A promise with the response object.
|
||||
*/
|
||||
async function getAllBrand(_req: Request, res: Response): Promise<Response> {
|
||||
async function getAllBrand(
|
||||
_req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const brands = await BrandService.getAll();
|
||||
if (!brands) {
|
||||
logger.error("Failed to retrieve brands");
|
||||
@ -140,7 +156,10 @@ async function getAllBrand(_req: Request, res: Response): Promise<Response> {
|
||||
* @param {Response} res - The response object.
|
||||
* @returns {Promise<Response>} - The response object indicating the success or failure of the delete operation.
|
||||
*/
|
||||
async function deleteBrand(req: Request, res: Response): Promise<Response> {
|
||||
async function deleteBrand(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const brandSlug = req.params["brandSlug"];
|
||||
if (!brandSlug) {
|
||||
logger.error("Brand slug is missing");
|
||||
|
@ -15,9 +15,14 @@ const logger = new Logger({
|
||||
* @param {Response} res - The response object to send back to the client.
|
||||
* @returns {Promise<Response>} The response object indicating the outcome of the category creation.
|
||||
*/
|
||||
async function createCategory(req: Request, res: Response): Promise<Response> {
|
||||
async function createCategory(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const body: IDbCategory = req.body;
|
||||
const doesExist = await CategoryService.getBySlug(`${body.slug_name}`);
|
||||
const doesExist = await CategoryService.getBySlug(
|
||||
`${body.slug_name}`,
|
||||
);
|
||||
if (doesExist) {
|
||||
logger.error("Category already exists");
|
||||
return res.status(400).json({
|
||||
@ -34,7 +39,9 @@ async function createCategory(req: Request, res: Response): Promise<Response> {
|
||||
error: "Failed to create category",
|
||||
});
|
||||
}
|
||||
logger.info(`Category created successfully ! (${body.slug_name})`);
|
||||
logger.info(
|
||||
`Category created successfully ! (${body.slug_name})`,
|
||||
);
|
||||
return res.status(201).json({
|
||||
message: "Category created successfully",
|
||||
});
|
||||
@ -48,7 +55,10 @@ async function createCategory(req: Request, res: Response): Promise<Response> {
|
||||
*
|
||||
* @return {Promise<Response>} - A promise that will be resolved with the result of the update operation.
|
||||
*/
|
||||
async function updateCategory(req: Request, res: Response): Promise<Response> {
|
||||
async function updateCategory(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const body: IDbCategory = req.body;
|
||||
const categoryId = req.params["categorySlug"];
|
||||
if (!categoryId) {
|
||||
@ -57,7 +67,9 @@ async function updateCategory(req: Request, res: Response): Promise<Response> {
|
||||
error: "Category slug is missing",
|
||||
});
|
||||
}
|
||||
const doesExist = await CategoryService.getById(`${categoryId}`);
|
||||
const doesExist = await CategoryService.getById(
|
||||
`${categoryId}`,
|
||||
);
|
||||
if (!doesExist || !doesExist.id) {
|
||||
logger.error("Category not found");
|
||||
return res.status(404).json({
|
||||
@ -88,7 +100,10 @@ async function updateCategory(req: Request, res: Response): Promise<Response> {
|
||||
* @param {Response} res - The response object to send the result.
|
||||
* @returns {Promise<Response>} A Promise that resolves to the response object.
|
||||
*/
|
||||
async function deleteCategory(req: Request, res: Response): Promise<Response> {
|
||||
async function deleteCategory(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const categorySlug = req.params["categorySlug"];
|
||||
if (!categorySlug) {
|
||||
logger.error("Category slug is missing");
|
||||
@ -96,21 +111,27 @@ async function deleteCategory(req: Request, res: Response): Promise<Response> {
|
||||
error: "Category slug is missing",
|
||||
});
|
||||
}
|
||||
const doesExist = await CategoryService.getBySlug(`${categorySlug}`);
|
||||
const doesExist = await CategoryService.getBySlug(
|
||||
`${categorySlug}`,
|
||||
);
|
||||
if (!doesExist || !doesExist.id) {
|
||||
logger.error("Category not found");
|
||||
return res.status(404).json({
|
||||
error: "Category not found",
|
||||
});
|
||||
}
|
||||
const deleteResult = await CategoryService.delete(`${doesExist.id}`);
|
||||
const deleteResult = await CategoryService.delete(
|
||||
`${doesExist.id}`,
|
||||
);
|
||||
if (!deleteResult) {
|
||||
logger.error("Failed to delete category");
|
||||
return res.status(500).json({
|
||||
error: "Failed to delete category",
|
||||
});
|
||||
}
|
||||
logger.info(`Category deleted successfully! (${categorySlug})`);
|
||||
logger.info(
|
||||
`Category deleted successfully! (${categorySlug})`,
|
||||
);
|
||||
return res.status(200).json({
|
||||
message: "Category deleted successfully",
|
||||
});
|
||||
@ -123,7 +144,10 @@ async function deleteCategory(req: Request, res: Response): Promise<Response> {
|
||||
* @param {Response} res - The response object.
|
||||
* @return {Promise<Response>} - A promise that resolves to the response object.
|
||||
*/
|
||||
async function getAllCategory(_req: Request, res: Response): Promise<Response> {
|
||||
async function getAllCategory(
|
||||
_req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const categories = await CategoryService.getAll();
|
||||
if (!categories) {
|
||||
logger.error("Failed to get categories");
|
||||
@ -162,14 +186,18 @@ async function getBySlugCategory(
|
||||
error: "Category slug is missing",
|
||||
});
|
||||
}
|
||||
const category = await CategoryService.getBySlug(`${categorySlug}`);
|
||||
const category = await CategoryService.getBySlug(
|
||||
`${categorySlug}`,
|
||||
);
|
||||
if (!category || !category.id) {
|
||||
logger.error("Category not found");
|
||||
return res.status(404).json({
|
||||
error: "Category not found",
|
||||
});
|
||||
}
|
||||
logger.info(`Category retrieved successfully! (${categorySlug})`);
|
||||
logger.info(
|
||||
`Category retrieved successfully! (${categorySlug})`,
|
||||
);
|
||||
return res.status(200).json({
|
||||
id: category.id,
|
||||
display_name: category.display_name,
|
||||
|
@ -9,9 +9,14 @@ const logger = new Logger({
|
||||
name: "ModelController",
|
||||
});
|
||||
|
||||
async function createModel(req: Request, res: Response): Promise<Response> {
|
||||
async function createModel(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const body: IDbModel = req.body;
|
||||
const doesExist = await CategoryService.getBySlug(`${body.slug_name}`);
|
||||
const doesExist = await CategoryService.getBySlug(
|
||||
`${body.slug_name}`,
|
||||
);
|
||||
if (doesExist) {
|
||||
logger.error("Category already exists");
|
||||
return res.status(400).json({
|
||||
@ -33,15 +38,22 @@ async function createModel(req: Request, res: Response): Promise<Response> {
|
||||
error: "Failed to create category",
|
||||
});
|
||||
}
|
||||
logger.info(`Category created successfully ! (${body.slug_name})`);
|
||||
logger.info(
|
||||
`Category created successfully ! (${body.slug_name})`,
|
||||
);
|
||||
return res.status(201).json({
|
||||
message: "Category created successfully",
|
||||
});
|
||||
}
|
||||
|
||||
async function updateModel(req: Request, res: Response): Promise<Response> {
|
||||
async function updateModel(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const body: IDbModel = req.body;
|
||||
const doesExist = await ModelService.getBySlug(`${body.slug_name}`);
|
||||
const doesExist = await ModelService.getBySlug(
|
||||
`${body.slug_name}`,
|
||||
);
|
||||
if (!doesExist) {
|
||||
logger.error("Model does not exist");
|
||||
return res.status(404).json({
|
||||
@ -64,7 +76,9 @@ async function updateModel(req: Request, res: Response): Promise<Response> {
|
||||
error: "Failed to update model",
|
||||
});
|
||||
}
|
||||
logger.info(`Model updated successfully! (${body.slug_name})`);
|
||||
logger.info(
|
||||
`Model updated successfully! (${body.slug_name})`,
|
||||
);
|
||||
return res.status(200).json({
|
||||
message: "Model updated successfully",
|
||||
});
|
||||
@ -85,7 +99,10 @@ async function getAllModel(res: Response): Promise<Response> {
|
||||
});
|
||||
}
|
||||
|
||||
async function getModelBySlug(req: Request, res: Response): Promise<Response> {
|
||||
async function getModelBySlug(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const slug = req.params["modelSlug"];
|
||||
if (!slug) {
|
||||
logger.error("Invalid slug");
|
||||
@ -105,7 +122,10 @@ async function getModelBySlug(req: Request, res: Response): Promise<Response> {
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteModel(req: Request, res: Response): Promise<Response> {
|
||||
async function deleteModel(
|
||||
req: Request,
|
||||
res: Response,
|
||||
): Promise<Response> {
|
||||
const modelSlug = req.params["modelSlug"];
|
||||
if (!modelSlug) {
|
||||
logger.error("Invalid model slug");
|
||||
@ -121,7 +141,9 @@ async function deleteModel(req: Request, res: Response): Promise<Response> {
|
||||
error: "Failed to delete model",
|
||||
});
|
||||
}
|
||||
logger.info(`Model deleted successfully! (SLUG: ${modelSlug})`);
|
||||
logger.info(
|
||||
`Model deleted successfully! (SLUG: ${modelSlug})`,
|
||||
);
|
||||
return res.status(200).json({
|
||||
message: "Model deleted successfully",
|
||||
});
|
||||
|
@ -10,16 +10,25 @@ AuthRouter.route("/register").post(AuthController.register);
|
||||
|
||||
// PATCH
|
||||
//TODO - To test
|
||||
AuthRouter.route("/me").patch(UserGuard, AuthController.editUser);
|
||||
AuthRouter.route("/me").patch(
|
||||
UserGuard,
|
||||
AuthController.editUser,
|
||||
);
|
||||
|
||||
// GET
|
||||
AuthRouter.route("/me").get(UserGuard, AuthController.getSelf);
|
||||
|
||||
// DELETE
|
||||
AuthRouter.route("/me").delete(UserGuard, AuthController.deleteSelf);
|
||||
AuthRouter.route("/me").delete(
|
||||
UserGuard,
|
||||
AuthController.deleteSelf,
|
||||
);
|
||||
|
||||
// GET
|
||||
AuthRouter.route("/all").get(AdminGuard, AuthController.getAllUsers);
|
||||
AuthRouter.route("/all").get(
|
||||
AdminGuard,
|
||||
AuthController.getAllUsers,
|
||||
);
|
||||
|
||||
// GET
|
||||
AuthRouter.route("/user/:targetId")
|
||||
|
@ -9,7 +9,10 @@ const CatalogRouter: Router = express.Router();
|
||||
|
||||
//-- MODELS >>
|
||||
|
||||
CatalogRouter.route("/model/new").get(AdminGuard, ModelController.create);
|
||||
CatalogRouter.route("/model/new").get(
|
||||
AdminGuard,
|
||||
ModelController.create,
|
||||
);
|
||||
|
||||
CatalogRouter.route("/model/all").get(ModelController.getAll);
|
||||
|
||||
@ -20,9 +23,14 @@ CatalogRouter.route("/model/:modelSlug")
|
||||
|
||||
//-- CATEGORY >>
|
||||
|
||||
CatalogRouter.route("/category/new").get(AdminGuard, CategoryController.create);
|
||||
CatalogRouter.route("/category/new").get(
|
||||
AdminGuard,
|
||||
CategoryController.create,
|
||||
);
|
||||
|
||||
CatalogRouter.route("/category/all").get(CategoryController.getAll);
|
||||
CatalogRouter.route("/category/all").get(
|
||||
CategoryController.getAll,
|
||||
);
|
||||
|
||||
CatalogRouter.route("/category/:categorySlug")
|
||||
.get(UserGuard, CategoryController.getBySlug)
|
||||
@ -31,7 +39,10 @@ CatalogRouter.route("/category/:categorySlug")
|
||||
|
||||
//-- BRAND >>
|
||||
|
||||
CatalogRouter.route("/brand/new").post(AdminGuard, BrandController.create);
|
||||
CatalogRouter.route("/brand/new").post(
|
||||
AdminGuard,
|
||||
BrandController.create,
|
||||
);
|
||||
CatalogRouter.route("/brand/all").get(BrandController.getAll);
|
||||
CatalogRouter.route("/brand/:brandSlug")
|
||||
.get(UserGuard, BrandController.getBySlug)
|
||||
|
@ -27,14 +27,19 @@ async function createBrand(data: IDbBrand): Promise<unknown> {
|
||||
};
|
||||
}
|
||||
const brandId = uuidv4();
|
||||
const createdBrand = await MysqlService.Brand.insert(DbHandler, {
|
||||
id: brandId,
|
||||
slug_name: `${data.slug_name}`,
|
||||
display_name: `${data.display_name}`,
|
||||
image_blob: data.image_blob,
|
||||
});
|
||||
const createdBrand = await MysqlService.Brand.insert(
|
||||
DbHandler,
|
||||
{
|
||||
id: brandId,
|
||||
slug_name: `${data.slug_name}`,
|
||||
display_name: `${data.display_name}`,
|
||||
image_blob: data.image_blob,
|
||||
},
|
||||
);
|
||||
if (createdBrand) {
|
||||
logger.info(`Brand created successfully (${data.slug_name})`);
|
||||
logger.info(
|
||||
`Brand created successfully (${data.slug_name})`,
|
||||
);
|
||||
return {
|
||||
success: true,
|
||||
brand: createdBrand,
|
||||
@ -66,14 +71,19 @@ async function updateBrand(data: IDbBrand): Promise<boolean> {
|
||||
logger.error(`Brand already exists (${data.slug_name})`);
|
||||
return false;
|
||||
}
|
||||
const updatedBrand = await MysqlService.Brand.update(DbHandler, {
|
||||
id: data.id,
|
||||
slug_name: `${data.slug_name}`,
|
||||
display_name: `${data.display_name}`,
|
||||
image_blob: data.image_blob,
|
||||
});
|
||||
const updatedBrand = await MysqlService.Brand.update(
|
||||
DbHandler,
|
||||
{
|
||||
id: data.id,
|
||||
slug_name: `${data.slug_name}`,
|
||||
display_name: `${data.display_name}`,
|
||||
image_blob: data.image_blob,
|
||||
},
|
||||
);
|
||||
if (updatedBrand) {
|
||||
logger.info(`Brand updated successfully (${data.slug_name})`);
|
||||
logger.info(
|
||||
`Brand updated successfully (${data.slug_name})`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
logger.error(`Failed to update brand (${data.slug_name})`);
|
||||
@ -90,7 +100,9 @@ async function getAllBrand(): Promise<Array<IDbBrand> | false> {
|
||||
logger.error("Failed to retrieve brands");
|
||||
return false;
|
||||
}
|
||||
logger.info(`Retrieved all brands successfully (${brands.length})`);
|
||||
logger.info(
|
||||
`Retrieved all brands successfully (${brands.length})`,
|
||||
);
|
||||
return brands;
|
||||
}
|
||||
|
||||
@ -100,17 +112,24 @@ async function getAllBrand(): Promise<Array<IDbBrand> | false> {
|
||||
* @param {string} brandSlug - The slug of the brand.
|
||||
* @returns {Promise<IDbBrand|false>} - A promise that resolves to the retrieved brand object or false if the brand is not found.
|
||||
*/
|
||||
async function getBySlugBrand(brandSlug: string): Promise<IDbBrand | false> {
|
||||
async function getBySlugBrand(
|
||||
brandSlug: string,
|
||||
): Promise<IDbBrand | false> {
|
||||
if (!brandSlug) {
|
||||
logger.error("Brand slug is missing");
|
||||
return false;
|
||||
}
|
||||
const brand = await MysqlService.Brand.getBySlug(DbHandler, brandSlug);
|
||||
const brand = await MysqlService.Brand.getBySlug(
|
||||
DbHandler,
|
||||
brandSlug,
|
||||
);
|
||||
if (!brand) {
|
||||
logger.error(`Brand not found (${brandSlug})`);
|
||||
return false;
|
||||
}
|
||||
logger.info(`Retrieved brand by slug successfully (${brandSlug})`);
|
||||
logger.info(
|
||||
`Retrieved brand by slug successfully (${brandSlug})`,
|
||||
);
|
||||
return brand;
|
||||
}
|
||||
|
||||
@ -121,7 +140,9 @@ async function getBySlugBrand(brandSlug: string): Promise<IDbBrand | false> {
|
||||
*
|
||||
* @returns {Promise<IDbBrand | false>} A promise that resolves to the retrieved brand object, or false if the brand is not found or the ID is invalid.
|
||||
*/
|
||||
async function getByIdBrand(brandId: string): Promise<IDbBrand | false> {
|
||||
async function getByIdBrand(
|
||||
brandId: string,
|
||||
): Promise<IDbBrand | false> {
|
||||
if (!brandId) {
|
||||
logger.error("Brand ID is missing");
|
||||
return false;
|
||||
@ -130,12 +151,17 @@ async function getByIdBrand(brandId: string): Promise<IDbBrand | false> {
|
||||
logger.error("Invalid brand ID");
|
||||
return false;
|
||||
}
|
||||
const brand = await MysqlService.Brand.getById(DbHandler, brandId);
|
||||
const brand = await MysqlService.Brand.getById(
|
||||
DbHandler,
|
||||
brandId,
|
||||
);
|
||||
if (!brand) {
|
||||
logger.error(`Brand not found (${brandId})`);
|
||||
return false;
|
||||
}
|
||||
logger.info(`Retrieved brand by ID successfully (${brandId})`);
|
||||
logger.info(
|
||||
`Retrieved brand by ID successfully (${brandId})`,
|
||||
);
|
||||
return brand;
|
||||
}
|
||||
|
||||
@ -159,7 +185,10 @@ async function deleteBrand(brandId: string): Promise<boolean> {
|
||||
return false;
|
||||
}
|
||||
//TODO verify if as models linked
|
||||
const deletedBrand = await MysqlService.Brand.delete(DbHandler, brandId);
|
||||
const deletedBrand = await MysqlService.Brand.delete(
|
||||
DbHandler,
|
||||
brandId,
|
||||
);
|
||||
if (!deletedBrand) {
|
||||
logger.error(`Failed to delete brand (${brandId})`);
|
||||
return false;
|
||||
|
@ -15,8 +15,12 @@ const logger = new Logger({
|
||||
* @returns {Promise<boolean>} A promise that resolves with the created category.
|
||||
* If an error occurs, the promise will reject with the error.
|
||||
*/
|
||||
async function createCategory(data: IDbCategory): Promise<boolean> {
|
||||
logger.info(`Creating a new category... (${data.display_name})`);
|
||||
async function createCategory(
|
||||
data: IDbCategory,
|
||||
): Promise<boolean> {
|
||||
logger.info(
|
||||
`Creating a new category... (${data.display_name})`,
|
||||
);
|
||||
try {
|
||||
await MysqlService.Category.insert(DbHandler, {
|
||||
id: uuidv4(),
|
||||
@ -65,7 +69,9 @@ async function updateCategory(data: IDbCategory) {
|
||||
*
|
||||
* @returns {Promise<Array<IDbCategory>> | null} Promise that resolves to an array of IDbCategory objects or null if an error occurred.
|
||||
*/
|
||||
async function getAll(): Promise<Promise<Array<IDbCategory>> | null> {
|
||||
async function getAll(): Promise<Promise<
|
||||
Array<IDbCategory>
|
||||
> | null> {
|
||||
try {
|
||||
logger.info("Getting all categories...");
|
||||
return await MysqlService.Category.getAll(DbHandler);
|
||||
@ -81,10 +87,15 @@ async function getAll(): Promise<Promise<Array<IDbCategory>> | null> {
|
||||
* @param {string} slug - The slug of the category
|
||||
* @return {Promise<IDbCategory|null>} - A promise that resolves to the category object or null if not found
|
||||
*/
|
||||
async function getBySlug(slug: string): Promise<IDbCategory | null> {
|
||||
async function getBySlug(
|
||||
slug: string,
|
||||
): Promise<IDbCategory | null> {
|
||||
try {
|
||||
logger.info(`Getting category by slug... (${slug})`);
|
||||
return await MysqlService.Category.getBySlug(DbHandler, slug);
|
||||
return await MysqlService.Category.getBySlug(
|
||||
DbHandler,
|
||||
slug,
|
||||
);
|
||||
} catch (error) {
|
||||
logger.error(`Error getting category by slug: ${error}`);
|
||||
return null;
|
||||
@ -97,7 +108,9 @@ async function getBySlug(slug: string): Promise<IDbCategory | null> {
|
||||
* @param {string} id - The id of the category to retrieve.
|
||||
* @returns {Promise<IDbCategory | null>} - A Promise that resolves with the retrieved category object or null if not found.
|
||||
*/
|
||||
async function getById(id: string): Promise<IDbCategory | null> {
|
||||
async function getById(
|
||||
id: string,
|
||||
): Promise<IDbCategory | null> {
|
||||
try {
|
||||
logger.info(`Getting category by id... (${id})`);
|
||||
return await MysqlService.Category.getById(DbHandler, id);
|
||||
|
@ -9,7 +9,10 @@ export async function getHashFromPassword(password: string) {
|
||||
}
|
||||
|
||||
//ToTest
|
||||
export async function comparePassword(password: string, hash: string) {
|
||||
export async function comparePassword(
|
||||
password: string,
|
||||
hash: string,
|
||||
) {
|
||||
return await Argon2id.verify(hash, password, {
|
||||
secret: Buffer.from(`${process.env["HASH_SECRET"]}`),
|
||||
algorithm: 2,
|
||||
|
@ -61,7 +61,9 @@ async function JwtSignService(
|
||||
.setIssuer(`${process.env["JWT_SECRET"]} - Mathis HERRIOT`)
|
||||
.setAudience(audience)
|
||||
.setExpirationTime(expTime)
|
||||
.sign(new TextEncoder().encode(`${process.env["JWT_SECRET"]}`));
|
||||
.sign(
|
||||
new TextEncoder().encode(`${process.env["JWT_SECRET"]}`),
|
||||
);
|
||||
}
|
||||
|
||||
const JwtService = {
|
||||
|
@ -72,13 +72,18 @@ async function updateModel(data: IDbModel): Promise<boolean> {
|
||||
* @param {string} modelSlug - The slug of the model to be deleted.
|
||||
* @return {Promise<boolean>} - A promise that resolves to true if the deletion is successful, else false.
|
||||
*/
|
||||
async function deleteModel(modelSlug: string): Promise<boolean> {
|
||||
async function deleteModel(
|
||||
modelSlug: string,
|
||||
): Promise<boolean> {
|
||||
if (!modelSlug) {
|
||||
logger.error("Model slug is missing");
|
||||
return false;
|
||||
}
|
||||
logger.info(`Deleting model with ID: ${modelSlug}`);
|
||||
const doesExist = await MysqlService.Model.getBySlug(DbHandler, modelSlug);
|
||||
const doesExist = await MysqlService.Model.getBySlug(
|
||||
DbHandler,
|
||||
modelSlug,
|
||||
);
|
||||
if (!doesExist || !doesExist.id) {
|
||||
logger.warn(`Model with slug ${modelSlug} not found`);
|
||||
return false;
|
||||
@ -99,10 +104,15 @@ async function deleteModel(modelSlug: string): Promise<boolean> {
|
||||
* @param {string} modelSlug - The slug of the model to be fetched.
|
||||
* @return {Promise<IDbModel | null>} - A promise that resolves to the model if found, else null.
|
||||
*/
|
||||
async function getBySlugModel(modelSlug: string): Promise<IDbModel | null> {
|
||||
async function getBySlugModel(
|
||||
modelSlug: string,
|
||||
): Promise<IDbModel | null> {
|
||||
logger.info(`Fetching model with slug: ${modelSlug}`);
|
||||
try {
|
||||
const model = await MysqlService.Model.getBySlug(DbHandler, modelSlug);
|
||||
const model = await MysqlService.Model.getBySlug(
|
||||
DbHandler,
|
||||
modelSlug,
|
||||
);
|
||||
if (!model) {
|
||||
logger.warn(`Model with slug ${modelSlug} not found`);
|
||||
return null;
|
||||
|
@ -5,7 +5,10 @@ import type { IDbModel } from "@interfaces/database/IDbModel";
|
||||
import type { IDbStatusResult } from "@interfaces/database/IDbStatusResult";
|
||||
import type { IDbUser } from "@interfaces/database/IDbUser";
|
||||
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";
|
||||
|
||||
const access: ConnectionOptions = {
|
||||
@ -32,7 +35,9 @@ class MysqlHandler {
|
||||
this.Logger.error(`Error connecting to MySQL: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
this.Logger.info(`Connected to MySQL database (${access.database})`);
|
||||
this.Logger.info(
|
||||
`Connected to MySQL database (${access.database})`,
|
||||
);
|
||||
});
|
||||
}
|
||||
closeConnection() {
|
||||
@ -60,7 +65,10 @@ class MysqlHandler {
|
||||
this.Connection.execute(
|
||||
queryString,
|
||||
values,
|
||||
(err: mysql.QueryError | null, results: mysql.QueryResult) => {
|
||||
(
|
||||
err: mysql.QueryError | null,
|
||||
results: mysql.QueryResult,
|
||||
) => {
|
||||
if (err) {
|
||||
this.Logger.error(`Error executing query: ${err}`);
|
||||
reject(err);
|
||||
@ -106,7 +114,10 @@ const MySqlService = {
|
||||
* @throws {Error} If an error occurs during the execution.
|
||||
* @throws {string} If the `id` field is undefined or invalid.
|
||||
*/
|
||||
insert(handler: MysqlHandler, data: IDbUser): Promise<IDbStatusResult> {
|
||||
insert(
|
||||
handler: MysqlHandler,
|
||||
data: IDbUser,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -127,7 +138,9 @@ const MySqlService = {
|
||||
];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
return resolve(
|
||||
result as unknown as IDbStatusResult,
|
||||
);
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
@ -135,7 +148,10 @@ const MySqlService = {
|
||||
});
|
||||
},
|
||||
|
||||
update(handler: MysqlHandler, data: IDbUser): Promise<IDbStatusResult> {
|
||||
update(
|
||||
handler: MysqlHandler,
|
||||
data: IDbUser,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -147,7 +163,11 @@ const MySqlService = {
|
||||
${data.lastname ? "`lastname` = ?," : null}
|
||||
${data.dob ? "`dob` = ?," : null}
|
||||
${data.email ? "`email` = ?," : null}
|
||||
${data.is_mail_verified ? "`is_mail_verified` = ?," : null}
|
||||
${
|
||||
data.is_mail_verified
|
||||
? "`is_mail_verified` = ?,"
|
||||
: null
|
||||
}
|
||||
${data.is_admin ? "`is_admin` = ?," : null}
|
||||
${data.gdpr ? "`gdpr` = ?," : null}
|
||||
${data.hash ? "`hash` = ?" : null}`;
|
||||
@ -166,7 +186,9 @@ const MySqlService = {
|
||||
|
||||
const _sql = `UPDATE "users" SET ${_template} WHERE 'id' = ?`;
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
return resolve(
|
||||
result as unknown as IDbStatusResult,
|
||||
);
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
@ -174,7 +196,10 @@ const MySqlService = {
|
||||
});
|
||||
},
|
||||
|
||||
getById(handler: MysqlHandler, userId: string): Promise<IDbUser> {
|
||||
getById(
|
||||
handler: MysqlHandler,
|
||||
userId: string,
|
||||
): Promise<IDbUser> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (userId.length !== 36) return reject("Id invalid");
|
||||
const _sql = "SELECT * FROM `users` WHERE `id` = ?";
|
||||
@ -217,7 +242,10 @@ const MySqlService = {
|
||||
* @return {Promise<IDbUser>} - A promise that resolves to the retrieved user object.
|
||||
* @throws {Error} - If an error occurs while retrieving the user.
|
||||
*/
|
||||
getByEmail(handler: MysqlHandler, email: string): Promise<IDbUser> {
|
||||
getByEmail(
|
||||
handler: MysqlHandler,
|
||||
email: string,
|
||||
): Promise<IDbUser> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!email) return reject("email is undefined");
|
||||
const _sql = "SELECT * FROM `users` WHERE `email` = ?";
|
||||
@ -245,7 +273,8 @@ const MySqlService = {
|
||||
userId: string,
|
||||
): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT `is_admin` FROM `users` WHERE `id` = ?";
|
||||
const _sql =
|
||||
"SELECT `is_admin` FROM `users` WHERE `id` = ?";
|
||||
const _values = [userId];
|
||||
try {
|
||||
const isAdmin = handler.execute(
|
||||
@ -268,16 +297,17 @@ const MySqlService = {
|
||||
* @param {string} userId - The ID of the user to delete.
|
||||
* @return {Promise<unknown>} - A Promise that resolves when the deletion is successful, or rejects with an error.
|
||||
*/
|
||||
delete(handler: MysqlHandler, userId: string): Promise<IDbStatusResult> {
|
||||
delete(
|
||||
handler: MysqlHandler,
|
||||
userId: string,
|
||||
): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!userId) return reject("Id is undefined");
|
||||
if (userId.length !== 36) return reject("Id invalid");
|
||||
const _sql = "DELETE FROM `users` WHERE `id` = ?";
|
||||
const _values = [userId];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
resolve(handler.execute(_sql, _values));
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -293,7 +323,10 @@ const MySqlService = {
|
||||
* @returns {Promise<IDbStatusResult>} - A Promise that resolves to the status result of the insert operation.
|
||||
* @throws {Error} - If an error occurs during the execution of the SQL query.
|
||||
*/
|
||||
insert(handler: MysqlHandler, data: IDbBrand): Promise<IDbStatusResult> {
|
||||
insert(
|
||||
handler: MysqlHandler,
|
||||
data: IDbBrand,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -307,7 +340,12 @@ const MySqlService = {
|
||||
data.image_blob,
|
||||
];
|
||||
try {
|
||||
resolve(handler.execute(_sql, _values) as unknown as IDbStatusResult);
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -322,7 +360,10 @@ const MySqlService = {
|
||||
* @returns {Promise<IDbStatusResult>} - A promise that resolves to the status result of the update operation.
|
||||
* @throws {Error} - If any error occurs during the process.
|
||||
*/
|
||||
update(handler: MysqlHandler, data: IDbBrand): Promise<IDbStatusResult> {
|
||||
update(
|
||||
handler: MysqlHandler,
|
||||
data: IDbBrand,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -340,9 +381,12 @@ const MySqlService = {
|
||||
data.id,
|
||||
];
|
||||
const _sql = `UPDATE "brands" SET ${_template} WHERE 'id' = ?`;
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
return resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -360,9 +404,9 @@ const MySqlService = {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT * FROM `brands`";
|
||||
try {
|
||||
handler.query(_sql).then((result) => {
|
||||
return resolve(result as unknown as Array<IDbBrand>);
|
||||
});
|
||||
resolve(
|
||||
handler.query(_sql) as unknown as Array<IDbBrand>,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -378,16 +422,22 @@ const MySqlService = {
|
||||
* @throws {Error} - If an error occurs during execution
|
||||
* @throws {string} - If brandId is undefined or invalid
|
||||
*/
|
||||
getById(handler: MysqlHandler, brandId: string): Promise<IDbBrand> {
|
||||
getById(
|
||||
handler: MysqlHandler,
|
||||
brandId: string,
|
||||
): Promise<IDbBrand> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!brandId) return reject("Id is undefined");
|
||||
if (brandId.length !== 36) return reject("Id invalid");
|
||||
const _sql = "SELECT * FROM `brands` WHERE `id` = ?";
|
||||
const _values = [brandId];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbBrand);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbBrand,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
//TODO Reject with null and logger error
|
||||
reject(err as Error);
|
||||
@ -402,15 +452,22 @@ const MySqlService = {
|
||||
* @param {string} brandSlug - The slug of the brand to retrieve.
|
||||
* @returns {Promise<IDbBrand>} - A promise that resolves with the brand object if found, or rejects with an error message.
|
||||
*/
|
||||
getBySlug(handler: MysqlHandler, brandSlug: string): Promise<IDbBrand> {
|
||||
getBySlug(
|
||||
handler: MysqlHandler,
|
||||
brandSlug: string,
|
||||
): Promise<IDbBrand> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!brandSlug) return reject("slug is undefined");
|
||||
const _sql = "SELECT * FROM `brands` WHERE `slug_name` = ?";
|
||||
const _sql =
|
||||
"SELECT * FROM `brands` WHERE `slug_name` = ?";
|
||||
const _values = [brandSlug];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbBrand);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbBrand,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -425,7 +482,10 @@ const MySqlService = {
|
||||
* @returns {Promise<IDbStatusResult>} A promise that resolves to the database status result.
|
||||
* @throws {Error} If an error occurs while deleting the brand.
|
||||
*/
|
||||
delete(handler: MysqlHandler, brandId: string): Promise<IDbStatusResult> {
|
||||
delete(
|
||||
handler: MysqlHandler,
|
||||
brandId: string,
|
||||
): Promise<IDbStatusResult> {
|
||||
//TODO check if has models linked before actions
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!brandId) return reject("Id is undefined");
|
||||
@ -433,9 +493,12 @@ const MySqlService = {
|
||||
const _sql = "DELETE FROM `brands` WHERE `id` = ?";
|
||||
const _values = [brandId];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -456,9 +519,9 @@ const MySqlService = {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT * FROM `models`";
|
||||
try {
|
||||
handler.query(_sql).then((result) => {
|
||||
return resolve(result as unknown as Array<IDbModel>);
|
||||
});
|
||||
resolve(
|
||||
handler.query(_sql) as unknown as Array<IDbModel>,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -473,14 +536,21 @@ const MySqlService = {
|
||||
* @return {Promise<IDbModel>} A promise that resolves with the retrieved model.
|
||||
* @throws {Error} If there was an error executing the query.
|
||||
*/
|
||||
getBySlug(handler: MysqlHandler, modelSlug: string): Promise<IDbModel> {
|
||||
getBySlug(
|
||||
handler: MysqlHandler,
|
||||
modelSlug: string,
|
||||
): Promise<IDbModel> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT * FROM `models` WHERE `slug_name` = ?";
|
||||
const _sql =
|
||||
"SELECT * FROM `models` WHERE `slug_name` = ?";
|
||||
const _values = [modelSlug];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbModel);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbModel,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -494,12 +564,20 @@ const MySqlService = {
|
||||
* @param {string} modelId - The ID of the model to retrieve.
|
||||
* @return {Promise<IDbModel>} - A promise that resolves with the retrieved model, or rejects with an error.
|
||||
*/
|
||||
getById(handler: MysqlHandler, modelId: string): Promise<IDbModel> {
|
||||
getById(
|
||||
handler: MysqlHandler,
|
||||
modelId: string,
|
||||
): Promise<IDbModel> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT * FROM `models` WHERE `id` = ?";
|
||||
const _values = [modelId];
|
||||
try {
|
||||
resolve(handler.execute(_sql, _values) as unknown as IDbModel);
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbModel,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -514,7 +592,10 @@ const MySqlService = {
|
||||
* @throws {string} - Throws an error message if the id is undefined or invalid.
|
||||
* @returns {Promise<IDbStatusResult>} - A promise that resolves to the status result of the insert operation.
|
||||
*/
|
||||
insert(handler: MysqlHandler, data: IDbModel): Promise<IDbStatusResult> {
|
||||
insert(
|
||||
handler: MysqlHandler,
|
||||
data: IDbModel,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -532,9 +613,12 @@ const MySqlService = {
|
||||
data.id,
|
||||
];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -551,7 +635,10 @@ const MySqlService = {
|
||||
* @return {Promise<IDbStatusResult>} - A promise that resolves to the status result of the update operation.
|
||||
* @throws {Error} - If an error occurs during the update process.
|
||||
*/
|
||||
update(handler: MysqlHandler, data: IDbModel): Promise<IDbStatusResult> {
|
||||
update(
|
||||
handler: MysqlHandler,
|
||||
data: IDbModel,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -577,9 +664,12 @@ const MySqlService = {
|
||||
data.id,
|
||||
];
|
||||
const _sql = `UPDATE "models" SET ${_template} WHERE 'id' = ?`;
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
return resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -594,7 +684,10 @@ const MySqlService = {
|
||||
* @returns {Promise<IDbStatusResult>} A promise that resolves to the result of the delete operation.
|
||||
* @throws {Error} If an error occurs during the delete operation.
|
||||
*/
|
||||
delete(handler: MysqlHandler, modelId: string): Promise<IDbStatusResult> {
|
||||
delete(
|
||||
handler: MysqlHandler,
|
||||
modelId: string,
|
||||
): Promise<IDbStatusResult> {
|
||||
//TODO check if has models linked before actions
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!modelId) return reject("Id is undefined");
|
||||
@ -602,9 +695,12 @@ const MySqlService = {
|
||||
const _sql = "DELETE FROM `models` WHERE `id` = ?";
|
||||
const _values = [modelId];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -619,7 +715,10 @@ const MySqlService = {
|
||||
* @throws Throws an error if the provided `data` object does not contain the `id` property or if the `id` is not a valid UUID.
|
||||
* @returns {Promise<IDbStatusResult>} A promise that resolves to the result of the insert operation.
|
||||
*/
|
||||
insert(handler: MysqlHandler, data: IDbVehicle): Promise<IDbStatusResult> {
|
||||
insert(
|
||||
handler: MysqlHandler,
|
||||
data: IDbVehicle,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -634,9 +733,12 @@ const MySqlService = {
|
||||
data.id,
|
||||
];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -651,7 +753,10 @@ const MySqlService = {
|
||||
* @throws {string} Throws an error if the id is undefined or invalid.
|
||||
* @returns {Promise<IDbStatusResult>} Returns a Promise that resolves to the status result of the update operation.
|
||||
*/
|
||||
update(handler: MysqlHandler, data: IDbVehicle): Promise<IDbStatusResult> {
|
||||
update(
|
||||
handler: MysqlHandler,
|
||||
data: IDbVehicle,
|
||||
): Promise<IDbStatusResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -661,7 +766,9 @@ const MySqlService = {
|
||||
${data.model_id ? "`model_id` = ?," : null}
|
||||
${data.plate_number ? "`plate_number` = ?," : null}
|
||||
${data.odometer ? "`odometer` = ?," : null}
|
||||
${data.health_state ? "`health_state` = ?," : null}`;
|
||||
${
|
||||
data.health_state ? "`health_state` = ?," : null
|
||||
}`;
|
||||
|
||||
const _values = [
|
||||
data.model_id,
|
||||
@ -671,9 +778,12 @@ const MySqlService = {
|
||||
data.id,
|
||||
];
|
||||
const _sql = `UPDATE "vehicles" SET ${_template} WHERE 'id' = ?`;
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
return resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbStatusResult,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -688,16 +798,23 @@ const MySqlService = {
|
||||
* @returns {Promise<IDbVehicle>} - A promise that resolves to the retrieved vehicle.
|
||||
* @throws {Error} - If an error occurs while retrieving the vehicle.
|
||||
*/
|
||||
getById(handler: MysqlHandler, vehicleId: string): Promise<IDbVehicle> {
|
||||
getById(
|
||||
handler: MysqlHandler,
|
||||
vehicleId: string,
|
||||
): Promise<IDbVehicle> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!vehicleId) return reject("Id is undefined");
|
||||
if (vehicleId.length !== 36) return reject("Id invalid");
|
||||
if (vehicleId.length !== 36)
|
||||
return reject("Id invalid");
|
||||
const _sql = "SELECT * FROM `vehicles` WHERE `id` = ?";
|
||||
const _values = [vehicleId];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbVehicle);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbVehicle,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -715,9 +832,9 @@ const MySqlService = {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT * FROM `models`";
|
||||
try {
|
||||
handler.query(_sql).then((result) => {
|
||||
return resolve(result as unknown as Array<IDbVehicle>);
|
||||
});
|
||||
resolve(
|
||||
handler.query(_sql) as unknown as Array<IDbVehicle>,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -731,13 +848,16 @@ const MySqlService = {
|
||||
* @returns {Promise<Array<IDbVehicle>>} A promise that resolves to an array of available vehicles.
|
||||
* @throws {Error} If an error occurs while executing the query.
|
||||
*/
|
||||
getAvailable(handler: MysqlHandler): Promise<Array<IDbVehicle>> {
|
||||
getAvailable(
|
||||
handler: MysqlHandler,
|
||||
): Promise<Array<IDbVehicle>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT * FROM `vehicles` WERE `isAvailable` = 1";
|
||||
const _sql =
|
||||
"SELECT * FROM `vehicles` WERE `isAvailable` = 1";
|
||||
try {
|
||||
handler.query(_sql).then((result) => {
|
||||
return resolve(result as unknown as Array<IDbVehicle>);
|
||||
});
|
||||
resolve(
|
||||
handler.query(_sql) as unknown as Array<IDbVehicle>,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -746,25 +866,29 @@ const MySqlService = {
|
||||
},
|
||||
Category: {
|
||||
/**
|
||||
* Insert a category into the database.
|
||||
* Inserts a category into the database.
|
||||
*
|
||||
* @param {MysqlHandler} handler - The MySQL handler instance.
|
||||
* @param {IDbCategory} data - The category data to insert.
|
||||
* @returns {Promise<IDbStatusResult>} A promise that resolves to the status result of the insertion.
|
||||
* @throws {Error} If an error occurs during the execution of the insertion.
|
||||
* @param {MysqlHandler} handler - The MySQL handler object.
|
||||
* @param {IDbCategory} data - The category data to be inserted.
|
||||
* @return {Promise<unknown>} - A promise that resolves if the insertion is successful, and rejects with an error if it fails.
|
||||
*/
|
||||
insert(handler: MysqlHandler, data: IDbCategory): Promise<IDbStatusResult> {
|
||||
insert(
|
||||
handler: MysqlHandler,
|
||||
data: IDbCategory,
|
||||
): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
|
||||
const _sql =
|
||||
"INSERT INTO `categories`(`id`,`slug_name`, `display_name`) VALUES (?, ?, ?)";
|
||||
const _values = [data.id, data.slug_name, data.display_name];
|
||||
const _values = [
|
||||
data.id,
|
||||
data.slug_name,
|
||||
data.display_name,
|
||||
];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
resolve(handler.execute(_sql, _values));
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -774,11 +898,15 @@ const MySqlService = {
|
||||
/**
|
||||
* Updates a category in the database.
|
||||
*
|
||||
* @param {MysqlHandler} handler - The MySQL handler for executing database queries.
|
||||
* @param {IDbCategory} data - The category data to be updated.
|
||||
* @returns {Promise<IDbStatusResult>} - A promise that resolves to the status result of the update operation.
|
||||
* @param {MysqlHandler} handler - The MySQL handler instance.
|
||||
* @param {IDbCategory} data - The category data to update.
|
||||
* @returns {Promise<number>} - A promise that resolves with the number of affected rows in the database.
|
||||
* @throws {Error} - If an error occurs during execution.
|
||||
*/
|
||||
update(handler: MysqlHandler, data: IDbCategory): Promise<IDbStatusResult> {
|
||||
update(
|
||||
handler: MysqlHandler,
|
||||
data: IDbCategory,
|
||||
): Promise<unknown> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!data.id) return reject("Id is undefined");
|
||||
if (data.id.length !== 36) return reject("Id invalid");
|
||||
@ -786,13 +914,19 @@ const MySqlService = {
|
||||
try {
|
||||
const _template = `
|
||||
${data.slug_name ? "`slug_name` = ?," : null}
|
||||
${data.display_name ? "`display_name` = ?," : null}`;
|
||||
${
|
||||
data.display_name ? "`display_name` = ?," : null
|
||||
}`;
|
||||
|
||||
const _values = [data.slug_name, data.display_name, data.id];
|
||||
const _values = [
|
||||
data.slug_name,
|
||||
data.display_name,
|
||||
data.id,
|
||||
];
|
||||
const _sql = `UPDATE "categories" SET ${_template} WHERE 'id' = ?`;
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
return resolve(
|
||||
handler.execute(_sql, _values) as unknown as number,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -803,16 +937,19 @@ const MySqlService = {
|
||||
*
|
||||
* @param {MysqlHandler} handler - The MySQL handler used for executing the query.
|
||||
*
|
||||
* @return {Promise<Array<IDbCategory>>}
|
||||
* - A promise that resolves with an array of category objects from the database.
|
||||
* - The category objects are of type IDbCategory.
|
||||
* - If an error occurs, the promise will be rejected with an Error object.
|
||||
* @return {Promise<Array<IDbCategory>>} - A promise that resolves with an array of category objects from the database.
|
||||
* - The category objects are of type IDbCategory.
|
||||
* - If an error occurs, the promise will be rejected with an Error object.
|
||||
*/
|
||||
getAll(handler: MysqlHandler): Promise<Array<IDbCategory>> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const _sql = "SELECT * FROM `categories`";
|
||||
try {
|
||||
resolve(handler.query(_sql) as unknown as Array<IDbCategory>);
|
||||
resolve(
|
||||
handler.query(
|
||||
_sql,
|
||||
) as unknown as Array<IDbCategory>,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -832,12 +969,16 @@ const MySqlService = {
|
||||
): Promise<IDbCategory> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!categorySlug) return reject("slug is undefined");
|
||||
const _sql = "SELECT * FROM `categories` WHERE `slug_name` = ?";
|
||||
const _sql =
|
||||
"SELECT * FROM `categories` WHERE `slug_name` = ?";
|
||||
const _values = [categorySlug];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbCategory);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbCategory,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
@ -851,41 +992,38 @@ const MySqlService = {
|
||||
* @returns {Promise<IDbCategory>} - A Promise that resolves with the category object.
|
||||
* @throws {Error} - If an error occurs during execution.
|
||||
*/
|
||||
getById(handler: MysqlHandler, categoryId: string): Promise<IDbCategory> {
|
||||
getById(
|
||||
handler: MysqlHandler,
|
||||
categoryId: string,
|
||||
): Promise<IDbCategory> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!categoryId) return reject("slug is undefined");
|
||||
if (categoryId.length !== 36) return reject("Id invalid");
|
||||
const _sql = "SELECT * FROM `categories` WHERE `id` = ?";
|
||||
if (categoryId.length !== 36)
|
||||
return reject("Id invalid");
|
||||
const _sql =
|
||||
"SELECT * FROM `categories` WHERE `id` = ?";
|
||||
const _values = [categoryId];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbCategory);
|
||||
});
|
||||
resolve(
|
||||
handler.execute(
|
||||
_sql,
|
||||
_values,
|
||||
) as unknown as IDbCategory,
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Deletes a category from the database based on the given categoryId.
|
||||
*
|
||||
* @param {MysqlHandler} handler - The MysqlHandler object for executing database queries.
|
||||
* @param {string} categoryId - The ID of the category to be deleted.
|
||||
*
|
||||
* @returns {Promise<IDbStatusResult>} - A promise that resolves to the database status result after deletion.
|
||||
* @throws {Error} - If an error occurs while executing the deletion query.
|
||||
*/
|
||||
delete(handler: MysqlHandler, categoryId: string) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!categoryId) return reject("Id is undefined");
|
||||
if (categoryId.length !== 36) return reject("Id invalid");
|
||||
if (categoryId.length !== 36)
|
||||
return reject("Id invalid");
|
||||
const _sql = "DELETE FROM `categories` WHERE `id` = ?";
|
||||
const _values = [categoryId];
|
||||
try {
|
||||
handler.execute(_sql, _values).then((result) => {
|
||||
return resolve(result as unknown as IDbStatusResult);
|
||||
});
|
||||
resolve(handler.execute(_sql, _values));
|
||||
} catch (err: unknown) {
|
||||
reject(err as Error);
|
||||
}
|
||||
|
@ -18,8 +18,13 @@ const DbHandler = new MySqlService.Handler("UserService");
|
||||
* @param {string} username - The username of the user to retrieve.
|
||||
* @returns {Promise<Object | null>} - The user object if found, or null if not found.
|
||||
*/
|
||||
async function getUserFromUsername(username: string): Promise<object | null> {
|
||||
const dbUser = await MySqlService.User.getByUsername(DbHandler, username);
|
||||
async function getUserFromUsername(
|
||||
username: string,
|
||||
): Promise<object | null> {
|
||||
const dbUser = await MySqlService.User.getByUsername(
|
||||
DbHandler,
|
||||
username,
|
||||
);
|
||||
if (dbUser === undefined) return null;
|
||||
return dbUser;
|
||||
}
|
||||
@ -32,16 +37,22 @@ async function getUserFromIdService(id: string | undefined) {
|
||||
|
||||
async function register(ReqData: IReqRegister) {
|
||||
if (ReqData.password.length < 6) {
|
||||
logger.info(`REGISTER :> Invalid password (${ReqData.username})`);
|
||||
logger.info(
|
||||
`REGISTER :> Invalid password (${ReqData.username})`,
|
||||
);
|
||||
return {
|
||||
error: "invalidPassword",
|
||||
};
|
||||
}
|
||||
const passwordHash = await CredentialService.hash(ReqData.password);
|
||||
const passwordHash = await CredentialService.hash(
|
||||
ReqData.password,
|
||||
);
|
||||
|
||||
// Does the new user has accepted GDPR ?
|
||||
if (ReqData.gdpr !== true) {
|
||||
logger.info(`REGISTER :> GDPR not validated (${ReqData.username})`);
|
||||
logger.info(
|
||||
`REGISTER :> GDPR not validated (${ReqData.username})`,
|
||||
);
|
||||
return {
|
||||
error: "gdprNotApproved",
|
||||
};
|
||||
@ -49,7 +60,9 @@ async function register(ReqData: IReqRegister) {
|
||||
|
||||
// Check if exist and return
|
||||
|
||||
const dbUserIfExist = await getUserFromUsername(ReqData.username);
|
||||
const dbUserIfExist = await getUserFromUsername(
|
||||
ReqData.username,
|
||||
);
|
||||
if (dbUserIfExist) {
|
||||
logger.info(
|
||||
`REGISTER :> User exist (${dbUserIfExist.username})\n ID:${dbUserIfExist.id}`,
|
||||
@ -97,7 +110,9 @@ async function register(ReqData: IReqRegister) {
|
||||
};
|
||||
logger.info(userData);
|
||||
await Db.collection("users").insertOne(NewUser);
|
||||
logger.info(`REGISTER :> Inserted new user (${NewUser.username})`);
|
||||
logger.info(
|
||||
`REGISTER :> Inserted new user (${NewUser.username})`,
|
||||
);
|
||||
return userData;
|
||||
}
|
||||
|
||||
@ -108,14 +123,18 @@ async function login(ReqData: IReqLogin) {
|
||||
ReqData.username,
|
||||
);
|
||||
if (!dbUser) {
|
||||
console.log(`LoginService :> User does not exist (${ReqData.username})`);
|
||||
console.log(
|
||||
`LoginService :> User does not exist (${ReqData.username})`,
|
||||
);
|
||||
return {
|
||||
error: "userNotFound",
|
||||
};
|
||||
}
|
||||
if (ReqData.password.length < 6) {
|
||||
console.log("X");
|
||||
console.log(`LoginService :> Invalid password (${ReqData.username})`);
|
||||
console.log(
|
||||
`LoginService :> Invalid password (${ReqData.username})`,
|
||||
);
|
||||
return {
|
||||
error: "invalidPassword",
|
||||
};
|
||||
@ -126,7 +145,9 @@ async function login(ReqData: IReqLogin) {
|
||||
);
|
||||
if (!isPasswordValid) {
|
||||
console.log(isPasswordValid);
|
||||
console.log(`LoginService :> Invalid password (${ReqData.username})`);
|
||||
console.log(
|
||||
`LoginService :> Invalid password (${ReqData.username})`,
|
||||
);
|
||||
return {
|
||||
error: "invalidPassword",
|
||||
};
|
||||
@ -192,12 +213,16 @@ async function getAllUsersService() {
|
||||
*/
|
||||
async function editUserService(targetId, sanitizedData) {
|
||||
if (sanitizedData.password) {
|
||||
const passwordHash = await getHashFromPassword(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(
|
||||
const updatedUserResult = await Db.collection(
|
||||
"users",
|
||||
).updateOne(
|
||||
{
|
||||
id: targetId,
|
||||
},
|
||||
|
@ -13,9 +13,14 @@ const UNAUTHORIZED = 401;
|
||||
const FORBIDDEN = 403;
|
||||
const UNAUTH_MESSAGE = "Missing Authorization Header";
|
||||
const INVALID_TOKEN_MESSAGE = "Invalid or expired token.";
|
||||
const PERMISSON_NOT_VALID = "You are missing the required permission.";
|
||||
const PERMISSON_NOT_VALID =
|
||||
"You are missing the required permission.";
|
||||
|
||||
async function AdminGuard(req: Request, res: Response, next: NextFunction) {
|
||||
async function AdminGuard(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader) {
|
||||
logger.warn(`Invalid header (${req.ip})`);
|
||||
@ -35,10 +40,11 @@ async function AdminGuard(req: Request, res: Response, next: NextFunction) {
|
||||
|
||||
if (token) {
|
||||
// @ts-ignore
|
||||
const isSourceAdmin = await MysqlService.User.getAdminStateForId(
|
||||
DbHandler,
|
||||
token.sub,
|
||||
);
|
||||
const isSourceAdmin =
|
||||
await MysqlService.User.getAdminStateForId(
|
||||
DbHandler,
|
||||
token.sub,
|
||||
);
|
||||
if (isSourceAdmin === true) next();
|
||||
return res.status(FORBIDDEN).json({
|
||||
message: PERMISSON_NOT_VALID,
|
||||
|
@ -14,7 +14,11 @@ const UNAUTH_MESSAGE = "Missing Authorization Header";
|
||||
const INVALID_TOKEN_MESSAGE = "Invalid or expired token.";
|
||||
const USER_NOT_EXIST = "You dont exist anymore";
|
||||
|
||||
async function UserGuard(req: Request, res: Response, next: NextFunction) {
|
||||
async function UserGuard(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
) {
|
||||
const authHeader = req.headers.authorization;
|
||||
if (!authHeader) {
|
||||
return res.status(UNAUTHORIZED).json({
|
||||
@ -40,7 +44,10 @@ async function UserGuard(req: Request, res: Response, next: NextFunction) {
|
||||
message: USER_NOT_EXIST,
|
||||
});
|
||||
}
|
||||
const user = await MySqlService.User.getById(DbHandler, userId);
|
||||
const user = await MySqlService.User.getById(
|
||||
DbHandler,
|
||||
userId,
|
||||
);
|
||||
if (user) {
|
||||
logger.info(`An user do a request. (${user?.username})`);
|
||||
next();
|
||||
|
Loading…
x
Reference in New Issue
Block a user