Skip to content

Commit

Permalink
fix - rate limiter & duplicated methods & env variables (#74)
Browse files Browse the repository at this point in the history
* Update access to env

* configure rate limiter to ignore the SSE requests

* verify user authorities and restrictions

* update access to env variables
  • Loading branch information
bellaabdelouahab committed Jul 26, 2023
1 parent c1894bc commit fbb1537
Show file tree
Hide file tree
Showing 13 changed files with 61 additions and 30 deletions.
13 changes: 9 additions & 4 deletions backend-app/.env.example
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
NODE_ENV = "development"
API_VERSION = "v1"
MONGO_URI = "mongodb+srv://username:password@cluster0.cmlpjag.mongodb.net/?retryWrites=true&w=majority"
MONGO_URI = "mongodb+srv://swo:zrcoCze9UKFTWzYx@nfs315.tayahgd.mongodb.net/S-W-O"
PORT = 5000
ADMIN_EMAIL = "admin@swf.com"
ADMIN_PASSWORD = "password123418746"
JWT_SECRET = "JWT-Seceret-Key"
JWT_EXPIRES_IN = "1y"
PORT = 5000
RATE_LIMIT_PER_HOUR = 500
JWT_EXPIRES_IN = "1d"
REQUIRE_ACTIVATION
RATE_LIMIT_PER_HOUR = 500
GITHUB_OAUTH_CLIENT_ID = "Iv1.6f4b4b8b0b1b4b8b"
GITHUB_OAUTH_CLIENT_SECRET = "6f4b4b8b0b1b4b8b6f4b4b8b0b1b4b8b"
GITHUB_OAUTH_REDIRECT_URL = "http://localhost:3000/auth/github/callback"
16 changes: 14 additions & 2 deletions backend-app/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const app = express();
// configure swagger docs
swaggerDocs(app);


// use json as default format
app.use(express.json());

Expand Down Expand Up @@ -54,11 +55,22 @@ app.use(hpp());
// Compress all responses
app.use(compression());

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

// check if no version is provided if so use the default version
// example api/auth/user/signup => api/v1/auth/user/signup
app.use((req, res, next) => {
if (req.originalUrl.startsWith('/api')) {
req.originalUrl = `/api/${API_VERSION}${req.originalUrl}`;
}
console.log("req.originalUrl", req.originalUrl);
next();
});


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

Expand Down
27 changes: 14 additions & 13 deletions backend-app/config/app_config.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
const { join } = require('path');
const dotenv = require('dotenv');
dotenv.config({ path: join(__dirname, '../.env') });
const fs = require('fs');

// console.log(process.env.NODE_ENV);
// load env file
const envFile = fs.existsSync('.env') ? '.env' : '.env.example';
dotenv.config( { path: join(__dirname, `../${envFile}`) } );

exports.logFilePath = join(__dirname, '../server-logs');
exports.CURRENT_ENV = process.env.NODE_ENV || 'development';
exports.API_VERSION = process.env.API_VERSION || 'v1';
exports.DATABASE = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017';
exports.PORT = process.env.PORT || '5000';
exports.ADMIN_EMAIL = process.env.ADMIN_EMAIL || 'admin@gmail.com';
exports.ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'admin123';
exports.JWT_SECRET = process.env.JWT_SECRET || 'sdfsdf';
exports.JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '1d';
exports.REQUIRE_ACTIVATION = process.env.REQUIRE_ACTIVATION || true;
// RATE_LIMIT_PER_HOUR
exports.RATE_LIMIT_PER_HOUR = process.env.RATE_LIMIT_PER_HOUR || 500;
exports.CURRENT_ENV = process.env.NODE_ENV ?.toLowerCase();
exports.API_VERSION = process.env.API_VERSION ;
exports.DATABASE = process.env.MONGO_URI ;
exports.PORT = process.env.PORT ;
exports.ADMIN_EMAIL = process.env.ADMIN_EMAIL ;
exports.ADMIN_PASSWORD = process.env.ADMIN_PASSWORD ;
exports.JWT_SECRET = process.env.JWT_SECRET ;
exports.JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN ;
exports.REQUIRE_ACTIVATION = process.env.REQUIRE_ACTIVATION ;
exports.RATE_LIMIT_PER_HOUR = process.env.RATE_LIMIT_PER_HOUR ;
exports.GITHUB_OAUTH_CLIENT_ID = process.env.GITHUB_OAUTH_CLIENT_ID;
exports.GITHUB_OAUTH_CLIENT_SECRET = process.env.GITHUB_OAUTH_CLIENT_SECRET;
exports.GITHUB_OAUTH_REDIRECT_URL = process.env.GITHUB_OAUTH_REDIRECT_URL;
Expand Down
2 changes: 1 addition & 1 deletion backend-app/config/logger_config.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const formatLogMessage = format.printf(
* when the log level is debug, debug and all the levels above it will be logged.
* when the log level is warn, warn and all the levels above it will be logged.
*/
const logLevel = CURRENT_ENV.toLowerCase() === "development" ? "debug" : "warn";
const logLevel = CURRENT_ENV === "development" ? "debug" : "warn";

/**
* @description - This is the configuration for the logger
Expand Down
1 change: 1 addition & 0 deletions backend-app/middlewares/rate_limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ module.exports = rateLimit({
max: RATE_LIMIT_PER_HOUR,
windowMs: 60 * 60 * 1000,
message: 'Too many requests from this IP, please try again in an hour!',
skip: (req, res) => req.headers.accept === 'text/event-stream', // Ignore SSE requests
});
10 changes: 10 additions & 0 deletions backend-app/models/user_model.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,16 @@ userSchema.methods.correctPassword = async function (
return await bcrypt.compare(typedPassword, originalPassword);
};


// verify if the user is authorized or restricted from an action
userSchema.methods.isAuthorizedTo = function (action) {
return this.authorities.includes(action);
};
userSchema.methods.isRestrictedFrom = function (action) {
return this.restrictions.includes(action);
};


userSchema.index(
{ email: 1 },
{ unique: true, partialFilterExpression: { deleted: false } }
Expand Down
2 changes: 1 addition & 1 deletion backend-app/routes/auth_routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ router.get('/github/callback', authController.githubHandler);

// make this file so i can use it with authRoutes(router) in index.js
const authRoutes = (mainrouter) => {
swaggergenerator.register('auth', './routes/auth_routes.js');
// swaggergenerator.register('auth', './routes/auth_routes.js');
mainrouter.use('/auth', router);
};
module.exports = authRoutes;
2 changes: 1 addition & 1 deletion backend-app/routes/github_routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const swaggergenerator = require('../utils/swagger/swaggergenerator');
router.get('/recent-repo', githubController.getRecentRepo);

const githubRoutes = (mainrouter) => {
swaggergenerator.register('github', './routes/github_routes.js');
// swaggergenerator.register('github', './routes/github_routes.js');
mainrouter.use('/github', router);
};

Expand Down
2 changes: 1 addition & 1 deletion backend-app/routes/users/admin_route.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ router.put(
);

adminRoutes = (mainrouter) => {
swaggergenerator.register('admin', './routes/users/admin_route.js');
// swaggergenerator.register('admin', './routes/users/admin_route.js');
mainrouter.use('/admin', router);
};
module.exports = adminRoutes;
8 changes: 4 additions & 4 deletions backend-app/routes/users/super_admin_route.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ router.put(
);

superAdminRoutes = (mainrouter) => {
swaggergenerator.register(
'super_admin',
'./routes/users/super_admin_route.js'
);
// swaggergenerator.register(
// 'super_admin',
// './routes/users/super_admin_route.js'
// );
mainrouter.use('/super_admin', router);
};
module.exports = superAdminRoutes;
Expand Down
2 changes: 1 addition & 1 deletion backend-app/routes/users/user_route.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ router
.patch(userController.updateMe);

userRoutes = (mainrouter) => {
swaggergenerator.register('user', './routes/users/user_route.js');
// swaggergenerator.register('user', './routes/users/user_route.js');
mainrouter.use('/users', router);
};

Expand Down
4 changes: 3 additions & 1 deletion backend-app/server.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const mongoose = require('mongoose');
require('./utils/logger');
const fs = require('fs');
const { DATABASE, PORT } = require('./config/app_config');
const createRoles = require('./utils/authorization/role/create_roles');

Expand All @@ -20,7 +21,7 @@ mongoose
Logger.info('DB Connected Successfully!');
})
.catch((err) => {
Logger.error('DB Connection Failed! \n\tException : ' + err);
Logger.error('DB Connection Failed! \n\tException : ' + err + '\n' + err.stack);
}); //Now all the errors of mongo will be handled by the catch block

// When the connection is disconnected
Expand All @@ -30,6 +31,7 @@ mongoose.connection.on('disconnected', () => {

// Start the server
const expServer = app.listen(PORT, async () => {
if(!fs.existsSync('.env')) Logger.warn('.env file not found, using .env.example file');
Logger.info(`App running on port ${PORT}`);
await createRoles();
});
Expand Down
2 changes: 1 addition & 1 deletion backend-app/utils/swagger/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const swaggerUiOptions = {
* @returns {void}
*/
const swaggerDocs = (app) => {
if (CURRENT_ENV.toLowerCase() === 'production') return;
if (CURRENT_ENV === 'production') return;
app.use(
'/docs',
swaggerUi.serve,
Expand Down

0 comments on commit fbb1537

Please sign in to comment.