├── .dockerignore
├── test
├── testConfig.json
└── index.js
├── bin
├── swagger
│ ├── swagger_views
│ │ ├── index.jade
│ │ └── layout.jade
│ ├── swagger_dependencies
│ │ ├── stylesheets
│ │ │ └── style.css
│ │ ├── swagger
│ │ │ ├── images
│ │ │ │ ├── throbber.gif
│ │ │ │ ├── logo_small.png
│ │ │ │ ├── wordnik_api.png
│ │ │ │ └── pet_store_api.png
│ │ │ ├── index.json
│ │ │ ├── lib
│ │ │ │ ├── jquery.slideto.min.js
│ │ │ │ ├── jquery.wiggle.min.js
│ │ │ │ ├── jquery.ba-bbq.min.js
│ │ │ │ ├── highlight.7.3.pack.js
│ │ │ │ ├── underscore-min.js
│ │ │ │ ├── backbone-min.js
│ │ │ │ └── swagger.js
│ │ │ ├── css
│ │ │ │ └── hightlight.default.css
│ │ │ ├── index.html
│ │ │ └── swagger-ui.min.js
│ │ └── swaggeruser.json
│ ├── swagger_Routes
│ │ └── user.js
│ └── swagger_lib
│ │ └── swagger-express
│ │ └── index.js
├── dbConnection.js
└── www.js
├── .gitignore
├── server
├── services
│ ├── index.js
│ └── commonService.js
├── routes
│ ├── index.js
│ └── v1
│ │ ├── index.js
│ │ └── userRoutes.js
├── config
│ ├── index.js
│ ├── awsConfig.js
│ └── dbConfig.js
├── controller
│ ├── index.js
│ └── userController.js
├── models
│ ├── index.js
│ ├── appVersionModel.js
│ └── userModel.js
└── util
│ ├── Bootstraping
│ └── Bootstraping.js
│ ├── auth.js
│ ├── commonFunction.js
│ └── constants.js
├── environment
├── development.yml
└── production.yml
├── client
└── index.html
├── Dockerfile
├── filebundle.js
├── gulpfile.js
├── api.yml
├── api.coffee
├── server.js
├── package.json
└── README.md
/.dockerignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | npm-debug.log
--------------------------------------------------------------------------------
/test/testConfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "BaseUrl": "http://localhost:4000"
3 | }
--------------------------------------------------------------------------------
/bin/swagger/swagger_views/index.jade:
--------------------------------------------------------------------------------
1 | extends layout
2 |
3 | block content
4 | h1= title
5 | p Welcome to #{title}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Dependency directories
2 | node_modules/
3 |
4 | # Visual Studio Code created by default file's
5 | .vscode
6 |
7 | # Remove unnessary file's
8 | .idea
9 | .eslintrc
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/stylesheets/style.css:
--------------------------------------------------------------------------------
1 | body {
2 | padding: 50px;
3 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
4 | }
5 |
6 | a {
7 | color: #00B7FF;
8 | }
--------------------------------------------------------------------------------
/bin/swagger/swagger_views/layout.jade:
--------------------------------------------------------------------------------
1 | doctype html
2 | html
3 | head
4 | title= title
5 | link(rel='stylesheet', href='/stylesheets/style.css')
6 | body
7 | block content
8 |
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/images/throbber.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radhey113/node-with-express-and-swagger-docker/HEAD/bin/swagger/swagger_dependencies/swagger/images/throbber.gif
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/images/logo_small.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radhey113/node-with-express-and-swagger-docker/HEAD/bin/swagger/swagger_dependencies/swagger/images/logo_small.png
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/images/wordnik_api.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radhey113/node-with-express-and-swagger-docker/HEAD/bin/swagger/swagger_dependencies/swagger/images/wordnik_api.png
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/images/pet_store_api.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/radhey113/node-with-express-and-swagger-docker/HEAD/bin/swagger/swagger_dependencies/swagger/images/pet_store_api.png
--------------------------------------------------------------------------------
/server/services/index.js:
--------------------------------------------------------------------------------
1 |
2 | "use strict";
3 |
4 |
5 | /********************************
6 | ***** Managing all Services ****
7 | ********************************/
8 | module.exports = {
9 | commonService : require("./commonService"),
10 | };
11 |
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/index.json:
--------------------------------------------------------------------------------
1 | {
2 | "apiVersion": "0.1.5",
3 | "swaggerVersion": "1.2.5",
4 | "basePath": "",
5 | "apis": [
6 | {
7 | "path": "/api-docs.json/user",
8 | "description": "User API"
9 | }
10 | ]
11 | }
12 |
--------------------------------------------------------------------------------
/server/routes/index.js:
--------------------------------------------------------------------------------
1 |
2 | 'use strict';
3 |
4 | /********************************
5 | **** Managing all the routes ***
6 | ********* independently ********
7 | ********************************/
8 | module.exports = function(app){
9 | require("./v1")(app)
10 | };
11 |
--------------------------------------------------------------------------------
/environment/development.yml:
--------------------------------------------------------------------------------
1 | apps:
2 | - script : ./server.js
3 | watch : true
4 | env :
5 | NODE_ENV: development
6 | PORT : 8080
7 | DB_PORT: 3306
8 | env_production:
9 | NODE_ENV: development
10 | PORT : 8080
11 | DB_PORT: 3306
--------------------------------------------------------------------------------
/environment/production.yml:
--------------------------------------------------------------------------------
1 | apps:
2 | - script : ./server.js
3 | watch : true
4 | env :
5 | NODE_ENV: production
6 | PORT : 8081
7 | DB_HOST: 3306
8 | env_production:
9 | NODE_ENV: production
10 | PORT : 8081
11 | DB_HOST: 3306
--------------------------------------------------------------------------------
/server/config/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | /***********************************
4 | ****** Configuration Manager ******
5 | ***********************************/
6 | module.exports = {
7 | dbConfig : require("./dbConfig"),
8 | awsConfig : require("./awsConfig"),
9 | };
--------------------------------------------------------------------------------
/server/controller/index.js:
--------------------------------------------------------------------------------
1 |
2 | "use strict";
3 |
4 | /**************************************************
5 | ************** Controller Manager ****************
6 | **************************************************/
7 | module.exports = {
8 | userController : require("./userController"),
9 | };
--------------------------------------------------------------------------------
/client/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 | Demo application.
10 | Click here to visit demo api documentation...
11 |
12 |
--------------------------------------------------------------------------------
/server/routes/v1/index.js:
--------------------------------------------------------------------------------
1 |
2 | 'use strict';
3 |
4 |
5 | /********************************
6 | * Calling routes and passing ***
7 | * @param app (express instance)*
8 | ******** to create API *********
9 | ********************************/
10 | module.exports = function(app){
11 | require("./userRoutes")(app)
12 | };
13 |
--------------------------------------------------------------------------------
/server/models/index.js:
--------------------------------------------------------------------------------
1 |
2 | "use strict";
3 |
4 | /**************************************************
5 | *********** Model or collection Manager **********
6 | **************************************************/
7 | module.exports = {
8 | userModel : require("./userModel"),
9 | appVersionModel : require("./appVersionModel"),
10 | };
11 |
12 |
--------------------------------------------------------------------------------
/server/config/awsConfig.js:
--------------------------------------------------------------------------------
1 |
2 | 'use strict';
3 |
4 | /** AWS credencials config **/
5 | var s3BucketCredentials = {
6 | "bucket": "",
7 | "accessKeyId": "",
8 | "secretAccessKey": "",
9 | "s3URL": "",
10 | "folder": {
11 | "bucketKey": ""
12 | }
13 | };
14 |
15 |
16 | module.exports = s3BucketCredentials;;
17 |
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/lib/jquery.slideto.min.js:
--------------------------------------------------------------------------------
1 | (function(b){b.fn.slideto=function(a){a=b.extend({slide_duration:"slow",highlight_duration:3E3,highlight:true,highlight_color:"#FFFF99"},a);return this.each(function(){obj=b(this);b("body").animate({scrollTop:obj.offset().top},a.slide_duration,function(){a.highlight&&b.ui.version&&obj.effect("highlight",{color:a.highlight_color},a.highlight_duration)})})}})(jQuery);
2 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM node:8
2 |
3 | # Create app directory
4 | WORKDIR /usr/src/app
5 |
6 | # Install app dependencies
7 | # A wildcard is used to ensure both package.json AND package-lock.json are copied
8 | # where available (npm@5+)
9 | COPY package*.json ./
10 |
11 | RUN npm install
12 | # If you are building your code for production
13 | # RUN npm install --only=production
14 |
15 | # Bundle app source
16 | COPY . .
17 |
18 | EXPOSE 4000
19 | CMD [ "npm", "start" ]
--------------------------------------------------------------------------------
/filebundle.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by Radhey Shyam on 14/02/18.
3 | */
4 |
5 | "use strict";
6 | /**************** Bundle modules ***************/
7 | module.exports = {
8 | CONFIG : require("./server/config"),
9 | ROUTES : require("./server/routes"),
10 | SERVICES : require("./server/services"),
11 | CONSTANTS : require("./server/util/constants"),
12 | COMMON_FUN : require("./server/util/commonFunction"),
13 | };
14 |
--------------------------------------------------------------------------------
/gulpfile.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by lakshmi on 20/02/18.
3 | */
4 |
5 | // npm install --save-dev gulp gulp-uglify
6 | let gulp = require('gulp');
7 | let gulp_Util = require('gulp-util');
8 | let exec = require('child_process').exec;
9 | let gls = require('gulp-live-server');
10 |
11 | // create a default task and just log a message
12 | gulp.task('default', function() {
13 | return gulp_Util.log('Gulp is running!')
14 | });
15 |
16 | /* start server using gulp*/
17 | gulp.task('start', function() {
18 | var server = gls.new('server.js');
19 | return server.start();
20 | });
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/bin/dbConnection.js:
--------------------------------------------------------------------------------
1 |
2 | 'use strict';
3 |
4 | /*******************************
5 | *** MONGOOSE for connection ***
6 | *******************************/
7 | let MONGOOSE = require('mongoose');
8 |
9 |
10 | /*******************************
11 | ***** Mongodb connection *****
12 | *******************************/
13 | module.exports = (URL) => {
14 | return new Promise((resolve, reject) => {
15 | MONGOOSE.connect(URL, (err, response)=>{
16 | if(err)
17 | reject(err);
18 | else
19 | resolve(null);
20 | });
21 | })
22 | };
23 |
24 |
--------------------------------------------------------------------------------
/api.yml:
--------------------------------------------------------------------------------
1 | resourcePath: /apiYml
2 | description: All about API
3 | apis:
4 |
5 | - path: /login
6 | operations:
7 |
8 | - httpMethod: POST
9 | summary: Login with username and password
10 | notes: Returns a user based on username
11 | responseClass: User
12 | nickname: login
13 | consumes:
14 | - text/html
15 | parameters:
16 |
17 | - name: username
18 | dataType: string
19 | paramType: query
20 | required: true
21 | description: Your username
22 |
23 | - name: password
24 | dataType: string
25 | paramType: query
26 | required: true
27 | description: Your password
28 |
29 | models:
30 | User:
31 | id: User
32 | properties:
33 | username:
34 | type: String
35 | password:
36 | type: String
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/lib/jquery.wiggle.min.js:
--------------------------------------------------------------------------------
1 | /*
2 | jQuery Wiggle
3 | Author: WonderGroup, Jordan Thomas
4 | URL: http://labs.wondergroup.com/demos/mini-ui/index.html
5 | License: MIT (http://en.wikipedia.org/wiki/MIT_License)
6 | */
7 | jQuery.fn.wiggle=function(o){var d={speed:50,wiggles:3,travel:5,callback:null};var o=jQuery.extend(d,o);return this.each(function(){var cache=this;var wrap=jQuery(this).wrap('').css("position","relative");var calls=0;for(i=1;i<=o.wiggles;i++){jQuery(this).animate({left:"-="+o.travel},o.speed).animate({left:"+="+o.travel*2},o.speed*2).animate({left:"-="+o.travel},o.speed,function(){calls++;if(jQuery(cache).parent().hasClass('wiggle-wrap')){jQuery(cache).parent().replaceWith(cache);}
8 | if(calls==o.wiggles&&jQuery.isFunction(o.callback)){o.callback();}});}});};
--------------------------------------------------------------------------------
/server/models/appVersionModel.js:
--------------------------------------------------------------------------------
1 |
2 | 'use strict';
3 |
4 | /********* Modules ********/
5 | let mongoose = require('mongoose');
6 | let Schema = mongoose.Schema;
7 |
8 |
9 | /**************************************************
10 | ********* AppVersions Model or collection ********
11 | **************************************************/
12 | let AppVersions = new Schema({
13 | latestIOSVersion : { type: String, required: true },
14 | latestAndroidVersion : { type: String, required: true },
15 | criticalAndroidVersion : { type: String, required: true },
16 | criticalIOSVersion : { type: String, required: true },
17 | appType : { type: String },
18 | timeStamp : { type: Date, default: Date.now }
19 | });
20 |
21 |
22 | module.exports = mongoose.model('AppVersions', AppVersions);
--------------------------------------------------------------------------------
/test/index.js:
--------------------------------------------------------------------------------
1 |
2 |
3 | process.env = 'test';
4 | let mongoose = require("mongoose");
5 | var mocha = require('mocha')
6 |
7 | let chai = require('chai');
8 | let chaiHttp = require('chai-http');
9 | let server = require('../server.js');
10 | let testConfig = require('./testConfig.json');
11 | let should = chai.should();
12 |
13 | chai.use(chaiHttp);
14 |
15 | describe('Test', () => {
16 |
17 | describe('/GET users', () => {
18 | it('it should GET all the users', (done) => {
19 |
20 | /** We can also place server.js file here rather than only link **/
21 | chai.request(testConfig.BaseUrl)
22 | .get('/getUser')
23 | .end((err, res) => {
24 |
25 | res.should.have.status(200);
26 | res.body.should.be.eql('cool');
27 | res.body.length.should.be.eql(4);
28 | done();
29 | });
30 | });
31 | });
32 | });
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swaggeruser.json:
--------------------------------------------------------------------------------
1 | {
2 | "apiVersion": "0.0.1",
3 | "swaggerVersion": "1.2.5",
4 | "basePath": "",
5 | "apis": [
6 | {
7 | "path": "/user",
8 | "operations": [
9 | {
10 | "httpMethod": "GET",
11 | "summary": "get a user by user id",
12 | "nickname": "User",
13 | "consumes": [
14 | "application/json"
15 | ],
16 | "produces": [
17 | "application/json"
18 | ],
19 | "responseMessages": [
20 | {
21 | "code": 500,
22 | "message": "Internal server error"
23 | },
24 | {
25 | "code": 400,
26 | "message": "Bad request"
27 | },
28 | {
29 | "code": 404,
30 | "message": "Not found"
31 | }
32 | ]
33 | }
34 | ]
35 | }
36 | ],
37 | "models": {}
38 | }
39 |
--------------------------------------------------------------------------------
/api.coffee:
--------------------------------------------------------------------------------
1 |
2 | ###
3 | * @swagger
4 | * resourcePath: /apiCoffee
5 | * description: All about API
6 | ###
7 |
8 | ###
9 | * @swagger
10 | * path: /login
11 | * operations:
12 | * - httpMethod: POST
13 | * summary: Login with username and password
14 | * notes: Returns a user based on username
15 | * responseClass: User
16 | * nickname: login
17 | * consumes:
18 | * - text/html
19 | * parameters:
20 | * - name: username
21 | * description: Your username
22 | * paramType: query
23 | * required: true
24 | * dataType: string
25 | * - name: password
26 | * description: Your password
27 | * paramType: query
28 | * required: true
29 | * dataType: string
30 |
31 | ###
32 |
33 | ###
34 | * @swagger
35 | * models:
36 | * User:
37 | * id: User
38 | * properties:
39 | * username:
40 | * type: String
41 | * password:
42 | * type: String
43 | ###
--------------------------------------------------------------------------------
/server/routes/v1/userRoutes.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by Radhey Shyam on 14/02/18.
3 | */
4 |
5 | 'use strict';
6 | let CONTROLLER = require("../../controller");
7 | let auth = require("../../util/auth");
8 |
9 | /****************************************
10 | ***** Managing User Routes here ********
11 | ***** @param APP (express instance)*****
12 | ****************************************/
13 | module.exports = (APP)=>{
14 |
15 | APP.route('/api/register')
16 | .post(CONTROLLER.userController.registerUser);
17 |
18 | APP.route('/api/fileUpload')
19 | .post(CONTROLLER.userController.upload);
20 |
21 | APP.route('/api/login')
22 | .get(CONTROLLER.userController.loginUser);
23 |
24 | APP.route('/api/forgotPassword')
25 | .post(CONTROLLER.userController.forgotPassword);
26 |
27 | APP.route('/api/changePassword')
28 | .post(CONTROLLER.userController.changePassword);
29 |
30 |
31 | APP.route('/getUser')
32 | .get((req, res)=>{
33 | res.jsonp('cool')
34 | })
35 | };
--------------------------------------------------------------------------------
/server.js:
--------------------------------------------------------------------------------
1 |
2 | 'use strict';
3 |
4 | /***********************************
5 | * www.js is a file from where our *
6 | * server is running **************
7 | ***********************************/
8 | let www = require('./bin/www.js');
9 |
10 |
11 | /***********************************
12 | * dbConnection.js is a file from **
13 | * where we are connecting our *****
14 | * mongodb database **************
15 | ***********************************/
16 |
17 | let db = require('./bin/dbConnection.js');
18 |
19 |
20 | /***********************************
21 | * dbConfig.js is a file from we ***
22 | ****** are getting mongodb ********
23 | ********* configurations **********
24 | ***********************************/
25 | let dbConfig = require('./server/config/dbConfig');
26 |
27 |
28 | /***********************************
29 | * Database conectinvity before ****
30 | ***** running server (www()) ******
31 | ***********************************/
32 | db(dbConfig.mongodb.url).then(resolve => {
33 | console.log(`*********DB is connected successfully*********`);
34 | www();
35 | }).catch(err => {
36 | console.log(`*********err********* ${err}`);
37 | });
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "withexpress",
3 | "version": "1.0.0",
4 | "description": "",
5 | "main": "index.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1",
8 | "start": "node server.js",
9 | "gulpstart": "gulp start",
10 | "gulp-build": "NODE_ENV='production' gulp"
11 | },
12 | "author": "",
13 | "license": "ISC",
14 | "dependencies": {
15 | "aws-sdk": "^2.287.0",
16 | "bcryptjs": "^2.4.3",
17 | "body-parser": "^1.18.2",
18 | "chai-http": "^4.0.0",
19 | "cheerio": "^1.0.0-rc.2",
20 | "express": "^4.16.2",
21 | "express-validation-swagger": "^0.1.5",
22 | "fs": "0.0.1-security",
23 | "fs-extra": "^7.0.0",
24 | "gm": "^1.23.1",
25 | "gulp-live-server": "0.0.31",
26 | "jsonwebtoken": "^8.1.1",
27 | "log4js": "^2.4.1",
28 | "mime-types": "^2.1.19",
29 | "moment": "^2.21.0",
30 | "moment-timezone": "^0.5.14",
31 | "mongoose": "^5.0.5",
32 | "multer": "^1.3.1",
33 | "nodemailer-smtp-transport": "^2.7.4",
34 | "passport": "^0.4.0",
35 | "passport-jwt": "^3.0.1",
36 | "path": "^0.12.7",
37 | "randomstring": "^1.1.5",
38 | "request": "^2.85.0",
39 | "sendinblue-api": "^1.0.8",
40 | "swagger-express": "^1.0.5",
41 | "swagger-node-express": "^2.1.3"
42 | },
43 | "devDependencies": {
44 | "chai": "^4.1.2",
45 | "child_process": "^1.0.2",
46 | "gulp": "^3.9.1",
47 | "gulp-util": "^3.0.8",
48 | "gulplog": "^1.0.0",
49 | "mocha": "^5.2.0"
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/server/models/userModel.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by lakshmi on 14/02/18.
3 | */
4 |
5 | /**
6 | * Created by Radhey Shyam on 14/02/18.
7 | */
8 |
9 | "use strict";
10 | /************* Modules ***********/
11 | const MONGOOSE = require("mongoose");
12 | const Schema = MONGOOSE.Schema;
13 | const Constants = require("../util/constants");
14 |
15 | /**************************************************
16 | ************* User Model or collection ***********
17 | **************************************************/
18 | const user_Schema = new Schema({
19 | username: {
20 | type: String,
21 | required: true,
22 | },
23 | email: {
24 | type: String,
25 | required: true,
26 | unique: true
27 | },
28 | password: {
29 | type: String
30 | // "required": true,
31 | },
32 | createAt: {
33 | type: Date,
34 | default: Date.now
35 | },
36 | roles: {
37 | type: [String],
38 | enum : [ Constants.DATABASE.USER_ROLES.USER, Constants.DATABASE.USER_ROLES.ADMIN, Constants.DATABASE.USER_ROLES.SUB_ADMIN ],
39 | default: "USER"
40 | },
41 | isActive: {
42 | type: Number,
43 | enum: [ Constants.SERVER.ISACTIVE[0].NOT_VERIFIED, Constants.SERVER.ISACTIVE[0].VERIFIED, Constants.SERVER.ISACTIVE[0].DELETED ],
44 | default: Constants.SERVER.ISACTIVE[0].NOT_VERIFIED
45 | },
46 | status: {
47 | type: Number,
48 | default: 0
49 | }
50 | });
51 |
52 | module.exports = MONGOOSE.model("User", user_Schema);
53 |
--------------------------------------------------------------------------------
/server/config/dbConfig.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by Radhey Shyam on 15/02/18.
3 | */
4 |
5 | "use strict";
6 |
7 | /******************************************
8 | ****** Default Server configuration ******
9 | ******************************************/
10 | let serverConfig = {
11 | mongodb: {
12 | host : "127.0.0.1",
13 | port : 27017,
14 | name : "mongodb",
15 | connector : "mongodb",
16 | url : process.env.dbUrl || "mongodb://127.0.0.1/demo_dev",
17 | database : "demo_dev",
18 | user : "",
19 | password : "",
20 | },
21 | host : "localhost",
22 | type : "http://",
23 | port : process.env.serverPort || '4000'
24 | };
25 |
26 |
27 | /***********************************
28 | ** Maintain server Configuration **
29 | **** according to env variable ****
30 | ***********************************/
31 | if(process.env.NODE_ENV === "development"){
32 |
33 | serverConfig.mongodb.user = "";
34 | serverConfig.mongodb.password = "";
35 | }
36 | else if( process.env.NODE_ENV === "production"){
37 |
38 | serverConfig.mongodb.url = process.env.dbUrl || "mongodb://127.0.0.1:27017/demo";
39 | serverConfig.mongodb.database = "demo";
40 | serverConfig.mongodb.user = "";
41 | serverConfig.mongodb.password = "";
42 | serverConfig.port = process.env.serverPort || "4001";
43 | }
44 |
45 | /** exporting server configuration **/
46 | module.exports = serverConfig;
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Run Node JS Back-End with Dockerfile [ Express Framework and Swagger Documentation ]
2 |
3 | This is a boiler plate for developing a nodejs application with express. I have used `Node 8+` and `MongoDB 3.6` to create it. I have also implemented `JWT` for token verification, I have created some middlewares or helpers for user authentication.
4 |
5 | For API documentation I have used `Swagger`.
6 |
7 | ## Requirment
8 | `Mongodb 3.6`:
9 | + **Install MonngDB 3.6**
10 | + *` Ref: `* https://docs.mongodb.com/manual/installation/
11 |
12 | `NodeJS v8+`
13 | + *`Ref:`* http://nodejs.org
14 |
15 | ## Run Locally with Node
16 | + Go to project working directory / Project folder
17 | + Execute command `npm install`
18 | + After that Run Command `node server.js`
19 | + Open `http://localhost:4000` to check that your server is running or not.
20 | + To check the documentation Kindly follow the: `http://localhost:4000/swagger`
21 |
22 |
23 | ## Run Project with Dockerfile
24 | + Install Docker
25 | + `https://docs.docker.com/install/`
26 | + [Run Docker image](https://medium.com/@radheyg11/docker-with-node-e6cf77cfd21f)
27 | + Go to terminal, Run command
28 | + `cd `
29 | + Run command to create node project build
30 | + `docker build -t node:8 ./`
31 | + To Run node server (Local 4000 port mapping node server 4000 port from container)
32 | + `docker run -p 4000:4000 node:8`
33 | + To Run node server in deamon mode use command ``
34 | + `docker run -p 4000:4000 -d node:8`
35 | + Open `http://localhost:4000` to check that your server is running or not.
36 | + To check the documentation Kindly follow the: `http://localhost:4000/swagger`
37 |
38 |
39 | ##### Set environment variable through ``
40 | - Create and .env file in your project directory
41 | - Write enviornment variable like: `NODE_ENV=development`
42 | - Use `--env-file ./env` parameter with `docker run` command
43 | - Example: `docker run --env-file ./env -p 4000:4000 node:8`
44 |
45 |
46 | ## Environment Vairable
47 | + To set the `environment`variable for your project, you can use `./environment/development.yml` or for development or `./environment/production.yml` for production environment.
48 | + You can also set the environment using shell command:
49 | + `export env=development`
50 | + To check that `environment` variable is set or not:
51 | + `echo ${env}`
52 |
53 | *I hope it will help you to create your new nodejs project with express using swagger api documentation.*
54 | ## Thank you
55 |
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/css/hightlight.default.css:
--------------------------------------------------------------------------------
1 | /*
2 |
3 | Original style from softwaremaniacs.org (c) Ivan Sagalaev
4 |
5 | */
6 |
7 | pre code {
8 | display: block; padding: 0.5em;
9 | background: #F0F0F0;
10 | }
11 |
12 | pre code,
13 | pre .subst,
14 | pre .tag .title,
15 | pre .lisp .title,
16 | pre .clojure .built_in,
17 | pre .nginx .title {
18 | color: black;
19 | }
20 |
21 | pre .string,
22 | pre .title,
23 | pre .constant,
24 | pre .parent,
25 | pre .tag .value,
26 | pre .rules .value,
27 | pre .rules .value .number,
28 | pre .preprocessor,
29 | pre .ruby .symbol,
30 | pre .ruby .symbol .string,
31 | pre .aggregate,
32 | pre .template_tag,
33 | pre .django .variable,
34 | pre .smalltalk .class,
35 | pre .addition,
36 | pre .flow,
37 | pre .stream,
38 | pre .bash .variable,
39 | pre .apache .tag,
40 | pre .apache .cbracket,
41 | pre .tex .command,
42 | pre .tex .special,
43 | pre .erlang_repl .function_or_atom,
44 | pre .markdown .header {
45 | color: #800;
46 | }
47 |
48 | pre .comment,
49 | pre .annotation,
50 | pre .template_comment,
51 | pre .diff .header,
52 | pre .chunk,
53 | pre .markdown .blockquote {
54 | color: #888;
55 | }
56 |
57 | pre .number,
58 | pre .date,
59 | pre .regexp,
60 | pre .literal,
61 | pre .smalltalk .symbol,
62 | pre .smalltalk .char,
63 | pre .go .constant,
64 | pre .change,
65 | pre .markdown .bullet,
66 | pre .markdown .link_url {
67 | color: #080;
68 | }
69 |
70 | pre .label,
71 | pre .javadoc,
72 | pre .ruby .string,
73 | pre .decorator,
74 | pre .filter .argument,
75 | pre .localvars,
76 | pre .array,
77 | pre .attr_selector,
78 | pre .important,
79 | pre .pseudo,
80 | pre .pi,
81 | pre .doctype,
82 | pre .deletion,
83 | pre .envvar,
84 | pre .shebang,
85 | pre .apache .sqbracket,
86 | pre .nginx .built_in,
87 | pre .tex .formula,
88 | pre .erlang_repl .reserved,
89 | pre .prompt,
90 | pre .markdown .link_label,
91 | pre .vhdl .attribute,
92 | pre .clojure .attribute,
93 | pre .coffeescript .property {
94 | color: #88F
95 | }
96 |
97 | pre .keyword,
98 | pre .id,
99 | pre .phpdoc,
100 | pre .title,
101 | pre .built_in,
102 | pre .aggregate,
103 | pre .css .tag,
104 | pre .javadoctag,
105 | pre .phpdoc,
106 | pre .yardoctag,
107 | pre .smalltalk .class,
108 | pre .winutils,
109 | pre .bash .variable,
110 | pre .apache .tag,
111 | pre .go .typename,
112 | pre .tex .command,
113 | pre .markdown .strong,
114 | pre .request,
115 | pre .status {
116 | font-weight: bold;
117 | }
118 |
119 | pre .markdown .emphasis {
120 | font-style: italic;
121 | }
122 |
123 | pre .nginx .built_in {
124 | font-weight: normal;
125 | }
126 |
127 | pre .coffeescript .javascript,
128 | pre .javascript .xml,
129 | pre .tex .formula,
130 | pre .xml .javascript,
131 | pre .xml .vbscript,
132 | pre .xml .css,
133 | pre .xml .cdata {
134 | opacity: 0.5;
135 | }
136 |
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Swagger UI
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
49 |
50 |
51 |
52 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/bin/www.js:
--------------------------------------------------------------------------------
1 | /**
2 | * express server setup
3 | */
4 |
5 | 'use strict';
6 |
7 | /***********************************
8 | **** node module defined here *****
9 | ***********************************/
10 | const EXPRESS = require("express");
11 | const BODY_PARSER = require("body-parser");
12 | const ALLFILES = require("./../filebundle");
13 | const SWAGGER = require('./swagger/swagger_lib/swagger-express');
14 | const PATH = require("path");
15 | const BOOTSTRAPING = require("../server/util/Bootstraping/Bootstraping");
16 |
17 |
18 | /**creating express server app for server */
19 | const app = EXPRESS();
20 |
21 |
22 | /********************************
23 | ***** Server Configuration *****
24 | ********************************/
25 | app.set('port', process.env.PORT || ALLFILES.CONFIG.dbConfig.port);
26 | app.set('swagger_views', __dirname + '../swagger_views');
27 | app.set('view engine', 'jade');
28 | app.use(EXPRESS.static("client"));
29 | app.use(BODY_PARSER.json({limit: '50mb'}));
30 | app.use(BODY_PARSER.urlencoded({ limit: '50mb', extended: true }));
31 |
32 | /** middleware for api's logging with deployment mode */
33 | let apiLooger = (req, res, next)=>{
34 | ALLFILES.COMMON_FUN.messageLogs(null, `api hitted ${req.url} ${ process.env.NODE_ENV}`);
35 | next();
36 | };
37 |
38 | /** Used logger middleware for each api call **/
39 | app.use(apiLooger);
40 |
41 | /*******************************
42 | *** For handling CORS Error ***
43 | *******************************/
44 | app.all('/*', (REQUEST, RESPONSE, NEXT) => {
45 | RESPONSE.header('Access-Control-Allow-Origin', '*');
46 | RESPONSE.header('Access-Control-Allow-Headers','Content-Type, api_key, Authorization, x-requested-with, Total-Count, Total-Pages, Error-Message');
47 | RESPONSE.header('Access-Control-Allow-Methods','POST, GET, DELETE, PUT, OPTIONS');
48 | RESPONSE.header('Access-Control-Max-Age',1800);
49 | NEXT();
50 | });
51 |
52 | /*******************************
53 | **** Swagger configuration ****
54 | *******************************/
55 | app.use(SWAGGER.init(app, {
56 | apiVersion: '1.0',
57 | swaggerVersion: '1.0',
58 | basePath: "http://" + ALLFILES.CONFIG.dbConfig.host + ":" +ALLFILES.CONFIG.dbConfig.port,
59 | swaggerURL: '/api_documentation',
60 | swaggerJSON: '/api-docs.json',
61 | swaggerUI: './swagger/swagger_dependencies/swagger',
62 | apis: [
63 | PATH.join(__dirname, '/swagger/swagger_Routes/user.js'),
64 | ]
65 | }));
66 | app.use(EXPRESS.static(PATH.join(__dirname, 'swagger/swagger_dependencies')));
67 |
68 |
69 | /*******************************
70 | ****** initializing routes ****
71 | *******************************/
72 | require('../server/routes')(app);
73 |
74 |
75 | /** server listening */
76 | module.exports = () => {
77 |
78 | /*******************************
79 | ****** Admin Bootstrapping ****
80 | *******************************/
81 | BOOTSTRAPING.bootstrapAdmin((ERR, RESULT)=>{
82 | if(ERR){
83 | ALLFILES.COMMON_FUN.messageLogs(ERR.message, null);
84 | process.exit(0);
85 | }else{
86 | ALLFILES.COMMON_FUN.messageLogs(null, "**************Bootstraping done**************");
87 | }
88 | });
89 |
90 | /*******************************
91 | ****** Version Controller* ****
92 | *******************************/
93 | BOOTSTRAPING.bootstrapAppVersion();
94 |
95 |
96 | /** Server is running here */
97 | app.listen(ALLFILES.CONFIG.dbConfig.port, ()=>{
98 | ALLFILES.COMMON_FUN.messageLogs(null, `**************Server is running on ${ALLFILES.CONFIG.dbConfig.port} **************`);
99 | });
100 | };
101 |
102 |
103 |
104 |
--------------------------------------------------------------------------------
/server/util/Bootstraping/Bootstraping.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 |
4 | /************** Modules ***************/
5 | let CONSTANTS = require('../constants');
6 | let Models = require('../../models');
7 | let UniversalFunction = require('../commonFunction');
8 |
9 | /******************************************
10 | * Bootstraping for default admin user... *
11 | ******************************************/
12 | exports.bootstrapAdmin = function (callback) {
13 |
14 | /**Default users**/
15 | let defaultUser = [
16 | {
17 | email: 'admin@example.com',
18 | password: 'fa59d2b94e355a8b5fd0c6bac0c81be5',
19 | username: 'example',
20 | roles: 'ADMIN'
21 | },
22 | {
23 | email: 'radhey@example.com',
24 | password: 'fa59d2b94e355a8b5fd0c6bac0c81be5', //asdfghjkl
25 | username: 'example1',
26 | roles: 'USER'
27 | }
28 | ];
29 |
30 | /******************************************
31 | ******** Default user mapping... *********
32 | ******************************************/
33 | return Promise.all(defaultUser.map( USER => {
34 |
35 | UniversalFunction.encryptPswrd(USER.password, (ERR, HASH)=> {
36 | if(ERR){
37 | throw ERR;
38 | }
39 | else {
40 | USER.password = HASH;
41 | return Models.userModel.findOneAndUpdate(
42 | {email: USER.email, username: USER.username},
43 | {$set: USER},
44 | {new: true, upsert: true, lean: true, setDefaultsOnInsert: true}
45 | ).then(RESULT => {
46 |
47 | return RESULT;
48 | }).catch(ERROR => {
49 | throw ERROR;
50 | })
51 | }
52 | });
53 | })).then(RESULT => {
54 |
55 | callback(null, CONSTANTS.STATUS_MSG.SUCCESS.CREATED);
56 | }).catch(ERROR => {
57 |
58 | callback(UniversalFunction.sendError(ERROR));
59 | });
60 | };
61 |
62 | /****************************************************************
63 | **** Maping app version with app model with respect to user*****
64 | ***************************************************************/
65 | exports.bootstrapAppVersion = function () {
66 | let AppVersion = [
67 | {
68 | latestIOSVersion: '100',
69 | latestAndroidVersion: '100',
70 | criticalAndroidVersion: '100',
71 | criticalIOSVersion: '100',
72 | appType: CONSTANTS.DATABASE.USER_ROLES.USER
73 | },
74 | {
75 | latestIOSVersion: '100',
76 | latestAndroidVersion: '100',
77 | criticalAndroidVersion: '100',
78 | criticalIOSVersion: '100',
79 | appType: CONSTANTS.DATABASE.USER_ROLES.SUB_ADMIN
80 | },
81 | {
82 | latestIOSVersion: '100',
83 | latestAndroidVersion: '100',
84 | criticalAndroidVersion: '100',
85 | criticalIOSVersion: '100',
86 | appType: CONSTANTS.DATABASE.USER_ROLES.ADMIN
87 | }
88 | ];
89 |
90 | /**********************
91 | **** Mapping data*****
92 | **********************/
93 | Promise.all(AppVersion.map(APP_V => {
94 |
95 | let CRITERIA = { appType: APP_V.appType };
96 | let OPTIONS = { upsert: true, new: true, setDefaultsOnInsert: true };
97 |
98 | /**Save App version by mapping **/
99 | return Models.appVersionModel.findOneAndUpdate( CRITERIA, { $set: APP_V }, OPTIONS ).then(RESULT => {
100 |
101 | return RESULT;
102 | }).catch(ERROR => {
103 |
104 | throw ERROR;
105 | })
106 | })).then(RESULT => {
107 | console.log("*************App Version Mapped*************");
108 | }).catch(ERROR => {
109 | console.log("*************App Version Error**************");
110 | })
111 | };
112 |
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/lib/jquery.ba-bbq.min.js:
--------------------------------------------------------------------------------
1 | /*
2 | * jQuery BBQ: Back Button & Query Library - v1.2.1 - 2/17/2010
3 | * http://benalman.com/projects/jquery-bbq-plugin/
4 | *
5 | * Copyright (c) 2010 "Cowboy" Ben Alman
6 | * Dual licensed under the MIT and GPL licenses.
7 | * http://benalman.com/about/license/
8 | */
9 | (function($,p){var i,m=Array.prototype.slice,r=decodeURIComponent,a=$.param,c,l,v,b=$.bbq=$.bbq||{},q,u,j,e=$.event.special,d="hashchange",A="querystring",D="fragment",y="elemUrlAttr",g="location",k="href",t="src",x=/^.*\?|#.*$/g,w=/^.*\#/,h,C={};function E(F){return typeof F==="string"}function B(G){var F=m.call(arguments,1);return function(){return G.apply(this,F.concat(m.call(arguments)))}}function n(F){return F.replace(/^[^#]*#?(.*)$/,"$1")}function o(F){return F.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(H,M,F,I,G){var O,L,K,N,J;if(I!==i){K=F.match(H?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);J=K[3]||"";if(G===2&&E(I)){L=I.replace(H?w:x,"")}else{N=l(K[2]);I=E(I)?l[H?D:A](I):I;L=G===2?I:G===1?$.extend({},I,N):$.extend({},N,I);L=a(L);if(H){L=L.replace(h,r)}}O=K[1]+(H?"#":L||!K[1]?"?":"")+L+J}else{O=M(F!==i?F:p[g][k])}return O}a[A]=B(f,0,o);a[D]=c=B(f,1,n);c.noEscape=function(G){G=G||"";var F=$.map(G.split(""),encodeURIComponent);h=new RegExp(F.join("|"),"g")};c.noEscape(",/");$.deparam=l=function(I,F){var H={},G={"true":!0,"false":!1,"null":null};$.each(I.replace(/\+/g," ").split("&"),function(L,Q){var K=Q.split("="),P=r(K[0]),J,O=H,M=0,R=P.split("]["),N=R.length-1;if(/\[/.test(R[0])&&/\]$/.test(R[N])){R[N]=R[N].replace(/\]$/,"");R=R.shift().split("[").concat(R);N=R.length-1}else{N=0}if(K.length===2){J=r(K[1]);if(F){J=J&&!isNaN(J)?+J:J==="undefined"?i:G[J]!==i?G[J]:J}if(N){for(;M<=N;M++){P=R[M]===""?O.length:R[M];O=O[P]=M').hide().insertAfter("body")[0].contentWindow;q=function(){return a(n.document[c][l])};o=function(u,s){if(u!==s){var t=n.document;t.open().close();t[c].hash="#"+u}};o(a())}}m.start=function(){if(r){return}var t=a();o||p();(function s(){var v=a(),u=q(t);if(v!==t){o(t=v,u);$(i).trigger(d)}else{if(u!==t){i[c][l]=i[c][l].replace(/#.*/,"")+"#"+u}}r=setTimeout(s,$[d+"Delay"])})()};m.stop=function(){if(!n){r&&clearTimeout(r);r=0}};return m})()})(jQuery,this);
--------------------------------------------------------------------------------
/server/util/auth.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by Radhey Shyam on 15/02/18.
3 | */
4 |
5 | "use strict";
6 |
7 |
8 | /************** Modules **************/
9 | let MODEL = require("../models");
10 | let COMMON_FUN = require("../util/commonFunction");
11 | let CONSTANTS = require("../util/constants");
12 | const JWT = require("jsonwebtoken");
13 |
14 | let velidateUser = {};
15 |
16 | /********************************
17 | ********* validate user ********
18 | ********************************/
19 | velidateUser.userValidation = ( REQUEST, RESPONSE, NEXT )=>{
20 | let status = JWT.decode(REQUEST.headers.authorization, CONSTANTS.SERVER.JWT_SECRET_KEY);
21 | (status && status.role === CONSTANTS.DATABASE.USER_ROLES.USER) ? NEXT() : RESPONSE.jsonp(CONSTANTS.STATUS_MSG.ERROR.UNAUTHORIZED);
22 | };
23 |
24 | /********************************
25 | ****** admin authentication ****
26 | ********************************/
27 | velidateUser.adminValidation = ( REQUEST, RESPONSE, NEXT )=>{
28 | let status = REQUEST.headers.authorization ?
29 | JWT.decode(REQUEST.headers.authorization, CONSTANTS.SERVER.JWT_SECRET_KEY):
30 | JWT.decode(REQUEST.query.api_key, CONSTANTS.SERVER.JWT_SECRET_KEY);
31 |
32 | (status && status.role === CONSTANTS.DATABASE.USER_ROLES.ADMIN) ? NEXT() : RESPONSE.jsonp(CONSTANTS.STATUS_MSG.ERROR.UNAUTHORIZED);
33 | };
34 |
35 | /********************************
36 | ****** admin check model ********
37 | *********************************/
38 | velidateUser.adminCheck = ( REQUEST, RESPONSE, NEXT )=>{
39 | let dataObj = REQUEST.query.username;
40 | if(REQUEST.query.username){
41 | dataObj = REQUEST.query;
42 | }else{
43 | dataObj = REQUEST.body;
44 | }
45 |
46 | /** Check required properties **/
47 | COMMON_FUN.objProperties(dataObj, (ERR, RESULT)=> {
48 | if (ERR) {
49 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR));
50 | } else {
51 | MODEL.userModel.findOne({
52 | $or: [
53 | {username: dataObj.username},
54 | {email: dataObj.username}
55 | ]
56 | }, {}, {lean:true}, (ERR, RESULT) => {
57 | if (ERR) {
58 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR));
59 | }else if(!RESULT){
60 | return RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.INVALID_USERNAME));
61 | }
62 | else{
63 | RESULT.roles === CONSTANTS.DATABASE.USER_ROLES.ADMIN ? NEXT() : RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.UNAUTHORIZED));
64 | }
65 | })
66 | }
67 | });
68 | };
69 |
70 | /********************************
71 | ****** User check model ********
72 | *********************************/
73 | velidateUser.userCheck = ( REQUEST, RESPONSE, NEXT )=>{
74 | let dataObj = REQUEST.query.username;
75 | if(REQUEST.query.username){
76 | dataObj = REQUEST.query;
77 | }else{
78 | dataObj = REQUEST.body;
79 | }
80 | COMMON_FUN.objProperties(dataObj, (ERR, RESULT)=> {
81 | if (ERR) {
82 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR));
83 | } else {
84 | MODEL.userModel.findOne({
85 | $or: [
86 | {username: dataObj.username},
87 | {email: dataObj.username}
88 | ]
89 | }, {}, {lean:true}, (ERR, RESULT) => {
90 | if (ERR) {
91 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR));
92 | }else if(!RESULT){
93 | return RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.INVALID_USERNAME));
94 | }
95 | else{
96 | RESULT.roles === CONSTANTS.DATABASE.USER_ROLES.USER ? NEXT() : RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.UNAUTHORIZED));
97 | }
98 | })
99 | }
100 | });
101 | };
102 |
103 | /* export userControllers */
104 | module.exports = velidateUser;
--------------------------------------------------------------------------------
/bin/swagger/swagger_Routes/user.js:
--------------------------------------------------------------------------------
1 |
2 | /**
3 | * @swagger
4 | * resourcePath: /User
5 | * description: All about API
6 | */
7 |
8 |
9 | /** login api
10 | * @swagger
11 | * path: /api/login
12 | * operations:
13 | * - httpMethod: GET
14 | * summary: Login with username/email and password
15 | * notes: Login user with username/email and password
16 | * responseClass: User
17 | * nickname: login
18 | * consumes:
19 | * - text/html
20 | * parameters:
21 | * - name: username
22 | * description: Your username here
23 | * paramType: query
24 | * required: true
25 | * dataType: string
26 | * - name: password
27 | * description: Your password
28 | * paramType: query
29 | * required: true
30 | * dataType: string
31 | */
32 |
33 |
34 |
35 | /** login api
36 | * @swagger
37 | * path: /api/register
38 | * operations:
39 | * - httpMethod: POST
40 | * summary: Signup with username, email and password
41 | * notes: Signup with username, email and password
42 | * responseClass: User
43 | * nickname: register_user
44 | * consumes:
45 | * - application/json
46 | * produces:
47 | * - application/json
48 | * parameters:
49 | * - in: body
50 | * description: User registration here
51 | * name: body
52 | * paramType: body
53 | * dataType: User
54 | * schema:
55 | * $ref: "#/models/User"
56 | *
57 | */
58 |
59 |
60 | /** login api
61 | * @swagger
62 | * path: /api/forgotPassword
63 | * operations:
64 | * - httpMethod: POST
65 | * summary: Forget password api for otp
66 | * notes: Returns an OTP for forget password
67 | * responseClass: FORGOT
68 | * nickname: register_user
69 | * consumes:
70 | * - application/json
71 | * produces:
72 | * - application/json
73 | * parameters:
74 | * - in: body
75 | * description: Returns an OTP for forget password
76 | * name: body
77 | * paramType: body
78 | * dataType: FORGOT
79 | * schema:
80 | * $ref: "#/models/FORGOT"
81 | *
82 | */
83 |
84 |
85 |
86 | /** login api
87 | * @swagger
88 | * path: /api/changePassword
89 | * operations:
90 | * - httpMethod: POST
91 | * summary: changePassword for users with OTP
92 | * notes: Change password api is used for changing password using OTP
93 | * responseClass: ChangePassword
94 | * nickname: change_password
95 | * consumes:
96 | * - application/json
97 | * produces:
98 | * - application/json
99 | * parameters:
100 | * - in: body
101 | * description: ChangePassword here
102 | * name: body
103 | * paramType: body
104 | * dataType: ChangePassword
105 | * schema:
106 | * $ref: "#/models/ChangePassword"
107 | *
108 | */
109 |
110 |
111 |
112 |
113 | /** file upload api
114 | * @swagger
115 | * path: /api/fileUpload
116 | * operations:
117 | * - httpMethod: POST
118 | * summary: Any Single file upload api
119 | * notes: file upload api for user
120 | * nickname: change_password
121 | * parameters:
122 | * - in: formData
123 | * name: file
124 | * dataType: file
125 | * required: true
126 | * description: The file to upload.
127 | *
128 | */
129 |
130 |
131 |
132 | /**
133 | * @swagger
134 | * models:
135 | * User:
136 | * id: User
137 | * properties:
138 | * username:
139 | * type: String
140 | * password:
141 | * type: String
142 | * email:
143 | * type: String
144 | * FORGOT:
145 | * id: FORGOT
146 | * properties:
147 | * email:
148 | * type: String
149 | * ChangePassword:
150 | * id: ChangePassword
151 | * properties:
152 | * email:
153 | * type: String
154 | * otp:
155 | * type: String
156 | * password:
157 | * type: String
158 | */
159 |
160 |
161 |
162 |
163 |
164 |
--------------------------------------------------------------------------------
/server/services/commonService.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by Radhey Shyam on 14/02/18.
3 | */
4 |
5 | "use strict";
6 | const commonFun = require("../util/commonFunction");
7 | let FS = require("fs");
8 | let CONFIG = require('../config');
9 | var multer = require('multer');
10 | let Path = require('path');
11 | var AWS = require("aws-sdk");
12 | var mime = require('mime-types')
13 | let GM = require('gm').subClass({imageMagick: true});
14 | var FsExtra = require('fs-extra');
15 |
16 |
17 | AWS.config.update({
18 | accessKeyId: CONFIG.awsConfig.accessKeyId,
19 | secretAccessKey: CONFIG.awsConfig.secretAccessKey,
20 | // region:' '
21 | });
22 | var s3 = new AWS.S3();
23 |
24 | /**
25 | * Storage for file in local machine
26 | */
27 | let storage = multer.diskStorage({
28 | destination: function (req, file, cb) {
29 | cb(null, './client/uploads/')
30 | },
31 | filename: function (req, file, cb) {
32 | let fileName = file.originalname.split('.');
33 | let fileExtension = fileName[fileName.length-1];
34 | cb(null, Date.now() + '.' + fileExtension);
35 | }
36 | });
37 |
38 | /** Upload single file **/
39 | const upload = multer({ storage: storage }).single('file');
40 |
41 | let commonService = {};
42 | /**
43 | * @param model mongodb model
44 | * @param criteria criteria for data finding
45 | * @param projection projection for filtering data according to requirement
46 | * @param callback return function
47 | */
48 | commonService.find = (model, criteria, projection, callback)=>{
49 | model.findOne(criteria, projection, (err, result)=>{
50 | if(err)
51 | return callback(commonFun.sendError(err));
52 | else
53 | return callback(null, commonFun.sendSuccess(result));
54 | })
55 | };
56 |
57 |
58 | /** Upload file **/
59 | commonService.fileUpload = (REQUEST, RESPONSE) => {
60 | return new Promise((resolve, reject) => {
61 |
62 | /** Upload pic locally first **/
63 | upload(REQUEST, RESPONSE, function (err) {
64 | if (err) {
65 | // An error occurred when uploading
66 | return reject(`Error: ${err}`);
67 | }
68 |
69 | /** File data **/
70 | let fileData = REQUEST.file,
71 | fileName = fileData.originalname.split('.'),
72 | fileExtension = fileName[fileName.length-1];
73 |
74 | fileName = Date.now() + '.' + fileExtension;
75 | let path = fileData.path;
76 |
77 | /** Profile and thumb **/
78 | fileData.original = "profile_" + fileName;
79 | fileData.thumb = "thumbe_" + fileName;
80 |
81 | /** Thumbnail image **/
82 | let finalArray = [{
83 | path: Path.resolve('.') + '/client/uploads/' + fileData.thumb,
84 | finalUrl: CONFIG.awsConfig.s3URL + fileData.thumb,
85 | }]
86 |
87 | /** Profile image **/
88 | finalArray.push({
89 | path: fileData.path,
90 | finalUrl: CONFIG.awsConfig.s3URL + fileData.original
91 | })
92 |
93 |
94 | /** Create thumb image locally **/
95 | commonService.createThumbImage(path, finalArray[0].path).then(result => {
96 |
97 | let functionsArray = [];
98 | finalArray.forEach(function (obj) {
99 | functionsArray.push(commonService.uploadFileS3(obj));
100 | });
101 |
102 | /** Upload image in s3 bucket **/
103 | return Promise.all(functionsArray).then(result => {
104 |
105 | commonService.deleteFile(finalArray[0].path);
106 | commonService.deleteFile(finalArray[1].path);
107 |
108 | return resolve({
109 | imgUrl: CONFIG.awsConfig.s3URL+fileData.original,
110 | thumb: CONFIG.awsConfig.s3URL+fileData.thumb
111 | });
112 |
113 | }).catch(error => {
114 | throw error;
115 | })
116 |
117 | }).catch(error => {
118 |
119 | reject(error);
120 | });
121 | });
122 | })
123 | }
124 |
125 | /** Create image **/
126 | commonService.createThumbImage = (originalPath, thumbnailPath) => {
127 |
128 | return new Promise((resolve, reject) => {
129 |
130 | var readStream = FS.createReadStream(originalPath);
131 | GM(readStream)
132 | .size({ bufferStream: true }, function (err, size) {
133 | if (size) {
134 | let height = 150;
135 | let width = (size.width * height)/size.height;
136 | this.thumb(width, height, thumbnailPath, 30,
137 | /* .autoOrient()
138 | .write(thumbnailPath1,*/ function (err, data) {
139 | console.log(data);
140 | err ? reject(err) : resolve(data);
141 | })
142 | }
143 | });
144 | });
145 | }
146 |
147 | /** Remove file **/
148 | commonService.deleteFile = (path) => {
149 | return FsExtra.remove(path);
150 | }
151 |
152 |
153 | /** Upload image to s3 bucket **/
154 | commonService.uploadFileS3 = (fileObj) => {
155 | return new Promise((resolve, reject) => {
156 |
157 | var fileName = Path.basename(fileObj.finalUrl);
158 | var stats = FS.statSync(fileObj.path);
159 |
160 | var fileSizeInBytes = stats["size"];
161 |
162 | FS.readFile(fileObj.path, (err, fileData) => {
163 | s3.putObject({
164 |
165 | Bucket: CONFIG.awsConfig.bucket,
166 | Key: fileName,
167 | Body: fileData,
168 | ContentType: mime.lookup(fileName)
169 |
170 | }, (err, data) => {
171 |
172 | err ? reject(err): resolve(data);
173 | });
174 | });
175 | })
176 | }
177 |
178 |
179 |
180 | /**
181 | * common model service exporting
182 | */
183 | module.exports = commonService;
184 |
--------------------------------------------------------------------------------
/bin/swagger/swagger_dependencies/swagger/lib/highlight.7.3.pack.js:
--------------------------------------------------------------------------------
1 | var hljs=new function(){function l(o){return o.replace(/&/gm,"&").replace(//gm,">")}function b(p){for(var o=p.firstChild;o;o=o.nextSibling){if(o.nodeName=="CODE"){return o}if(!(o.nodeType==3&&o.nodeValue.match(/\s+/))){break}}}function h(p,o){return Array.prototype.map.call(p.childNodes,function(q){if(q.nodeType==3){return o?q.nodeValue.replace(/\n/g,""):q.nodeValue}if(q.nodeName=="BR"){return"\n"}return h(q,o)}).join("")}function a(q){var p=(q.className+" "+q.parentNode.className).split(/\s+/);p=p.map(function(r){return r.replace(/^language-/,"")});for(var o=0;o"}while(x.length||v.length){var u=t().splice(0,1)[0];y+=l(w.substr(p,u.offset-p));p=u.offset;if(u.event=="start"){y+=s(u.node);r.push(u.node)}else{if(u.event=="stop"){var o,q=r.length;do{q--;o=r[q];y+=(""+o.nodeName.toLowerCase()+">")}while(o!=u.node);r.splice(q,1);while(q'+L[0]+""}else{r+=L[0]}N=A.lR.lastIndex;L=A.lR.exec(K)}return r+K.substr(N)}function z(){if(A.sL&&!e[A.sL]){return l(w)}var r=A.sL?d(A.sL,w):g(w);if(A.r>0){v+=r.keyword_count;B+=r.r}return''+r.value+""}function J(){return A.sL!==undefined?z():G()}function I(L,r){var K=L.cN?'':"";if(L.rB){x+=K;w=""}else{if(L.eB){x+=l(r)+K;w=""}else{x+=K;w=r}}A=Object.create(L,{parent:{value:A}});B+=L.r}function C(K,r){w+=K;if(r===undefined){x+=J();return 0}var L=o(r,A);if(L){x+=J();I(L,r);return L.rB?0:r.length}var M=s(A,r);if(M){if(!(M.rE||M.eE)){w+=r}x+=J();do{if(A.cN){x+=""}A=A.parent}while(A!=M.parent);if(M.eE){x+=l(r)}w="";if(M.starts){I(M.starts,"")}return M.rE?0:r.length}if(t(r,A)){throw"Illegal"}w+=r;return r.length||1}var F=e[D];f(F);var A=F;var w="";var B=0;var v=0;var x="";try{var u,q,p=0;while(true){A.t.lastIndex=p;u=A.t.exec(E);if(!u){break}q=C(E.substr(p,u.index-p),u[0]);p=u.index+q}C(E.substr(p));return{r:B,keyword_count:v,value:x,language:D}}catch(H){if(H=="Illegal"){return{r:0,keyword_count:0,value:l(E)}}else{throw H}}}function g(s){var o={keyword_count:0,r:0,value:l(s)};var q=o;for(var p in e){if(!e.hasOwnProperty(p)){continue}var r=d(p,s);r.language=p;if(r.keyword_count+r.r>q.keyword_count+q.r){q=r}if(r.keyword_count+r.r>o.keyword_count+o.r){q=o;o=r}}if(q.language){o.second_best=q}return o}function i(q,p,o){if(p){q=q.replace(/^((<[^>]+>|\t)+)/gm,function(r,v,u,t){return v.replace(/\t/g,p)})}if(o){q=q.replace(/\n/g,"
")}return q}function m(r,u,p){var v=h(r,p);var t=a(r);if(t=="no-highlight"){return}var w=t?d(t,v):g(v);t=w.language;var o=c(r);if(o.length){var q=document.createElement("pre");q.innerHTML=w.value;w.value=j(o,c(q),v)}w.value=i(w.value,u,p);var s=r.className;if(!s.match("(\\s|^)(language-)?"+t+"(\\s|$)")){s=s?(s+" "+t):t}r.innerHTML=w.value;r.className=s;r.result={language:t,kw:w.keyword_count,re:w.r};if(w.second_best){r.second_best={language:w.second_best.language,kw:w.second_best.keyword_count,re:w.second_best.r}}}function n(){if(n.called){return}n.called=true;Array.prototype.map.call(document.getElementsByTagName("pre"),b).filter(Boolean).forEach(function(o){m(o,hljs.tabReplace)})}function k(){window.addEventListener("DOMContentLoaded",n,false);window.addEventListener("load",n,false)}var e={};this.LANGUAGES=e;this.highlight=d;this.highlightAuto=g;this.fixMarkup=i;this.highlightBlock=m;this.initHighlighting=n;this.initHighlightingOnLoad=k;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|\\.|-|-=|/|/=|:|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.BE={b:"\\\\[\\s\\S]",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE],r:0};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE],r:0};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.inherit=function(q,r){var o={};for(var p in q){o[p]=q[p]}if(r){for(var p in r){o[p]=r[p]}}return o}}();hljs.LANGUAGES.xml=function(a){var c="[A-Za-z0-9\\._:-]+";var b={eW:true,c:[{cN:"attribute",b:c,r:0},{b:'="',rB:true,e:'"',c:[{cN:"value",b:'"',eW:true}]},{b:"='",rB:true,e:"'",c:[{cN:"value",b:"'",eW:true}]},{b:"=",c:[{cN:"value",b:"[^\\s/>]+"}]}]};return{cI:true,c:[{cN:"pi",b:"<\\?",e:"\\?>",r:10},{cN:"doctype",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},{cN:"comment",b:"",r:10},{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"",rE:true,sL:"css"}},{cN:"tag",b:"