Skip to content

Commit

Permalink
Update import paths.
Browse files Browse the repository at this point in the history
  • Loading branch information
muttaqin1 committed Jun 25, 2023
1 parent 7609c6b commit 2c4d94c
Show file tree
Hide file tree
Showing 28 changed files with 402 additions and 395 deletions.
47 changes: 23 additions & 24 deletions backend-app/app.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
const globalErrHandler = require("./middlewares/globalErrorHandler");
const AppError = require("./utils/appError");
const express = require("express");
const limiter = require("./middlewares/rate_limit");
const compression = require("compression");
const helmet = require("helmet");
const mongoSanitize = require("express-mongo-sanitize");
const xss = require("xss-clean");
const hpp = require("hpp");
const cors = require("cors");
const morgan = require("./middlewares/morgan");
const swaggerDocs = require("./utils/swagger");
const { CURRENT_ENV, API_VERSION } = require("./config/appConfig");
const globalErrHandler = require('./middlewares/global_error_handler');
const AppError = require('./utils/app_error');
const express = require('express');
const limiter = require('./middlewares/rate_limit');
const compression = require('compression');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const hpp = require('hpp');
const cors = require('cors');
const morgan = require('./middlewares/morgan');
const swaggerDocs = require('./utils/swagger');
const { CURRENT_ENV, API_VERSION } = require('./config/app_config');

const app = express();

Expand All @@ -34,14 +34,14 @@ app.use(helmet());
// Body parser, reading data from body into req.body
app.use(
express.json({
limit: "15kb",
limit: '15kb',
})
);

// Data sanitization against Nosql query injection
app.use(
mongoSanitize({
replaceWith: "_",
replaceWith: '_',
})
);

Expand All @@ -54,26 +54,25 @@ app.use(hpp());
// Compress all responses
app.use(compression());

if (CURRENT_ENV.toLocaleLowerCase() === "production") {
if (CURRENT_ENV.toLocaleLowerCase() === 'production') {
//Limiting request form same IP
app.use("/api", limiter);
app.use('/api', limiter);
}

// routes
app.use(`/api/${API_VERSION}`, require("./routes/index"));
app.use(`/api/${API_VERSION}`, require('./routes/index'));


app.get("/", (req, res) => {
app.get('/', (req, res) => {
res.status(200).json({
status: "success",
message: "Welcome to the backend app",
status: 'success',
message: 'Welcome to the backend app',
env: CURRENT_ENV,
});
});

// handle undefined Routes
app.use("*", (req, res, next) => {
const err = new AppError(404, "fail", "Route Not Found", req.path);
app.use('*', (req, res, next) => {
const err = new AppError(404, 'fail', 'Route Not Found', req.path);
next(err, req, res, next);
});

Expand Down
4 changes: 2 additions & 2 deletions backend-app/config/logger_config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { addColors, format } = require('winston');
const { logFilePath } = require('./appConfig');
const { logFilePath } = require('./app_config');
// Define the current environment
const currentEnv = process.env.NODE_ENV || 'development';

Expand Down Expand Up @@ -63,4 +63,4 @@ const fileOptions = {
module.exports = {
fileOptions,
consoleOptions,
}
};
2 changes: 1 addition & 1 deletion backend-app/constants/default_roles.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const Actions = require('./Actions');
const Actions = require('./actions');
const Roles = {
SUPER_ADMIN: {
type: 'SUPER_ADMIN',
Expand Down
14 changes: 7 additions & 7 deletions backend-app/controllers/admin_controller.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const userModel = require('../models/userModel');
const Actions = require('../constants/Actions');
const validateActions = require('../utils/authorization/validateActions');
const Role = require('../utils/authorization/role/Role');
const AppError = require('../utils/appError');
const userModel = require('../models/user_model');
const Actions = require('../constants/actions');
const validateActions = require('../utils/authorization/validate_actions');
const Role = require('../utils/authorization/role/role');
const AppError = require('../utils/app_error');
const role = new Role();

exports.addAdmin = async (req, res, next) => {
Expand Down Expand Up @@ -133,8 +133,8 @@ exports.authorizeOrRestrict = async (req, res, next) => {
const user = await userModel.findById(userId);
if (!user) throw new AppError(404, 'fail', 'No user found with this id');
// if the user is a super admin, he can't be restricted
if (user.roles?.includes("SUPER_ADMIN"))
throw new AppError(400, "fail", "User is a super admin");
if (user.roles?.includes('SUPER_ADMIN'))
throw new AppError(400, 'fail', 'User is a super admin');
const existingAuthorities = user.authorities;
const existingRestrictions = user.restrictions;
user.authorities = Array.from(
Expand Down
10 changes: 5 additions & 5 deletions backend-app/controllers/auth_controller.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const { promisify } = require('util');
const jwt = require('jsonwebtoken');
const User = require('../models/userModel');
const AppError = require('../utils/appError');
const Role = require('../utils/authorization/role/Role');
const { JWT_SECRET , JWT_EXPIRES_IN } = require("../config/appConfig");
const User = require('../models/user_model');
const AppError = require('../utils/app_error');
const Role = require('../utils/authorization/role/role');
const { JWT_SECRET, JWT_EXPIRES_IN } = require('../config/app_config');
const role = new Role();

const createToken = (id) => {
Expand Down Expand Up @@ -178,7 +178,7 @@ exports.restrictTo = (...roles) => {
});
if (!roleExist) {
return next(
new AppError(403, "fail", "You are not allowed to do this action"),
new AppError(403, 'fail', 'You are not allowed to do this action'),
req,
res,
next
Expand Down
183 changes: 95 additions & 88 deletions backend-app/controllers/base_controller.js
Original file line number Diff line number Diff line change
@@ -1,124 +1,131 @@
const AppError = require("../utils/appError");
const APIFeatures = require("../utils/apiFeatures");
const AppError = require('../utils/app_error');
const APIFeatures = require('../utils/api_features');

/**
* Delete a document by ID
* @param {Model} Model - The mongoose model
* @returns {Function} - Express middleware function
*/
exports.deleteOne = Model => async (req, res, next) => {
try {
const doc = await Model.findByIdAndDelete(req.params.id);

if (!doc) {
return next(new AppError(404, "fail", "No document found with that id"), req, res, next);
}

res.status(204).json({
status: "success",
data: null
});
} catch (error) {
next(error);
exports.deleteOne = (Model) => async (req, res, next) => {
try {
const doc = await Model.findByIdAndDelete(req.params.id);

if (!doc) {
return next(
new AppError(404, 'fail', 'No document found with that id'),
req,
res,
next
);
}
};

res.status(204).json({
status: 'success',
data: null,
});
} catch (error) {
next(error);
}
};

/**
* Update a document by ID
* @param {Model} Model - The mongoose model
* @returns {Function} - Express middleware function
*/
exports.updateOne = Model => async (req, res, next) => {
try {
const doc = await Model.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true
});

if (!doc) {
return next(new AppError(404, "fail", "No document found with that id"), req, res, next);
}

res.status(200).json({
status: "success",
data: {
doc
}
});

} catch (error) {
next(error);
exports.updateOne = (Model) => async (req, res, next) => {
try {
const doc = await Model.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
});

if (!doc) {
return next(
new AppError(404, 'fail', 'No document found with that id'),
req,
res,
next
);
}
};

res.status(200).json({
status: 'success',
data: {
doc,
},
});
} catch (error) {
next(error);
}
};

/**
* Create a new document
* @param {Model} Model - The mongoose model
* @returns {Function} - Express middleware function
*/
exports.createOne = Model => async (req, res, next) => {
try {
const doc = await Model.create(req.body);

res.status(201).json({
status: "success",
data: {
doc
}
});

} catch (error) {
next(error);
}
exports.createOne = (Model) => async (req, res, next) => {
try {
const doc = await Model.create(req.body);

res.status(201).json({
status: 'success',
data: {
doc,
},
});
} catch (error) {
next(error);
}
};
/**
* Get a document by ID
* @param {Model} Model - The mongoose model
* @returns {Function} - Express middleware function
*/
exports.getOne = Model => async (req, res, next) => {
try {
const doc = await Model.findById(req.params.id);

if (!doc) {
return next(new AppError(404, "fail", "No document found with that id"), req, res, next);
}

res.status(200).json({
status: "success",
data: {
doc
}
});
} catch (error) {
next(error);
exports.getOne = (Model) => async (req, res, next) => {
try {
const doc = await Model.findById(req.params.id);

if (!doc) {
return next(
new AppError(404, 'fail', 'No document found with that id'),
req,
res,
next
);
}

res.status(200).json({
status: 'success',
data: {
doc,
},
});
} catch (error) {
next(error);
}
};
/**
* Get all documents
* @param {Model} Model - The mongoose model
* @returns {Function} - Express middleware function
*/
exports.getAll = Model => async (req, res, next) => {
try {
const features = new APIFeatures(Model.find(), req.query)
.sort()
.paginate();

const doc = await features.query;

res.status(200).json({
status: "success",
results: doc.length,
data: {
data: doc
}
});

} catch (error) {
next(error);
}

exports.getAll = (Model) => async (req, res, next) => {
try {
const features = new APIFeatures(Model.find(), req.query).sort().paginate();

const doc = await features.query;

res.status(200).json({
status: 'success',
results: doc.length,
data: {
data: doc,
},
});
} catch (error) {
next(error);
}
};
Loading

0 comments on commit 2c4d94c

Please sign in to comment.