<commit_before>(function () {
    'use strict';

    var fs = require('fs');
    var https = require('https');
    var async = require('async');
    var morgan = require('morgan');
    var express = require('express');
    var mongoose = require('mongoose');
    var schedule = require('node-schedule');
    var spawn = require('child_process').spawn;

    // api version & url
    var apiVersion = 0;
    var apiBaseUrl = '/api/v' + apiVersion;

    // ssl
    var use_ssl;
    var https_options;
    try {
        use_ssl = true;
        var key = fs.readFileSync('./ssl.key');
        var cert = fs.readFileSync('./ssl.crt');
        // load passphrase from file
        var pass = require('./ssl-pass');
        https_options = {
            key: key,
            cert: cert,
            passphrase: pass.passphrase
        };
    } catch(err) {
        if (err) { use_ssl = false; }
    }

    // mongodb
    var mongohost = 'localhost:27017';
    var mongodb = process.env.TLSDB || 'tls';
    var mongoConnection = 'mongodb://' + mongohost + '/' + mongodb;

    // connect
    if (mongoose.connection.readyState === 0) { mongoose.connect(mongoConnection); }

    // create model
    var TLSModel = require('./tlsSchema');

    // create the express app, router & configure port
    var app = express();
    var router = express.Router();
    var apiPort = process.env.TLSORT || 1337;

    // use morgan to log
    app.use(morgan('dev'));

    // allow cross origin resource sharing
    app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
        next();
    });

    // api home route (GET /$apiBaseUrl)
    router.get('/', function(req, res) {
        res.status(200).json({ message: 'welcome to the tls api v' + apiVersion });
        res.end();
    });

    // register our routes & routers
    router.use('/scans', require('./routes/scans'));
    router.use('/ciphers', require('./routes/ciphers'));
    router.use('/pfs', require('./routes/pfs'));
    router.use('/exp', require('./routes/exp'));
    router.use('/mac', require('./routes/mac'));

    // register base & default router
    app.use(apiBaseUrl, router);

    // catch-all route to handle 404 errors
    app.get('*', function(req, res, next) {
        var err = new Error();
        err.status = 404;
        next(err);
    });

    // handle error
    app.use(function(err, req, res, next) {
        if(err.status === 404) {
            // send 404
            res.status(404).send({ msg: 'whoopsie!' });
        } else {
            // log error
            console.error(err);
            res.status(500).send({ msg: 'big whoopsie!' });
        }
    });

    // setup cron jobs for the aggregators
    schedule.scheduleJob('5 * * * *', function(){
        spawn('node', ['./queries/pfsOverview.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('15 * * * *', function(){
        spawn('node', ['./queries/cipherSummaryGlobal.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('25 * * * *', function(){
        spawn('node', ['./queries/cipherSummaryPerTld.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('35 * * * *', function(){
        spawn('node', ['./queries/pfsDistribution.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('45 * * * *', function(){
        spawn('node', ['./queries/expOverview.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('50 * * * *', function(){
        spawn('node', ['./queries/macDistributionGlobal.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('55 * * * *', function(){
        spawn('node', ['./queries/macDistributionPerTld.js'], { stdio: 'inherit' });
    });

    // start the server
    console.log('\n* starting the tls api\n');
    console.log('  mongodb:  ' + mongoConnection);
    console.log('  ssl:      ' + use_ssl);
    var server;
    if (use_ssl) {
        server = https.createServer(https_options, app).listen(apiPort);
        console.log('  url:      https://localhost:' + apiPort + apiBaseUrl);
    } else {
        server = app.listen(apiPort);
        console.log('  url:      http://localhost:' + apiPort + apiBaseUrl);
    }

    // starter & stopper functions for testing
    var startApi = function() {
        if (!server) { server = app.listen(apiPort); }
    };

    var stopApi = function() {
        server.close();
    };

    // export functions
    module.exports = { startApi: startApi, stopApi: stopApi };
}());
<commit_msg>scheduler: run aggregations only ones a day<commit_after>(function () {
    'use strict';

    var fs = require('fs');
    var https = require('https');
    var async = require('async');
    var morgan = require('morgan');
    var express = require('express');
    var mongoose = require('mongoose');
    var schedule = require('node-schedule');
    var spawn = require('child_process').spawn;

    // api version & url
    var apiVersion = 0;
    var apiBaseUrl = '/api/v' + apiVersion;

    // ssl
    var use_ssl;
    var https_options;
    try {
        use_ssl = true;
        var key = fs.readFileSync('./ssl.key');
        var cert = fs.readFileSync('./ssl.crt');
        // load passphrase from file
        var pass = require('./ssl-pass');
        https_options = {
            key: key,
            cert: cert,
            passphrase: pass.passphrase
        };
    } catch(err) {
        if (err) { use_ssl = false; }
    }

    // mongodb
    var mongohost = 'localhost:27017';
    var mongodb = process.env.TLSDB || 'tls';
    var mongoConnection = 'mongodb://' + mongohost + '/' + mongodb;

    // connect
    if (mongoose.connection.readyState === 0) { mongoose.connect(mongoConnection); }

    // create model
    var TLSModel = require('./tlsSchema');

    // create the express app, router & configure port
    var app = express();
    var router = express.Router();
    var apiPort = process.env.TLSORT || 1337;

    // use morgan to log
    app.use(morgan('dev'));

    // allow cross origin resource sharing
    app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
        next();
    });

    // api home route (GET /$apiBaseUrl)
    router.get('/', function(req, res) {
        res.status(200).json({ message: 'welcome to the tls api v' + apiVersion });
        res.end();
    });

    // register our routes & routers
    router.use('/scans', require('./routes/scans'));
    router.use('/ciphers', require('./routes/ciphers'));
    router.use('/pfs', require('./routes/pfs'));
    router.use('/exp', require('./routes/exp'));
    router.use('/mac', require('./routes/mac'));

    // register base & default router
    app.use(apiBaseUrl, router);

    // catch-all route to handle 404 errors
    app.get('*', function(req, res, next) {
        var err = new Error();
        err.status = 404;
        next(err);
    });

    // handle error
    app.use(function(err, req, res, next) {
        if(err.status === 404) {
            // send 404
            res.status(404).send({ msg: 'whoopsie!' });
        } else {
            // log error
            console.error(err);
            res.status(500).send({ msg: 'big whoopsie!' });
        }
    });

    // setup cron jobs for the aggregators
    schedule.scheduleJob('5 3 * * *', function(){
        spawn('node', ['./queries/pfsOverview.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('15 3 * * *', function(){
        spawn('node', ['./queries/cipherSummaryGlobal.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('25 3 * * *', function(){
        spawn('node', ['./queries/cipherSummaryPerTld.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('35 3 * * *', function(){
        spawn('node', ['./queries/pfsDistribution.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('45 3 * * *', function(){
        spawn('node', ['./queries/expOverview.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('50 3 * * *', function(){
        spawn('node', ['./queries/macDistributionGlobal.js'], { stdio: 'inherit' });
    });

    schedule.scheduleJob('55 3 * * *', function(){
        spawn('node', ['./queries/macDistributionPerTld.js'], { stdio: 'inherit' });
    });

    // start the server
    console.log('\n* starting the tls api\n');
    console.log('  mongodb:  ' + mongoConnection);
    console.log('  ssl:      ' + use_ssl);
    var server;
    if (use_ssl) {
        server = https.createServer(https_options, app).listen(apiPort);
        console.log('  url:      https://localhost:' + apiPort + apiBaseUrl);
    } else {
        server = app.listen(apiPort);
        console.log('  url:      http://localhost:' + apiPort + apiBaseUrl);
    }

    // starter & stopper functions for testing
    var startApi = function() {
        if (!server) { server = app.listen(apiPort); }
    };

    var stopApi = function() {
        server.close();
    };

    // export functions
    module.exports = { startApi: startApi, stopApi: stopApi };
}());
<|endoftext|>


<commit_before>if (process.env.NEW_RELIC_LICENSE_KEY) { require('newrelic') }
const Hapi = require('hapi')
const Inert = require('inert')
const Vision = require('vision')
const Pack = require('./package')
const HapiSwagger = require('hapi-swagger')

// Create Server Object
const server = new Hapi.Server({port: (~~process.env.PORT || 3000)})

// Define Swagger options
const options = {
  payloadType: 'form',
  info: {
    'title': Pack.name + ' API Documentation',
    'version': Pack.version,
    'description': Pack.description,
    'contact': {
      'name': Pack.author
    },
    'license': {
      'name': Pack.license
    }
  },
  tags: [
    {
      'name': 'account',
      'description': 'Access account data'
    }, {
      'name': 'users',
      'description': 'Access user data'
    }
  ]
}

// Declare plugins
const plugins = [
  {plugin: HapiSwagger, options: options},
  Inert,
  Vision,
  require('./api/index'),
  require('./api/account/hello'),
  require('./api/account/goodbye'),
  require('./api/users/list')
]

const init = async () => {
  await server.register(plugins)
  await server.start()
  console.log('Server running at:', server.info.uri)
  console.log('Documentation available at:', server.info.uri + '/documentation')
}

process.on('unhandledRejection', (err) => {
  console.log(err)
  process.exit(1)
})

init()

module.exports = server
<commit_msg>Remove default port/host after hapi integrated it<commit_after>if (process.env.NEW_RELIC_LICENSE_KEY) { require('newrelic') }
const Hapi = require('hapi')
const Inert = require('inert')
const Vision = require('vision')
const Pack = require('./package')
const HapiSwagger = require('hapi-swagger')

// Create Server Object
const server = new Hapi.Server()

// Define Swagger options
const options = {
  payloadType: 'form',
  info: {
    'title': Pack.name + ' API Documentation',
    'version': Pack.version,
    'description': Pack.description,
    'contact': {
      'name': Pack.author
    },
    'license': {
      'name': Pack.license
    }
  },
  tags: [
    {
      'name': 'account',
      'description': 'Access account data'
    }, {
      'name': 'users',
      'description': 'Access user data'
    }
  ]
}

// Declare plugins
const plugins = [
  {plugin: HapiSwagger, options: options},
  Inert,
  Vision,
  require('./api/index'),
  require('./api/account/hello'),
  require('./api/account/goodbye'),
  require('./api/users/list')
]

const init = async () => {
  await server.register(plugins)
  await server.start()
  console.log('Server running at:', server.info.uri)
  console.log('Documentation available at:', server.info.uri + '/documentation')
}

process.on('unhandledRejection', (err) => {
  console.log(err)
  process.exit(1)
})

init()

module.exports = server
<|endoftext|>


<commit_before>const fs = require('fs');
const qs = require('qs');
const https = require('https');
const url = require('url');
const request = require('request');
const passport = require('passport');
const config = require('./config');
const bodyParser = require('body-parser');
const sgMail = require('@sendgrid/mail');
const requestUtils = require('./client/src/shared/requestUtils');
const notifications = require('./notifications');
const crypto = require('crypto');
const compare = require('secure-compare');

module.exports = function(app) {
  const GITHUB_API_ROOT = 'https://api.github.com';

  const getlocalAppRootUrl = request => {
    return process.env.NODE_ENV == 'production'
      ? url.format({
          protocol: 'https', // request.protocol returns http for now since the node server itself is only using http. However the api is used over https thanks to azure / IIS
          host: request.hostname,
          // port: request.port,
          pathname: ''
        })
      : 'https://localhost:3000'; // hard coded value in development because the request came through the webpack dev server on a different port and via https.
  };

  function loadAppData() {
    return JSON.parse(fs.readFileSync(`${__dirname}/${config.app.groupConfigPath}`, 'utf-8'));
  }

  const appData = loadAppData();

  // Utility functions
  const sendMail = (to, title, body) => {
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: to,
      from: config.app.emailSender,
      subject: title,
      html: body,
    };
    return sgMail.send(msg);
  };

  const getProxyRequestOptions = url => ({
    url: GITHUB_API_ROOT + url.replace('/api', ''),
    headers: {
      Authorization: `token ${config.github.botToken}`
      //,"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      ,"accept-encoding": "identity",
    }
  });

  const rewriteResponseHeaders = (request, response) => {
    if (response.headers.link) {
      response.headers.link = response.headers.link.replace(GITHUB_API_ROOT, getlocalAppRootUrl(request) + '/api');
      console.log(`Request App: Rewritten response.headers.link: ${JSON.stringify(response.headers.link)}`);
    } else {
      console.log(`Request App: response.headers.link falsy, nothing to rewrite`);
    }
  };

  const genericErrorHandler = (error, response, body) => {
    if (error) {
      if (error.code === 'ECONNREFUSED') {
        console.error('Refused connection');
      } else if (error.code === 'ETIMEDOUT') {
        console.error('Connection timed out');
      } else {
        throw error;
      }
    }
  };

  const validateRepository = (organisation, repo, projects) => {
    if (projects.filter(p => p.organisation == organisation && p.repository == repo).length == 0) {
      console.error(`Request App: Repository not found : ${organisation}/${repo}`);
      return false;
    } else {
      console.log(`Request App: Valid repository: ${organisation}/${repo}`);
      return true;
    }
  };

  // App end points
  app.get('/api/projects', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    res.json(appData);
  });

  app.get('/api/authenticate/github/:code', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    const r = request.post(
      {
        url: 'https://github.com/login/oauth/access_token',
        json: {
          client_id: config.github.clientID,
          client_secret: config.github.clientSecret,
          code: req.params.code
        }
      },
      genericErrorHandler
    );
    r.pipe(res);
  });

  // proxy to github api end points
  app.get('/api/repos/:organisation/:repo/issues', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    console.log('Request App received request to: ', req.url);

    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    console.log(`Request App: Listing issues on repository ${req.params.organisation}/${req.params.repo}`);

    // this actually does a request to github, which is not required
    const gitHubRequest = request(getProxyRequestOptions(req.url)); // add the authorization that github wants

    console.log('Request App: Proxying request to: ', getProxyRequestOptions(req.url).url);

    req
    .pipe(gitHubRequest, genericErrorHandler) // send to git hub
    .on('response', response => rewriteResponseHeaders(req, response)) // response from github, monkey with the headers for some reason. Looking at the logs it doesn't seem to do anything
    .pipe(res); // pipe response from github back to response from this route / function
  });

  app.get('/api/repositories/:repoId/issues', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    console.log(`going through pages on repository ${req.params.repoId}`);
    const r = request(getProxyRequestOptions(req.url));
    console.log('Proxied request to: ', getProxyRequestOptions(req.url).url);
    req.pipe(r, genericErrorHandler).on('response', response => rewriteResponseHeaders(req, response)).pipe(res);
  });

  app.get('/api/repos/:organisation/:repo/issues/:issueId', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    const r = request(getProxyRequestOptions(req.url));
    console.log('Proxied request to: ', getProxyRequestOptions(req.url).url);
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  app.post('/api/repos/:organisation/:repo/issues', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    console.log(`creating issue on repository ${req.params.organisation}/${req.params.repo}`);
    const r = request.post(getProxyRequestOptions(req.url));
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  app.get('/api/repos/:organisation/:repo/issues/:issueId/comments', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    const r = request(getProxyRequestOptions(req.url));
    console.log('Proxied request to: ', getProxyRequestOptions(req.url).url);
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  app.post('/api/repos/:organisation/:repo/issues/:issueId/comments', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    console.log(`adding comment on issue in repository ${req.params.organisation}/${req.params.repo}`);
    const r = request.post(getProxyRequestOptions(req.url));
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  // Calculate the X-Hub-Signature header value.
  function getSignature(buf) {
    var hmac = crypto.createHmac("sha1", config.github.webHookSecret);
    hmac.update(buf, "utf-8");
    return "sha1=" + hmac.digest("hex");
  }

  // Verify function compatible with body-parser to retrieve the request payload.
  // Read more: https://github.com/expressjs/body-parser#verify
  function verifyRequest(req, res, buf, encoding) {
    var expected = req.headers['x-hub-signature'];
    var calculated = getSignature(buf);
    console.log("X-Hub-Signature:", expected, "Content:", "-" + buf.toString('utf8') + "-");
    if (!compare(expected,calculated)) {
      throw new Error("Invalid signature.");
    } else {
      console.log("Valid signature!");
    }
  }

  function isGitHubWebHookRequestValid(req)  {
    const eventType = req.headers['x-github-event'];

    return
      eventType &&
      ['issues', 'issue_comment'].includes(eventType) &&
      req.body &&
      req.body.issue &&
      req.body.issue.user.login === config.github.botLogin;
  }

  function handleInvalidGitHubWebHookRequest(req, res)  {
    console.log('RequestApp: The following github webhook was not valid:');
    console.log(config.github.botLogin);
    console.log(JSON.stringify(req.headers));
    console.log(JSON.stringify(req.body));

    res.json({
      message: 'The github webhook request is not valid',
      webhook: req.body
    });
  }

  function sendEmailsForGitHubWebHook(req, res)  {
    try {
      sendEmailsForGitHubWebHook(req, res);
    } catch (error) {
      handleErrorForEmailsForGitHubWebHook(req, res, error);
    }
  }

  function trySendEmailsForGitHubWebHook(req, res)  {
    const { email } = requestUtils.getCreator(req.body.issue);
    const project = notifications.findProject(req.body, appData.projects);
    const requestUrl = notifications.getRequestUrl(req.body.issue.number, project, getlocalAppRootUrl(req));
    const eventType = req.headers['x-github-event'];
    const { subject, content } = notifications.getNotificationText(eventType, req.body, project.name, requestUrl);

    console.log(`Request app: Email notification starting`);

    if (email && subject && content) {
      sendMail(email, subject, content)
        .then(response => {
          console.log(response.statusCode, `Email notification sent successfully to ${email}`);
        })
        .catch(error => {
          //error is an instance of SendGridError
          //The full response is attached to error.response
          console.log(error.response);
        });
    }

    console.log(`Request app: Email notification returning response`);
    res.json({ message: 'web hook processed' });
  }

  function handleErrorForEmailsForGitHubWebHook(req, res, error)  {
    console.log('RequestApp: An error occcured while attempting to process the following github webhook:');
    console.log(error);
    console.log('RequestApp: webhook data:');
    console.log(JSON.stringify(req.headers));
    console.log(JSON.stringify(req.body));
    res.json({
      message: 'An error occcured while attempting to process a github webhook',
      webhook: req.body
    });
  }

  // handle github web hooks
  app.post('/api/github-webhooks', [bodyParser.json({verify:verifyRequest})], function(req, res) {

    // this message is unsecured because github doesn't have a token to call us
    // instead we check that this message was generated by our github instance
    // by checking that the signature of the body was created with the correct secret
    console.log(`RequestApp: received web hook:`);
    console.log(JSON.stringify(req.headers));
    console.log(JSON.stringify(req.body));
    console.log(`RequestApp: received web hook action: ${req.headers['x-github-event']}`);

    if (isGitHubWebHookRequestValid(req)) {
      sendEmailsForGitHubWebHook(req, res)
    } else {
      handleInvalidGitHubWebHookRequest(req, res);
    }
  });
};
<commit_msg>Fix infinite recursion, remove validity check (which isn't working correctly), add status codes to responses, add logging, encapsulate conditional<commit_after>const fs = require('fs');
const qs = require('qs');
const https = require('https');
const url = require('url');
const request = require('request');
const passport = require('passport');
const config = require('./config');
const bodyParser = require('body-parser');
const sgMail = require('@sendgrid/mail');
const requestUtils = require('./client/src/shared/requestUtils');
const notifications = require('./notifications');
const crypto = require('crypto');
const compare = require('secure-compare');

module.exports = function(app) {
  const GITHUB_API_ROOT = 'https://api.github.com';

  const getlocalAppRootUrl = request => {
    return process.env.NODE_ENV == 'production'
      ? url.format({
          protocol: 'https', // request.protocol returns http for now since the node server itself is only using http. However the api is used over https thanks to azure / IIS
          host: request.hostname,
          // port: request.port,
          pathname: ''
        })
      : 'https://localhost:3000'; // hard coded value in development because the request came through the webpack dev server on a different port and via https.
  };

  function loadAppData() {
    return JSON.parse(fs.readFileSync(`${__dirname}/${config.app.groupConfigPath}`, 'utf-8'));
  }

  const appData = loadAppData();

  // Utility functions
  const sendMail = (to, title, body) => {
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: to,
      from: config.app.emailSender,
      subject: title,
      html: body,
    };
    return sgMail.send(msg);
  };

  const getProxyRequestOptions = url => ({
    url: GITHUB_API_ROOT + url.replace('/api', ''),
    headers: {
      Authorization: `token ${config.github.botToken}`
      //,"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
      ,"accept-encoding": "identity",
    }
  });

  const rewriteResponseHeaders = (request, response) => {
    if (response.headers.link) {
      response.headers.link = response.headers.link.replace(GITHUB_API_ROOT, getlocalAppRootUrl(request) + '/api');
      console.log(`Request App: Rewritten response.headers.link: ${JSON.stringify(response.headers.link)}`);
    } else {
      console.log(`Request App: response.headers.link falsy, nothing to rewrite`);
    }
  };

  const genericErrorHandler = (error, response, body) => {
    if (error) {
      if (error.code === 'ECONNREFUSED') {
        console.error('Refused connection');
      } else if (error.code === 'ETIMEDOUT') {
        console.error('Connection timed out');
      } else {
        throw error;
      }
    }
  };

  const validateRepository = (organisation, repo, projects) => {
    if (projects.filter(p => p.organisation == organisation && p.repository == repo).length == 0) {
      console.error(`Request App: Repository not found : ${organisation}/${repo}`);
      return false;
    } else {
      console.log(`Request App: Valid repository: ${organisation}/${repo}`);
      return true;
    }
  };

  // App end points
  app.get('/api/projects', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    res.json(appData);
  });

  app.get('/api/authenticate/github/:code', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    const r = request.post(
      {
        url: 'https://github.com/login/oauth/access_token',
        json: {
          client_id: config.github.clientID,
          client_secret: config.github.clientSecret,
          code: req.params.code
        }
      },
      genericErrorHandler
    );
    r.pipe(res);
  });

  // proxy to github api end points
  app.get('/api/repos/:organisation/:repo/issues', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    console.log('Request App received request to: ', req.url);

    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    console.log(`Request App: Listing issues on repository ${req.params.organisation}/${req.params.repo}`);

    // this actually does a request to github, which is not required
    const gitHubRequest = request(getProxyRequestOptions(req.url)); // add the authorization that github wants

    console.log('Request App: Proxying request to: ', getProxyRequestOptions(req.url).url);

    req
    .pipe(gitHubRequest, genericErrorHandler) // send to git hub
    .on('response', response => rewriteResponseHeaders(req, response)) // response from github, monkey with the headers for some reason. Looking at the logs it doesn't seem to do anything
    .pipe(res); // pipe response from github back to response from this route / function
  });

  app.get('/api/repositories/:repoId/issues', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    console.log(`going through pages on repository ${req.params.repoId}`);
    const r = request(getProxyRequestOptions(req.url));
    console.log('Proxied request to: ', getProxyRequestOptions(req.url).url);
    req.pipe(r, genericErrorHandler).on('response', response => rewriteResponseHeaders(req, response)).pipe(res);
  });

  app.get('/api/repos/:organisation/:repo/issues/:issueId', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    const r = request(getProxyRequestOptions(req.url));
    console.log('Proxied request to: ', getProxyRequestOptions(req.url).url);
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  app.post('/api/repos/:organisation/:repo/issues', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    console.log(`creating issue on repository ${req.params.organisation}/${req.params.repo}`);
    const r = request.post(getProxyRequestOptions(req.url));
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  app.get('/api/repos/:organisation/:repo/issues/:issueId/comments', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    const r = request(getProxyRequestOptions(req.url));
    console.log('Proxied request to: ', getProxyRequestOptions(req.url).url);
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  app.post('/api/repos/:organisation/:repo/issues/:issueId/comments', passport.authenticate('oauth-bearer', { session: false }), function(req, res) {
    if (!validateRepository(req.params.organisation, req.params.repo, appData.projects))
      res.status(403).send({ error: 'Invalid repository name' });

    console.log(`adding comment on issue in repository ${req.params.organisation}/${req.params.repo}`);
    const r = request.post(getProxyRequestOptions(req.url));
    req.pipe(r, genericErrorHandler).pipe(res);
  });

  // Calculate the X-Hub-Signature header value.
  function getSignature(buf) {
    var hmac = crypto.createHmac("sha1", config.github.webHookSecret);
    hmac.update(buf, "utf-8");
    return "sha1=" + hmac.digest("hex");
  }

  // Verify function compatible with body-parser to retrieve the request payload.
  // Read more: https://github.com/expressjs/body-parser#verify
  function verifyRequest(req, res, buf, encoding) {
    var expected = req.headers['x-hub-signature'];
    var calculated = getSignature(buf);
    console.log("X-Hub-Signature:", expected, "Content:", "-" + buf.toString('utf8') + "-");
    if (!compare(expected,calculated)) {
      throw new Error("Invalid signature.");
    } else {
      console.log("Valid signature!");
    }
  }

  function userLoginFromGitHubRequestBody(body){
    return
      req.body &&
      req.body.issue &&
      req.body.issue.user.login;
  }

  function isGitHubWebHookRequestValid(req)  {
    const eventType = req.headers['x-github-event'];

    return
      eventType &&
      ['issues', 'issue_comment'].includes(eventType);// &&
      //userLoginFromGitHubRequestBody(req.body) === config.github.botLogin;
  }

  function handleInvalidGitHubWebHookRequest(req, res)  {
    console.log('RequestApp: The following github webhook was not valid:');
    console.log(req.headers['x-github-event']);
    console.log(config.github.botLogin);
    console.log(userLoginFromGitHubRequestBody(req.body));
    req.body.issue && console.log(`issue ${JSON.stringify(req.body.issue)}`);
    req.body.issue && req.body.issue.user && console.log(`issue.user: ${JSON.stringify(req.body.issue.user)}`);
    req.body.issue && req.body.issue.user && req.body.issue.user.login && console.log(`issue.user.login: ${JSON.stringify(req.body.issue.user.login)}`);
    console.log(JSON.stringify(req.headers));
    console.log(JSON.stringify(req.body));

    res.status(422).send({
      message: 'The github webhook request is not valid'
    });
  }

  function sendEmailsForGitHubWebHook(req, res)  {
    try {
      trySendEmailsForGitHubWebHook(req, res);
    } catch (error) {
      handleErrorForEmailsForGitHubWebHook(req, res, error);
    }
  }

  function trySendEmailsForGitHubWebHook(req, res)  {
    const { email } = requestUtils.getCreator(req.body.issue);
    const project = notifications.findProject(req.body, appData.projects);
    const requestUrl = notifications.getRequestUrl(req.body.issue.number, project, getlocalAppRootUrl(req));
    const eventType = req.headers['x-github-event'];
    const { subject, content } = notifications.getNotificationText(eventType, req.body, project.name, requestUrl);

    console.log(`Request app: Email notification starting`);

    if (email && subject && content) {
      sendMail(email, subject, content)
        .then(response => {
          console.log(response.statusCode, `Email notification sent successfully to ${email}`);
        })
        .catch(error => {
          //error is an instance of SendGridError
          //The full response is attached to error.response
          console.log(error.response);
        });
    }

    console.log(`Request app: Email notification returning response`);
    res.json({ message: 'web hook processed' });
  }

  function handleErrorForEmailsForGitHubWebHook(req, res, error)  {
    console.log('RequestApp: An error occcured while attempting to process the following github webhook:');
    console.log(error);
    console.log('RequestApp: webhook data:');
    console.log(JSON.stringify(req.headers));
    console.log(JSON.stringify(req.body));
    res.status(500).json({
      message: 'An error occcured while attempting to process a github webhook',
    });
  }

  // handle github web hooks
  app.post('/api/github-webhooks', [bodyParser.json({verify:verifyRequest})], function(req, res) {

    // this message is unsecured because github doesn't have a token to call us
    // instead we check that this message was generated by our github instance
    // by checking that the signature of the body was created with the correct secret
    console.log(`RequestApp: received web hook:`);
    console.log(JSON.stringify(req.headers));
    console.log(JSON.stringify(req.body));
    console.log(`RequestApp: received web hook action: ${req.headers['x-github-event']}`);

    //if (isGitHubWebHookRequestValid(req)) {
      sendEmailsForGitHubWebHook(req, res)
    //} else {
    // handleInvalidGitHubWebHookRequest(req, res);
    //}
  });
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express'),
    route = require('./routes/route'),
    http = require('http'),
    path = require('path'),
    flash = require('connect-flash'),
    MongoStore = require('connect-mongo')(express),
    config = require('./config').config;

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(flash());
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser(config.cookieSecret));
  app.use(express.session({
      secret: config.sessionSecret,
      store: new MongoStore({
          url: config.db
      })
  }));

  // 检查当前用户状态
  app.use(require('./controllers/sign').checkCurrentUser);

  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

route(app);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});
<commit_msg>密集测试&开发<commit_after>
/**
 * Module dependencies.
 */

var express = require('express'),
    route = require('./routes/route'),
    http = require('http'),
    path = require('path'),
    flash = require('connect-flash'),
    partials = require('express-partials'),
    MongoStore = require('connect-mongo')(express),
    config = require('./config').config;

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(flash());
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser(config.cookieSecret));
  app.use(express.session({
      secret: config.sessionSecret,
      store: new MongoStore({
          url: config.db
      })
  }));
  app.use(partials());

  // 检查当前用户状态
  app.use(require('./controllers/sign').checkCurrentUser);

  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

route(app);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var ejs = require("ejs");

var request = require('request');
var cheerio = require('cheerio'); //scraping tool

var downloadCSV = require('./public/javascripts/downloadCSV');
var downloadICS = require('./public/javascripts/downloadICS');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

/*
    App parameters
    Enter year, (month-1) and day when the semester starts (Monday of the study week 1)
*/
var startYear = 2016;
var startMonth = 8;
var startDay = 19;

var skipWeek = false;
var url = "https://browser.ted.is.ed.ac.uk/generate?courses[]=BITE10013_SS1_YR&courses[]=BITE10002_SV1_SEM1&courses[]=BITE10001_SV1_SEM1&courses[]=BITE10007_SV1_YR&courses[]=BITE10006_SV1_SEM2&courses[]=CMSE10002_SV1_SEM1&show-close=1&show-close=1&period=SEM1";

var port = process.env.PORT || 3000;
//pp.set('port', process.env.PORT || 3000);

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//app.use(express.static(path.join(__dirname, 'views')));

app.get('/', function(req, res) {
  res.render('index.html');
});

app.get('/download/csv', function(req, res) {
    var url = req.query.url;
    console.log(url);
    if (!url) {
        res.redirect('/');
        return;
    }
    getFile(url, true, function(ts) {
        console.log(ts);
        res.send({ts:ts});
        //console.log("ping from csv");
    });

});

app.get('/download/ics', function(req, res) {
    var url = req.query.url;
    console.log(url);
    if (!url) {
        res.redirect('/');
        return;
    }
    getFile(url, false, function(ts) {
        console.log(ts);
        res.send({ts:ts});
        //console.log("ping from ts");
    });

    //res.setHeader('Content-disposition', 'attachment; filename=timetable.ics');
    //res.download('timetable.ics');
    //res.render('download.html');
    //
    //console.log("ping from ics");
    //res.setHeader('Content-disposition', 'attachment; filename=timetable.csv');
    //res.download('timetable.csv');
    //res.send('timetable.csv and timetable.ics have been successfully saved to your hard drive.');
});
//app.use('/users', users);

//router.get('/', function(req, res, next) {
//  res.render('index');
//});

/*
 Main Function Start
 */

function getFile(url, isCSVRequest, callback) {

    //url = 'https://browser.ted.is.ed.ac.uk/generate?courses[]=BILG09014_SV1_SEM2&courses[]=BUST10118_SV1_SEM2&courses[]=BUST10021_SV1_SEM2&show-close=1&period=SEM2#';
    var ts = 0;

    request(url, function (error, response, html) {
        if (!error) {
            var $ = cheerio.load(html);

            var course, type, times, location, day;
            var weeks = [];
            var event = {
                course: "",
                type: "",
                location: "",
                times: "",
                day: "",
                weeks: []
            };
            event.weeks = [];
            var items = [];

            $('.event-head span.course').each(function (i, elem) {
                items[i] = {
                    course: $(this).text()
                };
                items[i].day = $(this).parent().parent().parent().parent().find('th').text();
                if (items[i].day == '' && i != 0) {
                    items[i].day = items[i - 1].day;
                }
            });

            $('.type').each(function (i, elem) {
                items[i].type = $(this).clone().find('br').remove().end().find('small').remove().end().text().replace(/\s+/g, "");
            });

            $('div.times').each(function (i, elem) {
                items[i].times = $(this).clone().find('i').remove().end().text().replace(/\s+/g, "");
            });

            $('ul.facts').each(function (i, elem) {
                items[i].location = $(this).children().last().clone().find('span').remove().end().text().trim();
            });

            $('table .weeks').each(function (i, elem) {
                items[i].weeks = [];
                $(this).find('.on').each(function (n, nelem) {
                    items[i].weeks.push($(this).text());
                });
            });

            if (isCSVRequest) {
                ts = downloadCSV(startYear, startMonth, startDay, items);
                callback(ts);
            }
            else {
                ts = downloadICS(startYear, startMonth, startDay, items);
                callback(ts);
            }

        } else {
            console.log('url request failed');
        }

    });
}

/*
 Main Function End
 */

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        //res.render('error', {
        //    message: err.message,
        //    error: err
        //});
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    //res.render('error', {
    //    message: err.message,
    //    error: {}
    //});
});

app.listen(port, function() {
    console.log('Express server listening on port ' + port);
});

//app.listen(app.get('port'));
//console.log('Express server listening on port ' + app.get('port'));

module.exports = app;
<commit_msg>Remove ILW week skip<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var ejs = require("ejs");

var request = require('request');
var cheerio = require('cheerio'); //scraping tool

var downloadCSV = require('./public/javascripts/downloadCSV');
var downloadICS = require('./public/javascripts/downloadICS');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

/*
    App parameters
    Enter year, (month-1) and day when the semester starts (Monday of the study week 1)
*/
var startYear = 2016;
var startMonth = 8;
var startDay = 19;

var skipWeek = true;
var url = "https://browser.ted.is.ed.ac.uk/generate?courses[]=BITE10013_SS1_YR&courses[]=BITE10002_SV1_SEM1&courses[]=BITE10001_SV1_SEM1&courses[]=BITE10007_SV1_YR&courses[]=BITE10006_SV1_SEM2&courses[]=CMSE10002_SV1_SEM1&show-close=1&show-close=1&period=SEM1";

var port = process.env.PORT || 3000;
//pp.set('port', process.env.PORT || 3000);

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//app.use(express.static(path.join(__dirname, 'views')));

app.get('/', function(req, res) {
  res.render('index.html');
});

app.get('/download/csv', function(req, res) {
    var url = req.query.url;
    console.log(url);
    if (!url) {
        res.redirect('/');
        return;
    }
    getFile(url, true, function(ts) {
        console.log(ts);
        res.send({ts:ts});
        //console.log("ping from csv");
    });

});

app.get('/download/ics', function(req, res) {
    var url = req.query.url;
    console.log(url);
    if (!url) {
        res.redirect('/');
        return;
    }
    getFile(url, false, function(ts) {
        console.log(ts);
        res.send({ts:ts});
        //console.log("ping from ts");
    });

    //res.setHeader('Content-disposition', 'attachment; filename=timetable.ics');
    //res.download('timetable.ics');
    //res.render('download.html');
    //
    //console.log("ping from ics");
    //res.setHeader('Content-disposition', 'attachment; filename=timetable.csv');
    //res.download('timetable.csv');
    //res.send('timetable.csv and timetable.ics have been successfully saved to your hard drive.');
});
//app.use('/users', users);

//router.get('/', function(req, res, next) {
//  res.render('index');
//});

/*
 Main Function Start
 */

function getFile(url, isCSVRequest, callback) {

    //url = 'https://browser.ted.is.ed.ac.uk/generate?courses[]=BILG09014_SV1_SEM2&courses[]=BUST10118_SV1_SEM2&courses[]=BUST10021_SV1_SEM2&show-close=1&period=SEM2#';
    var ts = 0;

    request(url, function (error, response, html) {
        if (!error) {
            var $ = cheerio.load(html);

            var course, type, times, location, day;
            var weeks = [];
            var event = {
                course: "",
                type: "",
                location: "",
                times: "",
                day: "",
                weeks: []
            };
            event.weeks = [];
            var items = [];

            $('.event-head span.course').each(function (i, elem) {
                items[i] = {
                    course: $(this).text()
                };
                items[i].day = $(this).parent().parent().parent().parent().find('th').text();
                if (items[i].day == '' && i != 0) {
                    items[i].day = items[i - 1].day;
                }
            });

            $('.type').each(function (i, elem) {
                items[i].type = $(this).clone().find('br').remove().end().find('small').remove().end().text().replace(/\s+/g, "");
            });

            $('div.times').each(function (i, elem) {
                items[i].times = $(this).clone().find('i').remove().end().text().replace(/\s+/g, "");
            });

            $('ul.facts').each(function (i, elem) {
                items[i].location = $(this).children().last().clone().find('span').remove().end().text().trim();
            });

            $('table .weeks').each(function (i, elem) {
                items[i].weeks = [];
                $(this).find('.on').each(function (n, nelem) {
                    items[i].weeks.push($(this).text());
                });
            });

            if (isCSVRequest) {
                ts = downloadCSV(startYear, startMonth, startDay, items);
                callback(ts);
            }
            else {
                ts = downloadICS(startYear, startMonth, startDay, items);
                callback(ts);
            }

        } else {
            console.log('url request failed');
        }

    });
}

/*
 Main Function End
 */

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        //res.render('error', {
        //    message: err.message,
        //    error: err
        //});
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    //res.render('error', {
    //    message: err.message,
    //    error: {}
    //});
});

app.listen(port, function() {
    console.log('Express server listening on port ' + port);
});

//app.listen(app.get('port'));
//console.log('Express server listening on port ' + app.get('port'));

module.exports = app;
<|endoftext|>


<commit_before>var fs = require('graceful-fs');
	fs = require('fs.extra');

var path = require('path');
var async = require('async');

(function(exports) {

	// default path
	var dbpath = '/staticstore';
	var initialized = false;

	exports.initdb = function(costumpath, callback) {
		callback = callback || function() {};
		dbpath = costumpath || ((path.dirname(process.mainModule.filename) || __dirname) + dbpath);
		fs.exists(dbpath, function (exists) {
			if(exists) {
				initialized = true;
				callback(false);
			} else {
				fs.mkdir(dbpath, function() {
					initialized = true;
					callback(false);
				});
			}
		});
	};

	exports.createdb = function(name, callback) {
		callback = callback || function() {};
		var newdb = dbpath+'/'+name;

		if(!name) {
			return callback(true, 'Please define database');
		}

		fs.exists(newdb, function (exists) {
			if(exists) {
				callback('Database already exists!');
			} else {
				fs.mkdir(newdb, function() {
					callback(false);
				});
			}
		});
	};

	exports.deletedb = function(name, callback) {
		callback = callback || function() {};
		var removedb = dbpath+'/'+name;

		if(!name) {
			return callback(true, 'Please define database');
		}

		fs.exists(removedb, function (exists) {
			if(!exists) {
				callback('Database not found!');
			} else {
				fs.rmrf(removedb, function() {
					callback(false);
				});
			}
		});
	};

	exports.getItem = function(id, callback) {
		callback = callback || function() {};
		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = id.replace(/(.*)\/(.*)/gm, '$2');

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.readFile(itemid, function (err, data) {
		  if (err) {
		  	return callback('Item not found!');
		  } else {
		  	data = JSON.parse(data);
		  	callback(false, data);
		  }
		});
	};

	exports.setItem = function(id, data, callback) {
		callback = (typeof data === 'function') ? data : callback;
		data = (typeof data === 'function') ? undefined : data;
		callback = callback || function() {};

		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = String(id.replace(/(.*)\/(.*)/gm, '$2'));

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		data = data || {};
		data._id = id;
		data.timestamp = new Date();
		data = JSON.stringify(data);

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.writeFile(itemid, data, function (err) {
		  if (err) {
		  	return callback('Item not saved!');
		  } else {
		  	callback(false, id);
		  }
		});

	};

	exports.deleteItem = function(id, callback) {
		callback = callback || function() {};
		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = id.replace(/(.*)\/(.*)/gm, '$2');

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.unlink(itemid, function (err) {
		  if (err) {
		  	return callback('Item not deleted/found!');
		  } else {
		  	callback(false, id);
		  }
		});

	};

	exports.getAllItems = function(database, callback) {
		callback = callback || function() {};
		var db = dbpath+'/'+database;

		if(!database) {
			return callback(true, 'Please define database');
		}

		fs.exists(db, function (exists) {
			if(exists) {
				fs.readdir(db, function(err, files) {
					if(err) {
						callback('Cant read all indizies');
					} else {
						var filesArray = [];
						var q = async.queue(function(file, cb) {
							fs.readFile(db+'/'+file, function(err, data) {
								if(!err) {
									filesArray.push(JSON.parse(data));
								}
								cb();
							});
						});

						q.drain = function() {
							callback(false, filesArray);
						};

						q.push(files);
					}
				});
			} else {
				callback('Database not found!');
			}
		});

	};

	exports.itemExists = function(id, callback) {
		callback = callback || function() {};
		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = id.replace(/(.*)\/(.*)/gm, '$2');

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.exists(itemid, function (exists) {
			if(exists) {
				callback(false, true);
			} else {
				callback(false, false);
			}
		});

	};

	exports.getIndex = function(database, callback) {
		callback = callback || function() {};
		var db = dbpath+'/'+database;

		if(!database) {
			return callback(true, 'Please define database');
		}

		fs.exists(db, function (exists) {
			if(exists) {
				fs.readdir(db, function(err, files) {
					if(err) {
						callback('Cant read all indizies');
					} else {
						files.forEach(function(item, index) {
							files[index] = item.replace(/\.json/gm, '');
						});
						callback(false, files);
					}
				});
			} else {
				callback('Database not found!');
			}
		});
	};

	exports.itemCount = function(database, callback) {
		callback = callback || function() {};
		var db = dbpath+'/'+database;

		if(!database) {
			return callback(true, 'Please define database');
		}

		fs.exists(db, function (exists) {
			if(exists) {
				fs.readdir(db, function(err, files) {
					if(err || !files) {
						callback('Cant read all indizies');
					} else {
						callback(false, (files.length || 0));
					}
				});
			} else {
				callback('Database not found!');
			}
		});

	};

})(module.exports);
<commit_msg>catch invalid jsons<commit_after>var fs = require('graceful-fs');
	fs = require('fs.extra');

var path = require('path');
var async = require('async');

(function(exports) {

	// default path
	var dbpath = '/staticstore';
	var initialized = false;

	exports.initdb = function(costumpath, callback) {
		callback = callback || function() {};
		dbpath = costumpath || ((path.dirname(process.mainModule.filename) || __dirname) + dbpath);
		fs.exists(dbpath, function (exists) {
			if(exists) {
				initialized = true;
				callback(false);
			} else {
				fs.mkdir(dbpath, function() {
					initialized = true;
					callback(false);
				});
			}
		});
	};

	exports.createdb = function(name, callback) {
		callback = callback || function() {};
		var newdb = dbpath+'/'+name;

		if(!name) {
			return callback(true, 'Please define database');
		}

		fs.exists(newdb, function (exists) {
			if(exists) {
				callback('Database already exists!');
			} else {
				fs.mkdir(newdb, function() {
					callback(false);
				});
			}
		});
	};

	exports.deletedb = function(name, callback) {
		callback = callback || function() {};
		var removedb = dbpath+'/'+name;

		if(!name) {
			return callback(true, 'Please define database');
		}

		fs.exists(removedb, function (exists) {
			if(!exists) {
				callback('Database not found!');
			} else {
				fs.rmrf(removedb, function() {
					callback(false);
				});
			}
		});
	};

	exports.getItem = function(id, callback) {
		callback = callback || function() {};
		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = id.replace(/(.*)\/(.*)/gm, '$2');

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.readFile(itemid, function (err, data) {
		  if (err) {
		  	return callback('Item not found!');
		  } else {

		  	try {
		  		data = JSON.parse(data);
		  	} catch(e) {
		  		return callback('File invalid!');
		  	}

		  	callback(false, data);
		  }
		});
	};

	exports.setItem = function(id, data, callback) {
		callback = (typeof data === 'function') ? data : callback;
		data = (typeof data === 'function') ? undefined : data;
		callback = callback || function() {};

		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = String(id.replace(/(.*)\/(.*)/gm, '$2'));

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		data = data || {};
		data._id = id;
		data.timestamp = new Date();
		data = JSON.stringify(data);

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.writeFile(itemid, data, function (err) {
		  if (err) {
		  	return callback('Item not saved!');
		  } else {
		  	callback(false, id);
		  }
		});

	};

	exports.deleteItem = function(id, callback) {
		callback = callback || function() {};
		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = id.replace(/(.*)\/(.*)/gm, '$2');

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.unlink(itemid, function (err) {
		  if (err) {
		  	return callback('Item not deleted/found!');
		  } else {
		  	callback(false, id);
		  }
		});

	};

	exports.getAllItems = function(database, callback) {
		callback = callback || function() {};
		var db = dbpath+'/'+database;

		if(!database) {
			return callback(true, 'Please define database');
		}

		fs.exists(db, function (exists) {
			if(exists) {
				fs.readdir(db, function(err, files) {
					if(err) {
						callback('Cant read all indizies');
					} else {
						var filesArray = [];
						var q = async.queue(function(file, cb) {
							fs.readFile(db+'/'+file, function(err, data) {
								if(!err) {

									try {
										data = JSON.parse(data)
									} catch(e) {
										console.log('File invalid!', data);
									}

									if(typeof data !== 'string') {
										filesArray.push(data);
									}

								}
								cb();
							});
						});

						q.drain = function() {
							callback(false, filesArray);
						};

						q.push(files);
					}
				});
			} else {
				callback('Database not found!');
			}
		});

	};

	exports.itemExists = function(id, callback) {
		callback = callback || function() {};
		var database = id.replace(/(.*)\/(.*)/gm, '$1');
		id = id.replace(/(.*)\/(.*)/gm, '$2');

		if(!database || !id) {
			return callback(true, 'Please define database and key e.g. (database/key)');
		}

		var itemid = dbpath + '/' + database + '/' + id + '.json';

		fs.exists(itemid, function (exists) {
			if(exists) {
				callback(false, true);
			} else {
				callback(false, false);
			}
		});

	};

	exports.getIndex = function(database, callback) {
		callback = callback || function() {};
		var db = dbpath+'/'+database;

		if(!database) {
			return callback(true, 'Please define database');
		}

		fs.exists(db, function (exists) {
			if(exists) {
				fs.readdir(db, function(err, files) {
					if(err) {
						callback('Cant read all indizies');
					} else {
						files.forEach(function(item, index) {
							files[index] = item.replace(/\.json/gm, '');
						});
						callback(false, files);
					}
				});
			} else {
				callback('Database not found!');
			}
		});
	};

	exports.itemCount = function(database, callback) {
		callback = callback || function() {};
		var db = dbpath+'/'+database;

		if(!database) {
			return callback(true, 'Please define database');
		}

		fs.exists(db, function (exists) {
			if(exists) {
				fs.readdir(db, function(err, files) {
					if(err || !files) {
						callback('Cant read all indizies');
					} else {
						callback(false, (files.length || 0));
					}
				});
			} else {
				callback('Database not found!');
			}
		});

	};

})(module.exports);
<|endoftext|>


<commit_before>//Core Modules
var http            = require('http');
var path            = require('path');

//Basic Dependencies
var express         = require('express');

//required express 4 middleware
var compression     = require('compression');

//view engine
var expressHandlebars       = require( 'express3-handlebars' );

var app = express();

// setting mime types for webfonts and other things
express.static.mime.define( { 'application/x-font-woff': [ 'woff' ] } );
express.static.mime.define( { 'application/x-font-ttf': [ 'ttf' ] } );
express.static.mime.define( { 'application/vnd.ms-fontobject': [ 'eot' ] } );
express.static.mime.define( { 'font/opentype': [ 'otf' ] } );
express.static.mime.define( { 'image/svg+xml': [ 'svg' ] } );

app.disable( 'X-Powered-By' ); //SITE SECURITY: this way people cant see that we are using express.js and exploit its vulnerabilities
app.use( compression() ); // gzipping
app.set( 'port', process.env.PORT || 5000 ); //setting port

// Configuring view engine
app.engine('.html', expressHandlebars({
	defaultLayout: 'master',
	extname: ".html"
}));
app.set('view engine', '.html');

app.use(express.static(path.join(__dirname, '/dist')));
app.use('/bower_components', express.static( __dirname + '/bower_components' ) );

app.get( '/', function( req, res ){
	res.render( 'index', {
		isProd: true
	});
});

http.createServer( app ).listen( app.get( 'port' ) );

console.log( 'Application listening to port:', app.get( 'port' ));
<commit_msg>correcting express handlebars problem<commit_after>//Core Modules
var http            = require('http');
var path            = require('path');

//Basic Dependencies
var express         = require('express');

//required express 4 middleware
var compression     = require('compression');

//view engine
var expressHandlebars       = require( 'express-handlebars' );

var app = express();

// setting mime types for webfonts and other things
express.static.mime.define( { 'application/x-font-woff': [ 'woff' ] } );
express.static.mime.define( { 'application/x-font-ttf': [ 'ttf' ] } );
express.static.mime.define( { 'application/vnd.ms-fontobject': [ 'eot' ] } );
express.static.mime.define( { 'font/opentype': [ 'otf' ] } );
express.static.mime.define( { 'image/svg+xml': [ 'svg' ] } );

app.disable( 'X-Powered-By' ); //SITE SECURITY: this way people cant see that we are using express.js and exploit its vulnerabilities
app.use( compression() ); // gzipping
app.set( 'port', process.env.PORT || 5000 ); //setting port

// Configuring view engine
app.engine('.html', expressHandlebars({
	defaultLayout: 'master',
	extname: ".html"
}));
app.set('view engine', '.html');

app.use(express.static(path.join(__dirname, '/dist')));
app.use('/bower_components', express.static( __dirname + '/bower_components' ) );

app.get( '/', function( req, res ){
	res.render( 'index', {
		isProd: !!process.env.NODE_ENV
	});
});

http.createServer( app ).listen( app.get( 'port' ) );

console.log( 'Application listening to port:', app.get( 'port' ));
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var db = require("./db"); // starts a new mongoose connection

var routes = require('./routes/robots_controller');
var api_routes = require('./routes/api_controller');

var app = express();

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

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

app.use('/', routes);
app.use('/', api_routes);

// use webpack to bundle react components in development mode
if(process.env.NODE_ENV !== 'production') {
  var webpack = require('webpack');
  var webpackDevMiddleware = require('webpack-dev-middleware');
  var webpackHotMiddleware = require('webpack-hot-middleware');
  var config = require('./webpack.dev.config');
  var compiler = webpack(config);

  app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
  app.use(webpackHotMiddleware(compiler, {log: console.log}))
}

// when using react browserHistory, anchor all requests relative to one page to fix path issues (e.g. don't post to /robots/1234/api/robots/1234/update)
// this is not the code that tells react which page to use.
// this requires AJAX requests to use "/" preceding the request url (e.g. "/api/robots" instead of "api/robots")
// this enables proper requests from both the root url ("/") as well as from nested urls (e.g. "/robots/123")
//app.get('*', function (request, response){
//  response.sendFile(path.resolve(__dirname, 'views', 'robots', 'index.ejs'))
//})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>attempting to resolve an error whereby the browser wants to load the bundle and favicon but can't find them<commit_after>var express = require('express');
var path = require('path');
//var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var db = require("./db"); // starts a new mongoose connection

var routes = require('./routes/robots_controller');
var api_routes = require('./routes/api_controller');

var app = express();

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

//app.use(favicon(path.join(__dirname, 'public', 'images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'dist')));

app.use('/', routes);
app.use('/', api_routes);

// use webpack to bundle react components in development mode
if(process.env.NODE_ENV !== 'production') {
  var webpack = require('webpack');
  var webpackDevMiddleware = require('webpack-dev-middleware');
  var webpackHotMiddleware = require('webpack-hot-middleware');
  var config = require('./webpack.dev.config');
  var compiler = webpack(config);

  app.use(webpackDevMiddleware(compiler, {noInfo: true, publicPath: config.output.publicPath}));
  app.use(webpackHotMiddleware(compiler, {log: console.log}))
}

// when using react browserHistory, anchor all requests relative to one page to fix path issues (e.g. don't post to /robots/1234/api/robots/1234/update)
// this is not the code that tells react which page to use.
// this requires AJAX requests to use "/" preceding the request url (e.g. "/api/robots" instead of "api/robots")
// this enables proper requests from both the root url ("/") as well as from nested urls (e.g. "/robots/123")
//app.get('*', function (request, response){
//  response.sendFile(path.resolve(__dirname, 'views', 'robots', 'index.ejs'))
//})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>


<commit_before>var fs = require('fs');
var http = require('http');

process.title = "outport(node)";

var paths = {
    '/publish': function(req, res){
        req.addListener("data", function(chunk) {
            req.content += chunk;
        });

        req.addListener("end", function() {
            //parse req.content and do stuff with it
        });
    }
}

var server = http.createServer(function(req, res) {
//    req.setEncoding("utf8");
//    req.content = '';

    var body = 'not yet implemented';
        console.log(req);

    if (req.method === 'POST') {
        console.log(req);
        body = "Oh, so you want to do a post, eh?"
        // pipe the request data to the console
//        req.pipe(process.stdout);
        var w = fs.createWriteStream('output.dat');
        req.pipe(w);
        req.on('end', function () {
            res.writeHead(200, {
                'Content-Length': body.length,
                'Content-Type': 'text/plain' });
            res.write(body);
          res.end();
          fs.renameSync('output.dat', 'latest.ics');
        });

               //        req.on('data', function (chunk) {

        //}
    } else {
      body = "Methods other than POST don't really do anything."
      res.writeHead(200, {
        'Content-Length': body.length,
        'Content-Type': 'text/plain' });
      res.write(body);
      res.end();
    }

}).listen(8002);

<commit_msg>add comments<commit_after>// This simple node application listens to a port and accepts post requests.
// It writes the posted data into 'output.dat' and then moves it to 'latest.ics'
// It's intended to be proxied by nginx or yxorp into the server namespace.

var fs = require('fs');
var http = require('http');

process.title = "outport(node)";

var paths = {
    '/publish': function(req, res){
        req.addListener("data", function(chunk) {
            req.content += chunk;
        });

        req.addListener("end", function() {
            //parse req.content and do stuff with it
        });
    }
}

var server = http.createServer(function(req, res) {
//    req.setEncoding("utf8");
//    req.content = '';

    var body = 'not yet implemented';
        console.log(req);

    if (req.method === 'POST') {
        console.log(req);
        body = "Oh, so you want to do a post, eh?"
        // pipe the request data to the console
//        req.pipe(process.stdout);
        var w = fs.createWriteStream('output.dat');
        req.pipe(w);
        req.on('end', function () {
            res.writeHead(200, {
                'Content-Length': body.length,
                'Content-Type': 'text/plain' });
            res.write(body);
          res.end();
          fs.renameSync('output.dat', 'latest.ics');
        });

               //        req.on('data', function (chunk) {

        //}
    } else {
      body = "Methods other than POST don't really do anything."
      res.writeHead(200, {
        'Content-Length': body.length,
        'Content-Type': 'text/plain' });
      res.write(body);
      res.end();
    }

}).listen(8002);

<|endoftext|>


<commit_before>var express = require('express');
var router = require('./lib/router');
var http = require('http');
var path = require('path');
var app = express();
var config = require('./config/site');

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/themes/' + config.theme + '/views');
  app.set('view engine', 'hbs');
  app.use(express.favicon(__dirname + '/public/favicon.ico', { maxAge: 2592000000 }));
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use('/themes', express.static(path.join(__dirname, 'themes')));
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

router.setup(app);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port') + ' in ' + app.get('env') + ' mode');
});<commit_msg>Added global requireRoot function<commit_after>var express = require('express');
var router = require('./lib/router');
var http = require('http');
var path = require('path');
var app = express();
var config = require('./config/site');

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/themes/' + config.theme + '/views');
  app.set('view engine', 'hbs');
  app.use(express.favicon(__dirname + '/public/favicon.ico', { maxAge: 2592000000 }));
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use('/themes', express.static(path.join(__dirname, 'themes')));
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

GLOBAL.requireRoot = function(module) {
  return require(__dirname + module);
};

router.setup(app);

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port') + ' in ' + app.get('env') + ' mode');
});<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var parser = require('body-parser').urlencoded({ extended: false  });
var port = process.env.PORT || 3000;
var token = process.env.TOKEN || 'secretToken';

app.get('/', function (req, res) {
	res.send('Nothing here :O');
});

app.post('/', parser , function (req, res) {
	if(req.body.token === token){

		var callback = function(data){
			console.log(data);
			res.status(200).send(code +'\n-> ' + data);
		};
		var code = req.body.text;

		(new Function("log", code))(callback); // Perform the call

		// Need <code> encoding and format check, callback malformed data check, and timeout if log() is never called
	} else {
		res.status(404).send('Bad token');
	}
});

app.listen(port, function () {
	console.log('Magic on port %s',  port);
});
<commit_msg>added custom log and error reporting<commit_after>var express = require('express');
var app = express();
var parser = require('body-parser').urlencoded({ extended: false  });
var port = process.env.PORT || 3000;
var token = process.env.TOKEN || 'DJILKeK9aJPySkox3wXSK0Bb' || 'secretToken';

app.get('/', function (req, res) {
	res.send('Nothing here :O');
});

app.post('/', parser , function (req, res) {
	if(req.body.token === token){

		// callback to be called on done()
		var callback = function(data){
			// the response is the executed code and the logs joined
			var response = code +'\n-> ' + logs.join('\n');
			console.log(response)
			res.status(200).send(response);
		};

		// get user code to execute
		var code = req.body.text;

		var logs = [];
		// reduce scope of the evaluated function
		(function(process){
			// custom log function to be used
			log = function(a){
				console.log('console : ' + a);
				logs.push(a);
			};
			// catch errors
			try{
				(new Function("done", code))(callback); // Perform the call
			} catch(e){
				res.status(500).send('Error : ' + code + '\n' +e);
			}
		})();

		// Need <code> encoding and format check, callback malformed data check, and timeout if log() is never called
	} else {
		res.status(404).send('Bad token');
	}
});

app.listen(port, function () {
	console.log('Magic on port %s',  port);
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) Microsoft Corporation
 *  All Rights Reserved
 *  Apache License 2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @flow
 */

'use strict';

/**
 * Module dependencies.
 */

var express = require('express');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var util = require('util');
var bunyan = require('bunyan');
var config = require('./config');

// Enable CORS for server up custom HTML pages for B2C
//
var cors = require('cors');

// Enable SSL
//
var https = require('https');
var fs = require('fs');

var appkey = fs.readFileSync('app-key.pem');
var appcert = fs.readFileSync('app-cert.pem');

var options = {
  key: appkey,
  cert: appcert
};

// Start QuickStart here
//
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;

// Add some logging
var log = bunyan.createLogger({
    name: 'Microsoft OIDC Example Web Application'
});

// Passport session setup. (Section 2)
//
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.
// Passport session setup. (Section 2)

//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.
passport.serializeUser(function(user, done) {
  done(null, user.email);
});

passport.deserializeUser(function(id, done) {
  findByEmail(id, function (err, user) {
    done(err, user);
  });
});

// array to hold logged in users
var users = [];

var findByEmail = function(email, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    log.info('we are using user: ', user);
    if (user.email === email) {
      return fn(null, user);
    }
  }
  return fn(null, null);
};

// Use the OIDCStrategy within Passport. (Section 2)
//
//   Strategies in passport require a `validate` function, which accept
//   credentials (in this case, an OpenID identifier), and invoke a callback
//   with a user object.
passport.use(new OIDCStrategy({
    callbackURL: config.creds.returnURL,
    realm: config.creds.realm,
    clientID: config.creds.clientID,
    clientSecret: config.creds.clientSecret,
    oidcIssuer: config.creds.issuer,
    identityMetadata: config.creds.identityMetadata,
    responseType: config.creds.responseType,
    responseMode: config.creds.responseMode,
    skipUserProfile: config.creds.skipUserProfile,
    tenantName: config.creds.tenantName
    //scope: config.creds.scope
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    log.info('Example: Email address we received was: ', profile.email);
    // asynchronous verification, for effect...
    process.nextTick(function () {
      findByEmail(profile.email, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          // "Auto-registration"
          users.push(profile);
          return done(null, profile);
        }
        return done(null, user);
      });
    });
  }
));

// configure Express (Section 2)
var app = express();

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.methodOverride());
  app.use(cookieParser());
  app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
  app.use(bodyParser.urlencoded({ extended : true }));
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

// Routes (Section 4)

// Some routes for static content
//
// app.options('/public/*', cors());
app.get('/public/*', cors(), function(req, res, next){
  res.sendfile(req.params[0], {root: './public'});
});

app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', function(req, res){
  res.render('account', { user: req.user._json });
});

app.get('/login',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {
    log.info('Login was called in the Sample');
    res.redirect('/');
});

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

// GET /auth/openid
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in OpenID authentication will involve redirecting
//   the user to their OpenID provider.  After authenticating, the OpenID
//   provider will redirect the user back to this application at
//   /auth/openid/return

app.get('/auth/openid',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {
    log.info('Authenitcation was called in the Sample');
    res.redirect('/');
  });

// GET /auth/openid/return
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/openid/return',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {

    res.redirect('/');
  });

// POST /auth/openid/return
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.

app.post('/auth/openid/return',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {

    res.redirect('/');
  });

// Listen on http but redirect the calls to https
//
var http = require('http');
// var http = express.createServer();
http.get('*',function(req,res){
    res.redirect('https://proseware.skwantoso.com'+req.url)
});
http.createServer(app).listen(8080);
// http.listen(8080);

// Enable SSL
//
https.createServer(options, app).listen(8443);

// Simple route middleware to ensure user is authenticated. (Section 4)
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login?p=B2C_1_StandardSignIn')
}

<commit_msg>Try to fix error message on startup<commit_after>/**
 * Copyright (c) Microsoft Corporation
 *  All Rights Reserved
 *  Apache License 2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @flow
 */

'use strict';

/**
 * Module dependencies.
 */

var express = require('express');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var util = require('util');
var bunyan = require('bunyan');
var config = require('./config');

// Enable CORS for server up custom HTML pages for B2C
//
var cors = require('cors');

// Enable SSL
//
var https = require('https');
var fs = require('fs');

var appkey = fs.readFileSync('app-key.pem');
var appcert = fs.readFileSync('app-cert.pem');

var options = {
  key: appkey,
  cert: appcert
};

// Start QuickStart here
//
var OIDCStrategy = require('passport-azure-ad').OIDCStrategy;

// Add some logging
var log = bunyan.createLogger({
    name: 'Microsoft OIDC Example Web Application'
});

// Passport session setup. (Section 2)
//
//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.
// Passport session setup. (Section 2)

//   To support persistent login sessions, Passport needs to be able to
//   serialize users into and deserialize users out of the session.  Typically,
//   this will be as simple as storing the user ID when serializing, and finding
//   the user by ID when deserializing.
passport.serializeUser(function(user, done) {
  done(null, user.email);
});

passport.deserializeUser(function(id, done) {
  findByEmail(id, function (err, user) {
    done(err, user);
  });
});

// array to hold logged in users
var users = [];

var findByEmail = function(email, fn) {
  for (var i = 0, len = users.length; i < len; i++) {
    var user = users[i];
    log.info('we are using user: ', user);
    if (user.email === email) {
      return fn(null, user);
    }
  }
  return fn(null, null);
};

// Use the OIDCStrategy within Passport. (Section 2)
//
//   Strategies in passport require a `validate` function, which accept
//   credentials (in this case, an OpenID identifier), and invoke a callback
//   with a user object.
passport.use(new OIDCStrategy({
    callbackURL: config.creds.returnURL,
    realm: config.creds.realm,
    clientID: config.creds.clientID,
    clientSecret: config.creds.clientSecret,
    oidcIssuer: config.creds.issuer,
    identityMetadata: config.creds.identityMetadata,
    responseType: config.creds.responseType,
    responseMode: config.creds.responseMode,
    skipUserProfile: config.creds.skipUserProfile,
    tenantName: config.creds.tenantName
    //scope: config.creds.scope
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    log.info('Example: Email address we received was: ', profile.email);
    // asynchronous verification, for effect...
    process.nextTick(function () {
      findByEmail(profile.email, function(err, user) {
        if (err) {
          return done(err);
        }
        if (!user) {
          // "Auto-registration"
          users.push(profile);
          return done(null, profile);
        }
        return done(null, user);
      });
    });
  }
));

// configure Express (Section 2)
var app = express();

app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.methodOverride());
  app.use(cookieParser());
  app.use(expressSession({ secret: 'keyboard cat', resave: true, saveUninitialized: false }));
  app.use(bodyParser.urlencoded({ extended : true }));
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

// Routes (Section 4)

// Some routes for static content
//
// app.options('/public/*', cors());
app.get('/public/*', cors(), function(req, res, next){
  res.sendfile(req.params[0], {root: './public'});
});

app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', function(req, res){
  res.render('account', { user: req.user._json });
});

app.get('/login',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {
    log.info('Login was called in the Sample');
    res.redirect('/');
});

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

// GET /auth/openid
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in OpenID authentication will involve redirecting
//   the user to their OpenID provider.  After authenticating, the OpenID
//   provider will redirect the user back to this application at
//   /auth/openid/return

app.get('/auth/openid',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {
    log.info('Authenitcation was called in the Sample');
    res.redirect('/');
  });

// GET /auth/openid/return
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get('/auth/openid/return',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {

    res.redirect('/');
  });

// POST /auth/openid/return
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.

app.post('/auth/openid/return',
  passport.authenticate('azuread-openidconnect', { failureRedirect: '/login' }),
  function(req, res) {

    res.redirect('/');
  });

// Listen on http but redirect the calls to https
//
var http = require('http');
// var http = express.createServer();
http.createServer(app).listen(8080);
http.get('*',function(req,res){
    res.redirect('https://proseware.skwantoso.com'+req.url)
});
// http.listen(8080);

// Enable SSL
//
https.createServer(options, app).listen(8443);

// Simple route middleware to ensure user is authenticated. (Section 4)
//   Use this route middleware on any resource that needs to be protected.  If
//   the request is authenticated (typically via a persistent login session),
//   the request will proceed.  Otherwise, the user will be redirected to the
//   login page.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login?p=B2C_1_StandardSignIn')
}

<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var mongoose = require('mongoose');
var MONGO_ADD = process.env.MONGOTEST_PORT_27017_TCP_ADDR || "localhost"
var REDIST_ADD = process.env.REDISTEST_PORT_6379_TCP_ADDR || "localhost"
console.log(process.env.MONGOTEST_PORT_27017_TCP_PORT + REDISTEST_PORT_6379_TCP_PORT)
mongoose.connect("mongodb://" + MONGO_ADD + "/jenkins-demo");
require('./db/jenkins.demo.model');
mongoose.Promise = global.Promise;
require('./db/initdata');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

require('./routes')(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<commit_msg>add slave env<commit_after>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var mongoose = require('mongoose');
var MONGO_ADD = process.env.MONGOTEST_PORT_27017_TCP_ADDR || "localhost"
var REDIST_ADD = process.env.REDISTEST_PORT_6379_TCP_ADDR || "localhost"
console.log(process.env.MONGOTEST_PORT_27017_TCP_PORT + process.env.REDISTEST_PORT_6379_TCP_PORT)
mongoose.connect("mongodb://" + MONGO_ADD + "/jenkins-demo");
require('./db/jenkins.demo.model');
mongoose.Promise = global.Promise;
require('./db/initdata');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

require('./routes')(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;
<|endoftext|>