├── .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+=("")}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:"|$)",e:">",k:{title:"style"},c:[b],starts:{e:"",rE:true,sL:"css"}},{cN:"tag",b:"|$)",e:">",k:{title:"script"},c:[b],starts:{e:"<\/script>",rE:true,sL:"javascript"}},{b:"<%",e:"%>",sL:"vbscript"},{cN:"tag",b:"",c:[{cN:"title",b:"[^ />]+"},b]}]}}(hljs);hljs.LANGUAGES.json=function(a){var e={literal:"true false null"};var d=[a.QSM,a.CNM];var c={cN:"value",e:",",eW:true,eE:true,c:d,k:e};var b={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:true,eE:true,c:[a.BE],i:"\\n",starts:c}],i:"\\S"};var f={b:"\\[",e:"\\]",c:[a.inherit(c,{cN:null})],i:"\\S"};d.splice(d.length,0,b,f);return{c:d,k:e,i:"\\S"}}(hljs); -------------------------------------------------------------------------------- /server/controller/userController.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Radhey Shyam on 14/02/18. 3 | */ 4 | "use strict"; 5 | 6 | 7 | /************************************************** 8 | ***** User controller for user business logic **** 9 | **************************************************/ 10 | let userController = {}; 11 | let MODEL = require("../models"); 12 | let COMMON_FUN = require("../util/commonFunction"); 13 | let SERVICE = require("../services/commonService"); 14 | let CONSTANTS = require("../util/constants"); 15 | let FS = require('fs'); 16 | 17 | /************************************************** 18 | ****** Upload image or media (under process) ***** 19 | **************************************************/ 20 | userController.upload = (REQUEST, RESPONSE)=> { 21 | 22 | /** Stream 23 | // let myReadStream = FS.createReadStream(__dirname + '/index.js'); 24 | // let myWriteStream = FS.createWriteStream( 'client/uploads/newfile.js' ); 25 | 26 | // myReadStream.on('data', (chunks) => { 27 | // console.log('new chunks received--- ', chunks); 28 | // myWriteStream.write(chunks); 29 | // }) 30 | */ 31 | 32 | // myReadStream.pipe(myWriteStream); 33 | 34 | SERVICE.fileUpload(REQUEST, RESPONSE).then(result => { 35 | 36 | return RESPONSE.jsonp({status: true, message:result}); 37 | }); 38 | }; 39 | 40 | 41 | /************************************************** 42 | ******************* Register User **************** 43 | **************************************************/ 44 | userController.registerUser = (REQUEST, RESPONSE)=>{ 45 | // RESPONSE.jsonp(REQUEST.body); 46 | let dataToSave = { ...REQUEST.body }; 47 | COMMON_FUN.encryptPswrd(dataToSave.password, (ERR, PASSWORD)=>{ 48 | if(ERR) 49 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 50 | else { 51 | dataToSave.password = PASSWORD; 52 | MODEL.userModel(dataToSave).save({},(ERR, RESULT) => { 53 | if(ERR) 54 | RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 55 | else{ 56 | let UserData = { 57 | email: RESULT.email, 58 | username: RESULT.username, 59 | roles: RESULT.roles 60 | }; 61 | RESPONSE.jsonp(COMMON_FUN.sendSuccess(CONSTANTS.STATUS_MSG.SUCCESS.DEFAULT, UserData)); 62 | } 63 | }); 64 | } 65 | }) 66 | 67 | }; 68 | 69 | 70 | /************************************************** 71 | ******************* Login User ******************* 72 | **************************************************/ 73 | userController.loginUser = (REQUEST, RESPONSE)=>{ 74 | 75 | let CRITERIA = {$or: [{username: REQUEST.query.username},{email: REQUEST.query.username}]}, 76 | PROJECTION = {__v : 0, createAt: 0}; 77 | 78 | /** find user is exists or not */ 79 | MODEL.userModel.findOne(CRITERIA, PROJECTION, {lean: true}).then((USER) => { 80 | return USER; 81 | }).then((USER)=>{ 82 | 83 | USER ? /** matching password */ 84 | COMMON_FUN.decryptPswrd(REQUEST.query.password, USER.password, (ERR, MATCHED)=>{ 85 | if( ERR ) 86 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 87 | else if (!MATCHED) 88 | return RESPONSE.jsonp(COMMON_FUN.sendSuccess(CONSTANTS.STATUS_MSG.ERROR.INCORRECT_PASSWORD)); 89 | else{ 90 | let dataToJwt = {username: USER.username, Date: Date.now, email: USER.email, role: USER.roles}, 91 | jwtToken = COMMON_FUN.createToken(dataToJwt); /** creating jwt token */ 92 | dataToJwt.token = jwtToken; 93 | return RESPONSE.jsonp(COMMON_FUN.sendSuccess(CONSTANTS.STATUS_MSG.SUCCESS.DEFAULT, dataToJwt)); 94 | } 95 | }) 96 | :RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.INVALID_EMAIL)); 97 | 98 | }).catch((err) => { 99 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)) 100 | }); 101 | }; 102 | 103 | /************************************************** 104 | ******************* Forget Password ************** 105 | **************************************************/ 106 | userController.forgotPassword = (REQUEST, RESPONSE)=>{ 107 | let CRITERIA = {email: REQUEST.body.email}, 108 | PROJECTION = {__v : 0, createAt: 0}; 109 | /** find user is exists or not */ 110 | MODEL.userModel.findOne(CRITERIA, PROJECTION, {lean: true}).then((USER) => { 111 | return USER; 112 | 113 | }).then((USER)=>{ 114 | /** 115 | * Generate Random number for OTP 116 | * */ 117 | const OTP = COMMON_FUN.generateRandomString(); 118 | 119 | const subject = CONSTANTS.MAIL_STATUS.OTP_SUB; 120 | USER.type = 0; // for forget password mail 121 | let saveToOTP= { 122 | userId: USER._id, 123 | userEmail: USER.email, 124 | otp: OTP 125 | }; 126 | RESPONSE.jsonp(COMMON_FUN.sendSuccess(CONSTANTS.STATUS_MSG.SUCCESS.CREATED, saveToOTP)); 127 | 128 | }).catch((ERR) => { 129 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)) 130 | }); 131 | }; 132 | 133 | /************************************************** 134 | ******************* Change Password ************** 135 | **************************************************/ 136 | userController.changePassword = async (REQUEST, RESPONSE)=>{ 137 | try { 138 | /* check user exist or not*/ 139 | let checkUserExist = await MODEL.userModel.findOne({email: REQUEST.body.email}, {}, {lean: true}); 140 | 141 | if (checkUserExist) { 142 | 143 | /********** encrypt password ********/ 144 | COMMON_FUN.encryptPswrd(REQUEST.body.password, (ERR, HASH) => { 145 | 146 | /********** update password in usermodel ********/ 147 | MODEL.userModel.update({email: REQUEST.body.email}, {$set: {password: HASH}}).then((SUCCESS) => { 148 | 149 | return RESPONSE.jsonp(COMMON_FUN.sendSuccess(CONSTANTS.STATUS_MSG.SUCCESS.UPDATED)); 150 | }).catch((ERR) => { 151 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 152 | }); 153 | }); 154 | } 155 | else{ 156 | return RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.INVALID_EMAIL)); 157 | } 158 | } catch (ERR) { 159 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 160 | } 161 | }; 162 | 163 | 164 | /************************************************** 165 | ********* change loggged in user password ******** 166 | **************************************************/ 167 | userController.changedlogedInPassword = (REQUEST, RESPONSE)=>{ 168 | let BODY = REQUEST.body; 169 | COMMON_FUN.objProperties(REQUEST.body, (ERR, RESULT)=> { 170 | if (ERR) { 171 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 172 | }else{ 173 | MODEL.userModel.findOne({email: REQUEST.body.username},{},{lean: true}).then(RESULT=>{ 174 | if(!RESULT) 175 | return RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.NOT_FOUND)); 176 | else{ 177 | COMMON_FUN.decryptPswrd(BODY.currentPassword, RESULT.password, (ERR, isMatched)=>{ 178 | if(ERR){ 179 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 180 | }else if(isMatched){ 181 | COMMON_FUN.encryptPswrd(BODY.newPassword, (ERR, HASH)=>{ 182 | if(ERR) 183 | return RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.INCORRECT_PASSWORD)); 184 | else{ 185 | MODEL.userModel.update({email: BODY.username},{$set: {password:HASH}},{}).then(SUCCESS=>{ 186 | return RESPONSE.jsonp(COMMON_FUN.sendSuccess(CONSTANTS.STATUS_MSG.SUCCESS.DEFAULT)); 187 | }).catch(ERR=>{ 188 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 189 | }); 190 | } 191 | }) 192 | }else{ 193 | return RESPONSE.jsonp(COMMON_FUN.sendError(CONSTANTS.STATUS_MSG.ERROR.INCORRECT_PASSWORD)); 194 | } 195 | }) 196 | } 197 | }).catch(ERR=>{ 198 | return RESPONSE.jsonp(COMMON_FUN.sendError(ERR)); 199 | }) 200 | } 201 | }) 202 | }; 203 | 204 | 205 | 206 | 207 | /* export userControllers */ 208 | module.exports = userController; -------------------------------------------------------------------------------- /bin/swagger/swagger_lib/swagger-express/index.js: -------------------------------------------------------------------------------- 1 | var _ = require('underscore'); 2 | var async = require('async'); 3 | var fs = require('fs'); 4 | var path = require('path'); 5 | var yaml = require('js-yaml'); 6 | var coffee = require('coffee-script'); 7 | var url = require('url'); 8 | 9 | var doctrine = require('doctrine'); 10 | var express = require('express'); 11 | var descriptor = {}; 12 | var resources = {}; 13 | 14 | /** 15 | * Read from yml file 16 | * @api private 17 | * @param {String} file 18 | * @param {Function} fn 19 | */ 20 | function readYml(file, fn) { 21 | var resource = require(path.resolve(process.cwd(), file)); 22 | var api = {}; 23 | 24 | api.resourcePath = resource.resourcePath; 25 | api.description = resource.description; 26 | descriptor.apis.push(api); 27 | resources[resource.resourcePath] = resource; 28 | 29 | fn(); 30 | } 31 | 32 | /** 33 | * Parse jsDoc from a js file 34 | * @api private 35 | * @param {String} file 36 | * @param {Function} fn 37 | */ 38 | function parseJsDocs(file, fn) { 39 | fs.readFile(file, function (err, data) { 40 | if (err) { 41 | fn(err); 42 | } 43 | 44 | var js = data.toString(); 45 | var regex = /\/\*\*([\s\S]*?)\*\//gm; 46 | var fragments = js.match(regex); 47 | var docs = []; 48 | 49 | if (!fragments) { 50 | fn(null, docs); 51 | return; 52 | } 53 | 54 | for (var i = 0; i < fragments.length; i++) { 55 | var fragment = fragments[i]; 56 | var doc = doctrine.parse(fragment, { unwrap: true }); 57 | 58 | docs.push(doc); 59 | 60 | if (i === fragments.length - 1) { 61 | fn(null, docs); 62 | } 63 | } 64 | }); 65 | } 66 | 67 | /** 68 | * Parse coffeeDoc from a coffee file 69 | * @api private 70 | * @param {String} file 71 | * @param {Function} fn 72 | */ 73 | function parseCoffeeDocs(file, fn) { 74 | fs.readFile(file, function (err, data) { 75 | if (err) { 76 | fn(err); 77 | } 78 | 79 | var js = coffee.compile(data.toString()); 80 | var regex = /\/\**([\s\S]*?)\*\//gm; 81 | var fragments = js.match(regex); 82 | var docs = []; 83 | 84 | for (var i = 0; i < fragments.length; i++) { 85 | var fragment = fragments[i]; 86 | var doc = doctrine.parse(fragment, { unwrap: true }); 87 | 88 | docs.push(doc); 89 | 90 | if (i === fragments.length - 1) { 91 | fn(null, docs); 92 | } 93 | } 94 | }); 95 | } 96 | 97 | /** 98 | * Get jsDoc tag with title '@swagger' 99 | * @api private 100 | * @param {Object} fragment 101 | * @param {Function} fn 102 | */ 103 | function getSwagger(fragment, fn) { 104 | for (var i = 0; i < fragment.tags.length; i++) { 105 | var tag = fragment.tags[i]; 106 | if ('swagger' === tag.title) { 107 | return yaml.safeLoadAll(tag.description, fn); 108 | } 109 | } 110 | 111 | return fn(false); 112 | } 113 | 114 | /** 115 | * Read from jsDoc 116 | * @api private 117 | * @param {String} file 118 | * @param {Function} fn 119 | */ 120 | function readJsDoc(file, fn) { 121 | parseJsDocs(file, function (err, docs) { 122 | 123 | if (err) { 124 | fn(err); 125 | } 126 | 127 | var resource = { apis: [] }; 128 | 129 | async.eachSeries(docs, function (doc, cb) { 130 | getSwagger(doc, function (api) { 131 | 132 | if (!api) { 133 | return cb(); 134 | } 135 | 136 | if (api.resourcePath) { 137 | descriptor.apis.push(api); 138 | resource.resourcePath = api.resourcePath; 139 | } else if (api.models) { 140 | resource.models = api.models; 141 | } else { 142 | resource.apis.push(api); 143 | } 144 | 145 | cb(); 146 | }); 147 | }, function (err) { 148 | resources[resource.resourcePath] = resource; 149 | fn(); 150 | }); 151 | }); 152 | } 153 | 154 | /** 155 | * Read from coffeeDoc 156 | * @api private 157 | * @param {String} file 158 | * @param {Function} fn 159 | */ 160 | function readCoffee(file, fn) { 161 | parseCoffeeDocs(file, function (err, docs) { 162 | 163 | if (err) { 164 | fn(err); 165 | } 166 | 167 | var resource = { apis: [] }; 168 | 169 | async.eachSeries(docs, function (doc, cb) { 170 | getSwagger(doc, function (api) { 171 | 172 | if (!api) { 173 | return cb(); 174 | } 175 | 176 | if (api.resourcePath) { 177 | descriptor.apis.push(api); 178 | resource.resourcePath = api.resourcePath; 179 | } else if (api.models) { 180 | resource.models = api.models; 181 | } else { 182 | resource.apis.push(api); 183 | } 184 | 185 | cb(); 186 | }); 187 | }, function (err) { 188 | resources[resource.resourcePath] = resource; 189 | fn(); 190 | }); 191 | }); 192 | } 193 | 194 | /** 195 | * Read API from file 196 | * @api private 197 | * @param {String} file 198 | * @param {Function} fn 199 | */ 200 | function readApi(file, fn) { 201 | var ext = path.extname(file); 202 | if ('.js' === ext) { 203 | readJsDoc(file, fn); 204 | } else if ('.yml' === ext) { 205 | readYml(file, fn); 206 | } else if ('.coffee' === ext) { 207 | readCoffee(file, fn); 208 | } else { 209 | throw new Error('Unsupported extension \'' + ext + '\''); 210 | } 211 | } 212 | 213 | /** 214 | * Generate Swagger documents 215 | * @api private 216 | * @param {Object} opt 217 | */ 218 | function generate(opt) { 219 | if (!opt) { 220 | throw new Error('\'option\' is required.'); 221 | } 222 | 223 | if (!opt.swaggerUI) { 224 | throw new Error('\'swaggerUI\' is required.'); 225 | } 226 | 227 | if (!opt.basePath) { 228 | throw new Error('\'basePath\' is required.'); 229 | } 230 | 231 | descriptor.basePath = opt.basePath; 232 | descriptor.apiVersion = (opt.apiVersion) ? opt.apiVersion : '1.0'; 233 | descriptor.swaggerVersion = descriptor.swagger = (opt.swaggerVersion) ? opt.swaggerVersion : '1.0'; 234 | descriptor.swaggerURL = (opt.swaggerURL) ? opt.swaggerURL : '/swagger'; 235 | descriptor.swaggerJSON = (opt.swaggerJSON) ? opt.swaggerJSON : '/api-docs.json'; 236 | descriptor.apis = []; 237 | 238 | if(opt.info) { 239 | descriptor.info = opt.info; 240 | } 241 | 242 | opt.apiVersion = descriptor.apiVersion; 243 | opt.swaggerVersion = descriptor.swaggerVersion; 244 | opt.swaggerURL = descriptor.swaggerURL; 245 | opt.swaggerJSON = descriptor.swaggerJSON; 246 | 247 | if (!opt.fullSwaggerJSONPath) { 248 | opt.fullSwaggerJSONPath = url.parse(opt.basePath + opt.swaggerJSON).path; 249 | } 250 | 251 | if (opt.apis) { 252 | async.forEachSeries(opt.apis, function(api, cb) { 253 | readApi(api, cb); 254 | }, function(err) { 255 | if(err) throw err; 256 | }); 257 | } 258 | } 259 | 260 | /** 261 | * Express middleware 262 | * @api public 263 | * @param {Object} app 264 | * @param {Object} opt 265 | * @return {Function} 266 | */ 267 | exports.init = function (app, opt) { 268 | 269 | // generate resources 270 | generate(opt); 271 | 272 | // Serve up swagger ui static assets 273 | var swHandler = express.static(opt.swaggerUI); 274 | 275 | // Serve up swagger ui interface. 276 | var swaggerURL = new RegExp('^'+ opt.swaggerURL +'(\/.*)?$'); 277 | 278 | app.get(swaggerURL, function (req, res, next) { 279 | if (req.url === opt.swaggerURL) { // express static barfs on root url w/o trailing slash 280 | res.writeHead(302, { 'Location' : req.url + '/' }); 281 | res.end(); 282 | return; 283 | } 284 | 285 | // take off leading /swagger so that connect locates file correctly 286 | req.url = req.url.substr(opt.swaggerURL.length); 287 | return swHandler(req, res, next); 288 | }); 289 | 290 | return function (req, res, next) { 291 | var match, resource, result; 292 | var regex = new RegExp('^'+ opt.fullSwaggerJSONPath +'(\/.*)?$'); 293 | 294 | match = regex.exec(req.path); 295 | 296 | if (match) { 297 | result = _.clone(descriptor); 298 | 299 | if (match[1]) { 300 | 301 | resource = resources[match[1]]; 302 | 303 | if (!resource) { 304 | //detect if it's express 4.x or 3.5.x 305 | return (res.sendStatus ? res.sendStatus(404) : res.send(404)); 306 | } 307 | 308 | result.resourcePath = resource.resourcePath; 309 | result.apis = resource.apis; 310 | result.models = resource.models; 311 | } else { 312 | result.apis = _.map(result.apis, function (api) { 313 | return { 314 | path: opt.swaggerJSON + api.resourcePath, 315 | description: api.description 316 | }; 317 | }); 318 | } 319 | 320 | if(typeof(opt.middleware) == 'function'){ 321 | opt.middleware(req, res); 322 | } 323 | 324 | return res.json(result); 325 | } 326 | return next(); 327 | }; 328 | }; 329 | 330 | exports.descriptor = descriptor; 331 | exports.resources = resources; 332 | -------------------------------------------------------------------------------- /server/util/commonFunction.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Radhey Shyam on 11/14/17. 3 | */ 4 | 5 | let CONSTANTS = require('./constants'); 6 | const MONGOOSE = require('mongoose'); 7 | const BCRYPT = require("bcryptjs"); 8 | const JWT = require("jsonwebtoken"); 9 | const randomstring = require("randomstring"); 10 | 11 | 12 | /** 13 | * incrypt password in case user login implementation 14 | * @param {*} userPassword 15 | * @param {*} cb 16 | */ 17 | let encryptPswrd = (userPassword, cb) => { 18 | BCRYPT.hash(userPassword, 10, (err, encryptPswrd) => { 19 | return err ? cb(err) : cb(null, encryptPswrd); 20 | }); 21 | }; 22 | 23 | 24 | 25 | /** 26 | * @param {** decrypt password in case user login implementation} payloadPassword 27 | * @param {*} userPassword 28 | * @param {*} cb 29 | */ 30 | let decryptPswrd = (payloadPassword, userPassword, cb) => { 31 | BCRYPT.compare(payloadPassword, userPassword, (err, isMatched) => { 32 | return err ? cb(err) : cb(null, isMatched); 33 | }); 34 | }; 35 | 36 | 37 | /** To capitalize a stirng ***/ 38 | String.prototype.capitalize = function() { 39 | return this.charAt(0).toUpperCase() + this.slice(1); 40 | }; 41 | 42 | 43 | 44 | /** 45 | * if will take any kind of error and make it in embedded format as per the project require 46 | * @param {*} data (data could be object or string depecds upon the error type) 47 | */ 48 | let sendError = function (data) { 49 | 50 | let errorToSend = '', 51 | errorCode = data.code ? data.code : 0; 52 | 53 | if (typeof data === 'object' && data.hasOwnProperty('statusCode') && data.hasOwnProperty('customMessage')) { 54 | data.data = null; 55 | return data; 56 | } 57 | else { 58 | if (typeof data === 'object') { 59 | 60 | if (data.name === 'MongoError' || data.name === 'BulkWriteError' ) { 61 | 62 | errorToSend += CONSTANTS.STATUS_MSG.ERROR.DB_ERROR.customMessage; 63 | 64 | if (data.code = 11000) { 65 | 66 | let duplicateValue = data.errmsg.split(":"); 67 | duplicateValue = duplicateValue[2].split("_1")[0]; 68 | duplicateValue = duplicateValue.trim().capitalize(); 69 | duplicateValue += CONSTANTS.ERROR_MESSAGE.isAlreadyExist; 70 | errorToSend = duplicateValue; 71 | } 72 | } else if (data.name === 'ApplicationError') { 73 | 74 | errorToSend += CONSTANTS.STATUS_MSG.ERROR.APP_ERROR.customMessage + ' : '; 75 | } else if (data.name === 'ValidationError') { 76 | 77 | let keys = Object.keys(data.errors, []); 78 | errorToSend = data.errors[keys[0]].message; 79 | errorCode = 422; 80 | errorToSend = replaceValueFromString(errorToSend, 'Path',''); 81 | errorToSend = replaceValueFromString(errorToSend, /\`/g, ''); 82 | errorToSend = replaceValueFromString(errorToSend, /\./g, ''); 83 | errorToSend = errorToSend.trim(); 84 | errorToSend = errorToSend.capitalize(); 85 | 86 | } else if (data.name === 'CastError') { 87 | 88 | errorToSend += CONSTANTS.STATUS_MSG.ERROR.DB_ERROR.customMessage + CONSTANTS.STATUS_MSG.ERROR.INVALID_ID.customMessage + data.value; 89 | } else { 90 | errorToSend = data.message; 91 | } 92 | } else { 93 | errorToSend = data 94 | } 95 | let customErrorMessage = errorToSend; 96 | if (typeof customErrorMessage == 'string') { 97 | if (errorToSend.indexOf("[") > -1) { 98 | customErrorMessage = errorToSend.substr(errorToSend.indexOf("[")); 99 | } 100 | customErrorMessage = customErrorMessage && customErrorMessage.replace(/"/g, ''); 101 | customErrorMessage = customErrorMessage && customErrorMessage.replace('[', ''); 102 | customErrorMessage = customErrorMessage && customErrorMessage.replace(']', ''); 103 | } 104 | return {statusCode: errorCode ? errorCode : 400, customMessage: customErrorMessage, data: null } 105 | } 106 | }; 107 | 108 | 109 | 110 | /** 111 | * Send success message to frontend 112 | * @param {*} successMsg 113 | * @param {*} data 114 | */ 115 | let sendSuccess = (successMsg, data)=> { 116 | successMsg = successMsg || CONSTANTS.STATUS_MSG.SUCCESS.DEFAULT.customMessage; 117 | if (typeof successMsg == 'object' && successMsg.hasOwnProperty('statusCode') && successMsg.hasOwnProperty('customMessage')) { 118 | return { statusCode: successMsg.statusCode, customMessage: successMsg.customMessage, data: data || null }; 119 | } else { 120 | return { statusCode: 200, customMessage: successMsg, data: data || null }; 121 | } 122 | }; 123 | 124 | 125 | 126 | /** 127 | * Check duplicate value in array 128 | * @param {*} request 129 | * @param {*} reply 130 | * @param {*} source 131 | * @param {*} error 132 | */ 133 | let checkDuplicateValuesInArray = (array)=> { 134 | let storeArray = []; 135 | let duplicateFlag = false; 136 | if(array && array.length>0){ 137 | for (let i=0; i { 155 | return randomstring.generate({ 156 | length: 5, 157 | charset: 'numeric' 158 | }); 159 | }; 160 | 161 | 162 | 163 | /** 164 | * Filter the array 165 | * @param {*} array 166 | */ 167 | let filterArray = (array) =>{ 168 | return array.filter(function (n) { 169 | return n !== undefined && n !== '' 170 | }); 171 | }; 172 | 173 | 174 | 175 | /** 176 | * sanitizer for spliting a string corresponding to space if string has value otherwise it will join the space in it 177 | * @param {*} string 178 | */ 179 | let sanitizeName = (string) => { 180 | return filterArray(string && string.split(' ') || []).join(' ') 181 | }; 182 | 183 | 184 | 185 | /** 186 | * Verify email is in correct format or not 187 | * @param {*} string 188 | */ 189 | let verifyEmailFormat = (email)=> { 190 | return validator.isEmail(email); 191 | }; 192 | 193 | 194 | 195 | /************************************** 196 | * check all fields are filed with *** 197 | *** values in request body or not ****/ 198 | let objProperties = (obj, callback)=>{ 199 | for (i in obj) { 200 | if (!obj[i]) { 201 | return callback(i+CONSTANTS.STATUS_MSG.ERROR.CUSTOME_ERROR.customMessage); 202 | } 203 | else if(typeof obj[i] == "object"){ 204 | for (j in obj[i]) { 205 | if (!obj[i][j]) { 206 | return callback(j+CONSTANTS.STATUS_MSG.ERROR.CUSTOME_ERROR.customMessage); 207 | } 208 | } 209 | } 210 | } 211 | return callback(null); 212 | }; 213 | 214 | 215 | 216 | /** check all fields are available */ 217 | let objToArray = (obj)=>{ 218 | let arr = []; 219 | for (i in obj) { 220 | if(typeof obj[i] == "object"){ 221 | for (j in obj[i]) { 222 | arr.push(obj[i][j]); 223 | } 224 | }else{ 225 | arr.push(obj[i]); 226 | } 227 | } 228 | return arr; 229 | }; 230 | 231 | 232 | 233 | /** 234 | * @param {*} errObj error obj from constants 235 | * @param {*} customMsg custom new msg 236 | * @param {*} callback callback back to api || controller || service || routes 237 | */ 238 | let customErrorResponse = (errObj, customMsg, callback)=>{ 239 | errObj.message = customMsg; 240 | callback(errObj); 241 | }; 242 | 243 | 244 | 245 | /** used for converting string id to mongoose object id */ 246 | let convertIdToMongooseId = (stringId)=>{ 247 | return MONGOOSE.Types.ObjectId(stringId); 248 | }; 249 | 250 | 251 | 252 | 253 | /** create jsonwebtoken **/ 254 | let createToken = (objData)=>{ 255 | return JWT.sign(objData, CONSTANTS.SERVER.JWT_SECRET_KEY , { expiresIn: 1 }); 256 | }; 257 | 258 | 259 | 260 | /*search filter*/ 261 | let dataFilter = (data, cb)=>{ 262 | let CRITERIA = {}; 263 | data.type = Number(data.type); 264 | switch(data.filteredData){ 265 | case "status" : CRITERIA = { [data.filteredData]: data.type }; 266 | cb(null, CRITERIA); 267 | break; 268 | default: 269 | cb(null, CRITERIA); 270 | break; 271 | } 272 | }; 273 | 274 | 275 | /** 276 | * replace . with : 277 | */ 278 | let replaceValueFromString = (stringValue, valueToReplace, value) => { 279 | /** for special character ayou have to pass /\./g, **/ 280 | return stringValue.replace(valueToReplace, value); 281 | }; 282 | 283 | 284 | 285 | /*************************************** 286 | **** Logger for error and success ***** 287 | ***************************************/ 288 | let messageLogs = (error, success) => { 289 | if(error) 290 | console.log(`\x1b[31m`+error); 291 | else 292 | console.log(`\x1b[32m`+success); 293 | }; 294 | 295 | 296 | /*exporting all object from here*/ 297 | module.exports = { 298 | sendError : sendError, 299 | sendSuccess : sendSuccess, 300 | encryptPswrd : encryptPswrd, 301 | decryptPswrd : decryptPswrd, 302 | checkDuplicateValuesInArray : checkDuplicateValuesInArray, 303 | verifyEmailFormat : verifyEmailFormat, 304 | filterArray : filterArray, 305 | sanitizeName : sanitizeName, 306 | customErrorResponse : customErrorResponse, 307 | convertIdToMongooseId : convertIdToMongooseId, 308 | objProperties : objProperties, 309 | createToken : createToken, 310 | generateRandomString : generateRandomString, 311 | objToArray : objToArray, 312 | dataFilter : dataFilter, 313 | replaceValueFromString : replaceValueFromString, 314 | messageLogs : messageLogs 315 | }; -------------------------------------------------------------------------------- /bin/swagger/swagger_dependencies/swagger/lib/underscore-min.js: -------------------------------------------------------------------------------- 1 | // Underscore.js 1.3.3 2 | // (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. 3 | // Underscore is freely distributable under the MIT license. 4 | // Portions of Underscore are inspired or borrowed from Prototype, 5 | // Oliver Steele's Functional, and John Resig's Micro-Templating. 6 | // For all details and documentation: 7 | // http://documentcloud.github.com/underscore 8 | (function(){function r(a,c,d){if(a===c)return 0!==a||1/a==1/c;if(null==a||null==c)return a===c;a._chain&&(a=a._wrapped);c._chain&&(c=c._wrapped);if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return!1;switch(e){case "[object String]":return a==""+c;case "[object Number]":return a!=+a?c!=+c:0==a?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source== 9 | c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if("object"!=typeof a||"object"!=typeof c)return!1;for(var f=d.length;f--;)if(d[f]==a)return!0;d.push(a);var f=0,g=!0;if("[object Array]"==e){if(f=a.length,g=f==c.length)for(;f--&&(g=f in a==f in c&&r(a[f],c[f],d)););}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return!1;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&r(a[h],c[h],d))))break;if(g){for(h in c)if(b.has(c,h)&&!f--)break; 10 | g=!f}}d.pop();return g}var s=this,I=s._,o={},k=Array.prototype,p=Object.prototype,i=k.slice,J=k.unshift,l=p.toString,K=p.hasOwnProperty,y=k.forEach,z=k.map,A=k.reduce,B=k.reduceRight,C=k.filter,D=k.every,E=k.some,q=k.indexOf,F=k.lastIndexOf,p=Array.isArray,L=Object.keys,t=Function.prototype.bind,b=function(a){return new m(a)};"undefined"!==typeof exports?("undefined"!==typeof module&&module.exports&&(exports=module.exports=b),exports._=b):s._=b;b.VERSION="1.3.3";var j=b.each=b.forEach=function(a, 11 | c,d){if(a!=null)if(y&&a.forEach===y)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e2;a==null&&(a=[]);if(A&& 12 | a.reduce===A){e&&(c=b.bind(c,e));return f?a.reduce(c,d):a.reduce(c)}j(a,function(a,b,i){if(f)d=c.call(e,d,a,b,i);else{d=a;f=true}});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(B&&a.reduceRight===B){e&&(c=b.bind(c,e));return f?a.reduceRight(c,d):a.reduceRight(c)}var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=function(a, 13 | c,b){var e;G(a,function(a,g,h){if(c.call(b,a,g,h)){e=a;return true}});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(C&&a.filter===C)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(D&&a.every===D)return a.every(c,b);j(a,function(a,g,h){if(!(e=e&&c.call(b, 14 | a,g,h)))return o});return!!e};var G=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(E&&a.some===E)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return o});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;if(q&&a.indexOf===q)return a.indexOf(c)!=-1;return b=G(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck= 15 | function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a)&&a[0]===+a[0])return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a)&&a[0]===+a[0])return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;bd?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]}; 17 | j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||(d=b.identity);for(var e=0,f=a.length;e>1;d(a[g])=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1),true);return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a= 20 | i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e=0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=L||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&& 25 | c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.pick=function(a){var c={};j(b.flatten(i.call(arguments,1)),function(b){b in a&&(c[b]=a[b])});return c};b.defaults=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return r(a,b,[])};b.isEmpty= 26 | function(a){if(a==null)return true;if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=p||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};b.isArguments=function(a){return l.call(a)=="[object Arguments]"};b.isArguments(arguments)||(b.isArguments=function(a){return!(!a||!b.has(a,"callee"))});b.isFunction=function(a){return l.call(a)=="[object Function]"}; 27 | b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isFinite=function(a){return b.isNumber(a)&&isFinite(a)};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a, 28 | b){return K.call(a,b)};b.noConflict=function(){s._=I;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.result=function(a,c){if(a==null)return null;var d=a[c];return b.isFunction(d)?d.call(a):d};b.mixin=function(a){j(b.functions(a),function(c){M(c,b[c]=a[c])})};var N=0;b.uniqueId= 29 | function(a){var b=N++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var u=/.^/,n={"\\":"\\","'":"'",r:"\r",n:"\n",t:"\t",u2028:"\u2028",u2029:"\u2029"},v;for(v in n)n[n[v]]=v;var O=/\\|'|\r|\n|\t|\u2028|\u2029/g,P=/\\(\\|'|r|n|t|u2028|u2029)/g,w=function(a){return a.replace(P,function(a,b){return n[b]})};b.template=function(a,c,d){d=b.defaults(d||{},b.templateSettings);a="__p+='"+a.replace(O,function(a){return"\\"+n[a]}).replace(d.escape|| 30 | u,function(a,b){return"'+\n_.escape("+w(b)+")+\n'"}).replace(d.interpolate||u,function(a,b){return"'+\n("+w(b)+")+\n'"}).replace(d.evaluate||u,function(a,b){return"';\n"+w(b)+"\n;__p+='"})+"';\n";d.variable||(a="with(obj||{}){\n"+a+"}\n");var a="var __p='';var print=function(){__p+=Array.prototype.join.call(arguments, '')};\n"+a+"return __p;\n",e=new Function(d.variable||"obj","_",a);if(c)return e(c,b);c=function(a){return e.call(this,a,b)};c.source="function("+(d.variable||"obj")+"){\n"+a+"}";return c}; 31 | b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var x=function(a,c){return c?b(a).chain():a},M=function(a,c){m.prototype[a]=function(){var a=i.call(arguments);J.call(a,this._wrapped);return x(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return x(d, 32 | this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return x(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.chain=function(){this._chain=true;return this};m.prototype.value=function(){return this._wrapped}}).call(this); 33 | -------------------------------------------------------------------------------- /bin/swagger/swagger_dependencies/swagger/lib/backbone-min.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 0.9.2 2 | 3 | // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. 4 | // Backbone may be freely distributed under the MIT license. 5 | // For all details and documentation: 6 | // http://backbonejs.org 7 | (function(){var l=this,y=l.Backbone,z=Array.prototype.slice,A=Array.prototype.splice,g;g="undefined"!==typeof exports?exports:l.Backbone={};g.VERSION="0.9.2";var f=l._;!f&&"undefined"!==typeof require&&(f=require("underscore"));var i=l.jQuery||l.Zepto||l.ender;g.setDomLibrary=function(a){i=a};g.noConflict=function(){l.Backbone=y;return this};g.emulateHTTP=!1;g.emulateJSON=!1;var p=/\s+/,k=g.Events={on:function(a,b,c){var d,e,f,g,j;if(!b)return this;a=a.split(p);for(d=this._callbacks||(this._callbacks= 8 | {});e=a.shift();)f=(j=d[e])?j.tail:{},f.next=g={},f.context=c,f.callback=b,d[e]={tail:g,next:j?j.next:f};return this},off:function(a,b,c){var d,e,h,g,j,q;if(e=this._callbacks){if(!a&&!b&&!c)return delete this._callbacks,this;for(a=a?a.split(p):f.keys(e);d=a.shift();)if(h=e[d],delete e[d],h&&(b||c))for(g=h.tail;(h=h.next)!==g;)if(j=h.callback,q=h.context,b&&j!==b||c&&q!==c)this.on(d,j,q);return this}},trigger:function(a){var b,c,d,e,f,g;if(!(d=this._callbacks))return this;f=d.all;a=a.split(p);for(g= 9 | z.call(arguments,1);b=a.shift();){if(c=d[b])for(e=c.tail;(c=c.next)!==e;)c.callback.apply(c.context||this,g);if(c=f){e=c.tail;for(b=[b].concat(g);(c=c.next)!==e;)c.callback.apply(c.context||this,b)}}return this}};k.bind=k.on;k.unbind=k.off;var o=g.Model=function(a,b){var c;a||(a={});b&&b.parse&&(a=this.parse(a));if(c=n(this,"defaults"))a=f.extend({},c,a);b&&b.collection&&(this.collection=b.collection);this.attributes={};this._escapedAttributes={};this.cid=f.uniqueId("c");this.changed={};this._silent= 10 | {};this._pending={};this.set(a,{silent:!0});this.changed={};this._silent={};this._pending={};this._previousAttributes=f.clone(this.attributes);this.initialize.apply(this,arguments)};f.extend(o.prototype,k,{changed:null,_silent:null,_pending:null,idAttribute:"id",initialize:function(){},toJSON:function(){return f.clone(this.attributes)},get:function(a){return this.attributes[a]},escape:function(a){var b;if(b=this._escapedAttributes[a])return b;b=this.get(a);return this._escapedAttributes[a]=f.escape(null== 11 | b?"":""+b)},has:function(a){return null!=this.get(a)},set:function(a,b,c){var d,e;f.isObject(a)||null==a?(d=a,c=b):(d={},d[a]=b);c||(c={});if(!d)return this;d instanceof o&&(d=d.attributes);if(c.unset)for(e in d)d[e]=void 0;if(!this._validate(d,c))return!1;this.idAttribute in d&&(this.id=d[this.idAttribute]);var b=c.changes={},h=this.attributes,g=this._escapedAttributes,j=this._previousAttributes||{};for(e in d){a=d[e];if(!f.isEqual(h[e],a)||c.unset&&f.has(h,e))delete g[e],(c.silent?this._silent: 12 | b)[e]=!0;c.unset?delete h[e]:h[e]=a;!f.isEqual(j[e],a)||f.has(h,e)!=f.has(j,e)?(this.changed[e]=a,c.silent||(this._pending[e]=!0)):(delete this.changed[e],delete this._pending[e])}c.silent||this.change(c);return this},unset:function(a,b){(b||(b={})).unset=!0;return this.set(a,null,b)},clear:function(a){(a||(a={})).unset=!0;return this.set(f.clone(this.attributes),a)},fetch:function(a){var a=a?f.clone(a):{},b=this,c=a.success;a.success=function(d,e,f){if(!b.set(b.parse(d,f),a))return!1;c&&c(b,d)}; 13 | a.error=g.wrapError(a.error,b,a);return(this.sync||g.sync).call(this,"read",this,a)},save:function(a,b,c){var d,e;f.isObject(a)||null==a?(d=a,c=b):(d={},d[a]=b);c=c?f.clone(c):{};if(c.wait){if(!this._validate(d,c))return!1;e=f.clone(this.attributes)}a=f.extend({},c,{silent:!0});if(d&&!this.set(d,c.wait?a:c))return!1;var h=this,i=c.success;c.success=function(a,b,e){b=h.parse(a,e);if(c.wait){delete c.wait;b=f.extend(d||{},b)}if(!h.set(b,c))return false;i?i(h,a):h.trigger("sync",h,a,c)};c.error=g.wrapError(c.error, 14 | h,c);b=this.isNew()?"create":"update";b=(this.sync||g.sync).call(this,b,this,c);c.wait&&this.set(e,a);return b},destroy:function(a){var a=a?f.clone(a):{},b=this,c=a.success,d=function(){b.trigger("destroy",b,b.collection,a)};if(this.isNew())return d(),!1;a.success=function(e){a.wait&&d();c?c(b,e):b.trigger("sync",b,e,a)};a.error=g.wrapError(a.error,b,a);var e=(this.sync||g.sync).call(this,"delete",this,a);a.wait||d();return e},url:function(){var a=n(this,"urlRoot")||n(this.collection,"url")||t(); 15 | return this.isNew()?a:a+("/"==a.charAt(a.length-1)?"":"/")+encodeURIComponent(this.id)},parse:function(a){return a},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return null==this.id},change:function(a){a||(a={});var b=this._changing;this._changing=!0;for(var c in this._silent)this._pending[c]=!0;var d=f.extend({},a.changes,this._silent);this._silent={};for(c in d)this.trigger("change:"+c,this,this.get(c),a);if(b)return this;for(;!f.isEmpty(this._pending);){this._pending= 16 | {};this.trigger("change",this,a);for(c in this.changed)!this._pending[c]&&!this._silent[c]&&delete this.changed[c];this._previousAttributes=f.clone(this.attributes)}this._changing=!1;return this},hasChanged:function(a){return!arguments.length?!f.isEmpty(this.changed):f.has(this.changed,a)},changedAttributes:function(a){if(!a)return this.hasChanged()?f.clone(this.changed):!1;var b,c=!1,d=this._previousAttributes,e;for(e in a)if(!f.isEqual(d[e],b=a[e]))(c||(c={}))[e]=b;return c},previous:function(a){return!arguments.length|| 17 | !this._previousAttributes?null:this._previousAttributes[a]},previousAttributes:function(){return f.clone(this._previousAttributes)},isValid:function(){return!this.validate(this.attributes)},_validate:function(a,b){if(b.silent||!this.validate)return!0;var a=f.extend({},this.attributes,a),c=this.validate(a,b);if(!c)return!0;b&&b.error?b.error(this,c,b):this.trigger("error",this,c,b);return!1}});var r=g.Collection=function(a,b){b||(b={});b.model&&(this.model=b.model);b.comparator&&(this.comparator=b.comparator); 18 | this._reset();this.initialize.apply(this,arguments);a&&this.reset(a,{silent:!0,parse:b.parse})};f.extend(r.prototype,k,{model:o,initialize:function(){},toJSON:function(a){return this.map(function(b){return b.toJSON(a)})},add:function(a,b){var c,d,e,g,i,j={},k={},l=[];b||(b={});a=f.isArray(a)?a.slice():[a];c=0;for(d=a.length;c=b))this.iframe=i('