Guest User

Untitled

a guest
Oct 1st, 2017
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let fs      = require('fs'),
  2.     os      = require('os'),
  3.     path    = require('path'),
  4.  
  5.     winston = require('winston'),
  6.     express = require('express');
  7. /**
  8.  * Returns an Application.
  9.  * @param {object} options the parent directory
  10.  * @returns {Application} the Application function.
  11.  */
  12. let Application = function Application ( options ) {
  13.   let opts                  = options || {},
  14.       directoryInformation  = opts['directoryInformation'],
  15.       //sys argv options         :> .-. ;-;
  16.       // verbosity , v , default:info,
  17.       argv                  = opts['argv'],
  18.       verbosity             = opts['argv']['verbosity'],  /* ;-; 26:me.config */
  19.  
  20.       me = this;
  21.  
  22.       // me.viewDirectories = [];
  23.       // or put it in me._init();
  24.       me._init(opts);
  25. /*<-Class related
  26.   Function Related
  27.               Log Related
  28.                   Tab delimited beautify standard */
  29.   me.config       = require(path.join(directoryInformation['Etc']['EtcDirectory'],
  30.                     'config.json'));
  31.  
  32.   me.logger       = me.initLogManager({'directoryInformation': directoryInformation,
  33.                     'config':me.config});
  34.  
  35.               me.logger.log('info',argv);
  36.               me.logger.log('info', 'Application CTOR( options ) { ... }');
  37.  
  38.   me.app          = me.initExpress({'directoryInformation': directoryInformation,
  39.                     'config':me.config});
  40.  
  41.           me.viewDirectories.push(directoryInformation['Application']['TemplatesDirectory']);
  42.  
  43.   me.db           = me.initDB({"application": me.app,
  44.                     'directoryInformation': directoryInformation,
  45.                     'config':me.config,
  46.                     'logger':me.logger});
  47.  
  48.   me.assets       = me.initAssets({"application": me.app,
  49.                     'directoryInformation': directoryInformation,
  50.                     'config':me.config,
  51.                     'logger':me.logger,
  52.                     "datastore": me.db });
  53.  
  54.   me.extensions   = me.initExtensions({"application": me.app,
  55.                     'directoryInformation': directoryInformation,
  56.                     'config':me.config,
  57.                     'logger':me.logger,
  58.                     "datastore": me.db,
  59.                     "viewDirectories": me.viewDirectories});
  60.  
  61.   me.db.initialize({'application': me.app,
  62.                     'directoryInformation': directoryInformation,
  63.                     'config': me.config,
  64.                     'logger':me.logger});
  65.  
  66.   me.initRoutes({"application": me.app,
  67.                     "directoryInformation": directoryInformation,
  68.                     "config": me.config,
  69.                     'logger':me.logger,
  70.                     "datastore": me.db});
  71. };
  72. /**
  73.  * Initializes the Application object's member variables.
  74.  * @param {object} options the parent directory
  75.  * @returns {Application} the Application function.
  76.  */
  77. Application.prototype._init = function _init ( options ) {
  78.   let opts                  = options || {},
  79.       directoryInformation  = opts['directoryInformation'],
  80.       //sys argv options         :> .-. ;-;
  81.       // verbosity , v , default:info,
  82.       argv                  = opts['argv'],
  83.       verbosity             = opts['argv']['verbosity'],  /* ;-; 26:me.config */
  84.  
  85.       me = this;
  86. /*<-Class related
  87.   Function Related
  88.               Log Related
  89.                   Tab delimited beautify standard */
  90.   me.viewDirectories = [];
  91. }
  92. /**
  93.  * Returns an Winston Logger Object.
  94.  * @param {object} options the parent directory
  95.  * @return {winston} the Logger Object.
  96.  */
  97. Application.prototype.initLogManager = function initLogManager ( options ) {
  98.   let opts                  = options || {},
  99.       directoryInformation  = opts['directoryInformation'],
  100.       config                = opts['config'],
  101.  
  102.       me = this;
  103.  
  104.   let winston = require('winston'); // +++ check goto win
  105.   return new winston.Logger({
  106.     level: config['logger']['verbosity'],
  107.     transports: [
  108.       new (winston.transports.Console)({colorize: true}),
  109.       new (winston.transports.File)({ filename: path.join(directoryInformation['Var']['Log']['LogDirectory'],'log.json') })
  110.     ]
  111.   });
  112. };
  113. /**
  114.  * Returns an Express Application Object.
  115.  * @param {object} options the parent directory
  116.  * @return {express} the Application function.
  117.  */
  118. Application.prototype.initExpress = function initExpress ( options ) {
  119.   let opts                  = options || {},
  120.       directoryInformation  = opts['directoryInformation'],
  121.       config                = opts['config'],
  122.  
  123.       me = this;
  124. /*<-Class related
  125.   Function Related
  126.               Log Related
  127.                   Tab delimited beautify standard */
  128.               me.logger.log('info','Application.initDB(' + options +')');
  129.  
  130.   let app = express();
  131.  
  132.   let bodyParser      =require('body-parser'),
  133.       cookieParser    =require('cookie-parser'),
  134.       expressSession  =require('express-session');
  135.  
  136.   app.locals.pretty   = true;
  137.  
  138.   app.use(express.static(directoryInformation['Application']['StaticDirectory']));
  139.  
  140.   app.use(bodyParser.urlencoded({extended:false}));
  141.   app.use(bodyParser.json({inflate:true}));
  142.   app.use(cookieParser());
  143.   app.use(expressSession({
  144.     secret: 'keyboard cat',
  145.     resave: false,
  146.     saveUninitialized: false
  147.   }));
  148.  
  149.   app.use(require('connect-flash')());
  150.   app.use(function (req, res, next) {
  151.     res.locals.messages = require('express-messages')(req, res);
  152.     next();
  153.   });
  154.  
  155.   app.use(function(req,res,next) {
  156.     //request.headers['user-agent']
  157.     console.log(req.get('user-agent'));
  158.     next();
  159.   });
  160.  
  161.   app.set('views', me.viewDirectories );
  162.   app.set('view engine', 'pug');
  163.  
  164.   return app;
  165. };
  166. /**
  167.  * Returns the Datastore Object.
  168.  * @param {object} options the parent directory
  169.  * @return {express} the instantiated Datastore object.
  170.  */
  171. Application.prototype.initDB = function initDB ( options ) {
  172.   let opts                  = options || {},
  173.       application           = opts['application'],
  174.       directoryInformation  = opts['directoryInformation'],
  175.       config                = opts['config'],
  176.  
  177.       me = this;
  178. /*<-Class related
  179.   Function Related
  180.               Log Related
  181.                   Tab delimited beautify standard */
  182.               me.logger.log('info','ApplicationFactory.initDB(' + options +')');
  183.  
  184.   let DataStore = require(
  185.     path.join ( opts ['directoryInformation'].baseDirectory , path.join ( 'Datastore' , 'index.js' ) )
  186.   );
  187.  
  188.   let datastore = new DataStore(opts);
  189.   // Here's the chance to alter the datastore before sending it to the main Application Object.
  190.  
  191.   return datastore;
  192. };
  193. /**
  194.  * Returns the Datastore Object.
  195.  * @param {object} options the parent directory
  196.  * @return {express} the instantiated Datastore object.
  197.  */
  198. Application.prototype.initAssets = function initAssets ( options ) {
  199.   let opts                  = options || {},
  200.       application           = opts['application'],
  201.       directoryInformation  = opts['directoryInformation'],
  202.       config                = opts['config'],
  203.       logger                = opts['logger'],
  204.       datastore             = opts['datastore']['db'],
  205.       models                = datastore['sequelize']['models'],
  206.  
  207.       me                    = this;
  208. /*<-Class related
  209.   Function Related
  210.               Log Related
  211.                   Tab delimited beautify standard */
  212.               me.logger.log('info', 'Application.initAssets(' + options +')');
  213.  
  214.       let AssetManager = require(
  215.         path.join ( directoryInformation['assetsDirectory'],
  216.               'main.js' )
  217.       );
  218.  
  219.       let assetManager = new AssetManager(opts);
  220.       // Here's the chance to alter the datastore before sending it to the main Application Object.
  221.  
  222.       return assetManager;
  223. };
  224. /**
  225.  * Returns the Datastore Object.
  226.  * @param {object} options the parent directory
  227.  * @return {express} the instantiated Datastore object.
  228.  */
  229. Application.prototype.initExtensions = function initExtensions ( options ) {
  230.   let opts                  = options || {},
  231.       application           = opts['application'],
  232.       directoryInformation  = opts['directoryInformation'],
  233.       config                = opts['config'],
  234.       logger                = opts['logger'],
  235.       datastore             = opts['datastore']['db'],
  236.       models                = datastore['sequelize']['models'],
  237.       viewDirectories       = opts['viewDirectories'],
  238.  
  239.       me                    = this;
  240. /*<-Class related
  241.   Function Related
  242.               Log Related
  243.                   Tab delimited beautify standard */
  244.               me.logger.log('info', 'Application.initExtensions(' + options +')');
  245.  
  246.       let ExtensionManager = require(
  247.         path.join ( directoryInformation['Application']['ApplicationDirectory'],
  248.               'extensionmanager.js' )
  249.       );
  250.  
  251.       let extensionManager = new ExtensionManager(opts);
  252.       // Here's the chance to alter the datastore before sending it to the main Application Object.
  253.       return extensionManager;
  254. };
  255. /**
  256.  * Returns the Datastore Object.
  257.  * @param {object} options the parent directory
  258.  * @return {express} the instantiated Datastore object.
  259.  */
  260. Application.prototype.initRoutes = function initRoutes ( options ) {
  261.   let opts                  = options || {},
  262.       application           = opts.application,
  263.       app                   = application,
  264.       directoryInformation  = opts.directoryInformation,
  265.       config                = opts.config,
  266.       logger                = opts['logger'],
  267.       datastore             = opts['datastore'],
  268.       db                    = datastore.db,
  269.       models                = db.sequelize.models,
  270.  
  271.       passport        =require('passport'),
  272.       passportLocal   =require('passport-local'),
  273.       LocalStrategy   =passportLocal.Strategy,
  274.       bCrypt          =require('bcrypt'),
  275.  
  276.       me                    = this;
  277. /*<-Class related
  278.   Function Related
  279.               Log Related
  280.                   Tab delimited beautify standard */
  281.               me.logger.log('info', 'Application.initRoutes(' + options +')');
  282.  
  283.  
  284.   app.use(passport.initialize());
  285.   app.use(passport.session());
  286.  
  287.   passport.serializeUser(function(user, done) {
  288.     done(null, user.id);
  289.   });
  290.  
  291.   passport.deserializeUser(function(id, done) {
  292.     datastore.models['Member'].model.find({where: {id: id}}).then(function(user){
  293.       done(null, user);
  294.     }).error(function(err){
  295.       done(err, null);
  296.     });
  297.   });
  298.  
  299.   passport.use('local-login',
  300.   new LocalStrategy({
  301.       usernameField: 'email',
  302.       passwordField: 'password',
  303.       passReqToCallback: true // allows us to pass back the entire request to the callback
  304.   }, function(req, email, password, done) {
  305.     var compareHash = function(password,hash) {
  306.       var bcrypt = require('bcrypt');
  307.       return bcrypt.compareSync(password, hash);
  308.     };
  309.     datastore.models['Member'].model.find({ where: { email: email }}).then(function(user) {
  310.       if (!user) {
  311.         done(null, false, { message: 'Unknown user' });
  312.       }
  313.       if (!compareHash(password,user.password)) {
  314.         return done(null, false, {
  315.             message: 'Incorrect password.'
  316.         });
  317.       }
  318.       var userinfo = user.get();
  319.       return done(null, userinfo);
  320.     }).error(function(err){
  321.       done(err);
  322.     });
  323.   }));
  324.  
  325.   passport.use('local-register',
  326.   new LocalStrategy({
  327.       usernameField: 'email',
  328.       passwordField: 'password',
  329.       passReqToCallback: true // allows us to pass back the entire request to the callback
  330.   },function(req, email, password, done) {
  331.     console.dir(datastore.models);
  332.     //datastore.models['Member'].
  333.     var generateHash = function(password) {
  334.       return bCrypt.hashSync(password, bCrypt.genSaltSync(8), null);
  335.     };
  336.     datastore.models['Member']['model'].findOne({where: {email: email}}).then(function(user) {
  337.       if (user)
  338.       {
  339.         return done(null, false, {
  340.           message: 'That email is already taken'
  341.         });
  342.       }
  343.       else
  344.       {
  345.         var userPassword = generateHash(password);
  346.         var data =
  347.           {
  348.               email: email,
  349.               password: userPassword,
  350.               firstname: req.body.firstname,
  351.               lastname: req.body.lastname
  352.           };
  353.           datastore.models['Member']['model'].create(data).then(function(newUser, created) {
  354.             if (!newUser) {
  355.                 return done(null, false);
  356.             }
  357.             if (newUser) {
  358.                 return done(null, newUser);
  359.             }
  360.         });
  361.       }
  362.     });
  363.   }));
  364.   me.app.get('/', function( req , res ) {
  365.     res.render('basic/index', { ds:datastore, lg:logger, user:req.user,expressFlash:req.flash('success') });
  366.   });
  367.   me.app.get('/login', function( req , res ) {
  368.     res.render('basic/login', { ds:datastore, lg:logger,expressFlash:req.flash('success') });
  369.   });
  370.   me.app.post('/login',
  371.   passport.authenticate('local-login', {
  372.     successRedirect: '/',
  373.     failureRedirect: '/login'
  374.   }));
  375.   me.app.get('/register', function( req , res ) {
  376.     res.render('basic/register', { ds:datastore, lg:logger, expressFlash:req.flash('success') });
  377.   });
  378.   me.app.post('/register',
  379.   passport.authenticate('local-register', {
  380.     successRedirect: '/',
  381.     failureRedirect: '/register'
  382.   }));
  383.   me.app.get('/logout', function(req,res) {
  384.     req.logout();
  385.     res.redirect('/');
  386.   });
  387. };
  388. /**
  389.  * Returns the Datastore Object.
  390.  * @param {object} options the parent directory
  391.  * @return {express} the instantiated Datastore object.
  392.  */
  393. Application.prototype.run = function run ( options ) {
  394.   let opts                  = options || {},
  395.       application           = opts['application'],
  396.       directoryInformation  = opts['directoryInformation'],
  397.       config                = opts['config'],
  398.       logger                = opts['logger'],
  399.  
  400.       me                    = this;
  401. /*<-Class related
  402.   Function Related
  403.               Log Related
  404.                   Tab delimited beautify standard */
  405.               me.logger.log('info', 'Application.run(' + options +')');
  406.  
  407.   me.app.listen(3000, function (err) {
  408.     me.logger.log('info', '[http] listening on port 3000!');
  409.   });
  410. };
  411.  
  412. module.exports = Application;
Add Comment
Please, Sign In to add comment