Skip to content

Commit

Permalink
Code Synced by DhiWise
Browse files Browse the repository at this point in the history
  • Loading branch information
avina-zalavadiya committed Jun 14, 2021
1 parent e01f28e commit e5f6043
Show file tree
Hide file tree
Showing 54 changed files with 4,236 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .env
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
PORT=3000
DB_URL = 'mongodb://localhost:27017/node_test'
TEST=test
data=tabws
2 changes: 2 additions & 0 deletions .env.PRODUCTION
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
TEST=da
data=tab
2 changes: 2 additions & 0 deletions .env.QA
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
TEST=test
data=tab
35 changes: 35 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
parserOptions: {
ecmaVersion: 12,
sourceType: 'module',
},
rules: {
'multiline-comment-style': ['error', 'starred-block'],
'object-property-newline': ['error', {
allowAllPropertiesOnSameLine: false,
allowMultiplePropertiesPerLine: false,
}],
'object-curly-newline': ['error', {
minProperties: 2,
multiline: true,
}],
'no-multiple-empty-lines': ['error', {
max: 1,
maxEOF: 0,
}],
semi: ['error', 'always'],
indent: ['error', 2],
'no-param-reassign': 'off',
'no-underscore-dangle': 'off',
'class-methods-use-this': 'off',
'max-len': [2, {
code: 1000,
ignorePattern: '^import .*',
}],
'linebreak-style': ['error', process.platform === 'win32' ? 'windows' : 'unix'],
},
};
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
121 changes: 121 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# MVC NodeJS,Mongoose,Express Project


supported version of nodejs-15.13.0
supported version of mongoose-4.0

This is a template of Web application, developed using MVC pattern with Node.js, ExpressJS, and Mongoose ODM.
Basic boilerplate for web applications, built on Express.js using the Model–View–Controller architectural pattern.
The views are created with the Embedded JavaScript template (EJS) view engine.
A MongoDB database is used for data storage, with object modeling provided by Mongoose.

# initial
- Configure a basic server in app.js.
- Organize the routes with Express Router.
- Use the mainRoutes in app as middleware.
- Set a final use after the routes, to display a 404 message for the unhandled requests.
1.Install needed Node.js modules:
```$ npm install```
2.execute server:
```$ npm start```
# folder structure:

--project
--project_folder
--config
--controller
--jobs
--logs
--middleware
--model
--postman
--public
--routes
--services
--utils
--views
--app.js
--.env
--.gitignore
--.eslintrc.js
--project_folder.zip
# app.js
- entry point of application.
# config
- passport strategy for all platforms.
- based on Auth Model - authentication files has been generated.
- Auth constant File that has authentication configuration constants
- Used .env file and configure the db connection string to use in the project.
# controller
- includes controller files per model
- Controllers are separated per Platform

-controller
-admin
-modelController.js
-device
-modelController.js
-desktop
-modelController.js
-client
-modelController.js

# jobs
- Cron jobs related Files and configuration
# logs
- Log file
# middleware
- User authentication Middleware based on Roles and permission for Routes' access
- Custom Policy files
# models
- Mongoose Models , as per user defined schema
# postman
- Postman collection File for Platform based APIs that are generated.
- Import this JSON in Postman to test the APIs.
# public
- You can add static files like like images, pdf etc.
# routes
- based on platform,separate folder is generated,within those folders model wise route files are that has model crud APIs' routes.
- index.js file, main file which includes all platform routes.
- added index files in app.js to access the routes of the application.
# services
-jobs
-cron job services
-auth.js
-Logic for JWT Tokenization for user to login into Application using username and password along with otp if required.
# utils
-validation
-joi validations files.
-files are separated by models.
-common.js
-converted object to enum function.
-dbService.js
-common Database functionalities
-getAllDocuments(find all documents)
-updateDocuments(update single documents in db)
-deleteDocuments(delete single documents in db)
-createDocuments(create single documents in db)
-getDocumentByQuery(find single document)
-getSingleDocumentById(find by id)
-softDelete
-findExistData
-bulkInsert(insert multiple documents in db)
-bulkUpdate(update multiple documents in db)
-countDocument
-Aggregation
-messages.js
-static messages that are sent with response - contains status and Data
-responseCode.js
-codes for responses
-validateRequest.js
-validate schema based on joi validation
# views
- add ejs files








37 changes: 37 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const express = require('express');
const path = require('path');
const dotenv = require('dotenv');
dotenv.config();
global.__basedir = __dirname;
const ejs = require("ejs");
let cookieParser = require('cookie-parser');
let logger = require('morgan');
const passport = require("passport")

const {adminPassportStrategy} = require("./config/adminPassportStrategy");

const app = express();

//template engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

//all routes
const routes = require("./routes/index")

//jobs configuration
require('./jobs/index');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(routes)

adminPassportStrategy(passport);


app.listen(process.env.PORT,()=>{
console.log(`your application is running on ${process.env.PORT}`)
});
43 changes: 43 additions & 0 deletions config/adminPassportStrategy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* admin authentication - with passport
*/

const { Strategy, ExtractJwt } = require("passport-jwt")
const { JWT } = require("./authConstant")
const user = require("../model/user")

let token = null;
const jwtExtractor = (req) => {
if (req && req.headers) {
let tokenParts = req.headers.authorization.split(' ');
if (/^Bearer$/i.test(tokenParts[0])) {
token = tokenParts[1];
}
}
return token;
};

module.exports = {
adminPassportStrategy: passport => {
const options = {};
options.jwtFromRequest =jwtExtractor; options.secretOrKey = JWT.ADMIN_SECRET;
passport.use('admin-rule',
new Strategy(options, (payload, done) => {
user.findOne({ username: payload.username }, (err, user) => {
if (err) {
// console.log(err)
return done(err, false);
}
if (user) {
if(user.tokens.includes(token)){
return done(null, {
...user.toJSON()
});
}
}
return done('No User Found', {});
});
})
);
}
}
90 changes: 90 additions & 0 deletions config/authConstant.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* constants
*/

const JWT={
ADMIN_SECRET:"myjwtadminsecret",
EXPIRES_IN: 10000
}

const USER_ROLE ={
User:1,
Admin:2,
}

const PLATFORM = {
ADMIN:1,
}

let LOGIN_ACCESS ={
[USER_ROLE.User]:[PLATFORM.ADMIN],
[USER_ROLE.Admin]:[PLATFORM.ADMIN],
}

const DEFAULT_ROLE= 1

const ROLE_RIGHTS={

[USER_ROLE.User] : [
"getAllByUserInAdminPlatform",
"getByUserInAdminPlatform",
"aggregateByUserInAdminPlatform",
"getCountByUserInAdminPlatform",
"createByUserInAdminPlatform",
"addBulkByUserInAdminPlatform",
"updateByUserInAdminPlatform",
"updateBulkByUserInAdminPlatform",
"partialUpdateByUserInAdminPlatform",
"deleteByUserInAdminPlatform",
"softDeleteByUserInAdminPlatform",
"upsertByUserInAdminPlatform",
"fileUploadByUserInAdminPlatform",
"changePasswordByUserInAdminPlatform"
],

[USER_ROLE.Admin] : [
"getAllByAdminInAdminPlatform",
"getByAdminInAdminPlatform",
"aggregateByAdminInAdminPlatform",
"getCountByAdminInAdminPlatform",
"createByAdminInAdminPlatform",
"addBulkByAdminInAdminPlatform",
"updateByAdminInAdminPlatform",
"updateBulkByAdminInAdminPlatform",
"partialUpdateByAdminInAdminPlatform",
"deleteByAdminInAdminPlatform",
"softDeleteByAdminInAdminPlatform",
"upsertByAdminInAdminPlatform",
"fileUploadByAdminInAdminPlatform",
"changePasswordByAdminInAdminPlatform"
],

}
const MAX_LOGIN_RETRY_LIMIT = 3;

const SEND_LOGIN_OTP = {
SMS:1,
EMAIL:2,
}
const DEFAULT_SEND_LOGIN_OTP=SEND_LOGIN_OTP.SMS

const FORGOT_PASSWORD_WITH = {
LINK: {
sms: true,
email: false
},
EXPIRETIME: 23
}

module.exports = {
JWT,
USER_ROLE,
DEFAULT_ROLE,
ROLE_RIGHTS,
PLATFORM,
MAX_LOGIN_RETRY_LIMIT,
SEND_LOGIN_OTP,
DEFAULT_SEND_LOGIN_OTP,
FORGOT_PASSWORD_WITH,
LOGIN_ACCESS
}
17 changes: 17 additions & 0 deletions config/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* Database connection file.
*/
const mongoose = require("mongoose")
const uri = process.env.DB_URL;
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
var db = mongoose.connection

db.once("open", () => {
console.log("Connection Successful")
})

db.on("error", () => {
console.log("Error in Connect Mongo")
})

module.exports = mongoose
8 changes: 8 additions & 0 deletions constants/account.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* constants
*/

module.exports={
type: { data: 1, data_2: 2 },
type_type: { type: { data: 1, data_2: 2 } }
}
5 changes: 5 additions & 0 deletions constants/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/*
* constants
*/

module.exports={ type: 1 }
Loading

0 comments on commit e5f6043

Please sign in to comment.