<commit_before>var express = require('express')
var router = express.Router()

// Route index page
router.get('/', function (req, res) {
  res.render('index')
})

// make radio-group button routes work

router.get('*/example-service/*', function (req, res) {

  var radioGroup = req.query['radio-group'];

  if (radioGroup) {

    res.redirect(radioGroup);

  } else {

    // if radio-group is any other value (or is missing) render the page requested

    var str = req.path;
    res.render( str.substring(1) );

  }
});

// add your routes here

router.all('/service-patterns/parking-permit/example-service/pre-payment', function (req, res) {

  function makeStartDate(permitWait, requestedDate) {
    let earliestDate = new Date()
    earliestDate.setDate(earliestDate.getDate() + Number(permitWait || 0))
    if (requestedDate < earliestDate) return earliestDate
    return requestedDate
  }

  function makeEndDate(startDate, length) {
    var date = new Date(startDate.getTime())
    date.setMonth(date.getMonth() + (length === '6 month' ? 6 : 12))
    return date
  }

  function makeDate(permitStartDate) {
    if (permitStartDate && permitStartDate.year !== '' && permitStartDate.month !== '' && permitStartDate.day !== '')
      return new Date(permitStartDate.year, permitStartDate.month - 1, permitStartDate.day)
    return new Date()
  }

  function makeCost(length, permitCostForNthPermit, permitsCosts) {
    let cost = permitCostForNthPermit || permitsCosts[permitsCosts.length - 1] || 0
    return (cost / (length === '6 month' ? 2 : 1)).toFixed(2)
  }

  const data = req.session.data
  const council = req.session.data.council
  const permitRequests = data.registerNumbers.map((registerNumber, i) => {
    let requestedStartDate = makeDate(data.permitStartDate[data.permitStartChoice] && (data.permitStartDate[data.permitStartChoice][i] || data.permitStartDate[data.permitStartChoice][0]))
    let startDate = makeStartDate(council.permitWait, requestedStartDate)
    let length = data.permitLength === 'multi-lengths' ? data.permitLengths[i] : data.permitLength
    return {
      registerNumber: registerNumber,
      startDate: startDate,
      endDate: makeEndDate(startDate, length),
      length: length,
      cost: makeCost(length, council.permitsCosts[i], council.permitsCosts)
    }
  })

  req.session.data.permitRequestData = {
    permitRequests: permitRequests,
    totalSum: permitRequests.reduce((sum, permit) => sum + Number(permit.cost), 0).toFixed(2)
  }

  res.render('service-patterns/parking-permit/example-service/pre-payment', {
    data: permitRequests
  });
})

router.get('/service-patterns/concessionary-travel/example-service/add-poa', function(req, res) {
  req.session.skip_verify = true

  res.render('service-patterns/concessionary-travel/example-service/add-poa')
})

router.get('/service-patterns/concessionary-travel/example-service/photo/success', function(req, res) {
  res.render('service-patterns/concessionary-travel/example-service/photo/success', { skip_verify: req.session.skip_verify})
})

router.get('/service-patterns/concessionary-travel/example-service/add-poa', function(req, res) {
  req.session.skip_verify = true

  res.render('service-patterns/concessionary-travel/example-service/add-poa')
})

router.get('/service-patterns/concessionary-travel/example-service/photo/success', function(req, res) {
  res.render('service-patterns/concessionary-travel/example-service/photo/success', { skip_verify: req.session.skip_verify})
})

module.exports = router
<commit_msg>Fix a nullpointer when user does not support permit start date<commit_after>var express = require('express')
var router = express.Router()

// Route index page
router.get('/', function (req, res) {
  res.render('index')
})

// make radio-group button routes work

router.get('*/example-service/*', function (req, res) {

  var radioGroup = req.query['radio-group'];

  if (radioGroup) {

    res.redirect(radioGroup);

  } else {

    // if radio-group is any other value (or is missing) render the page requested

    var str = req.path;
    res.render( str.substring(1) );

  }
});

// add your routes here

router.all('/service-patterns/parking-permit/example-service/pre-payment', function (req, res) {

  function makeStartDate(permitWait, requestedDate) {
    let earliestDate = new Date()
    earliestDate.setDate(earliestDate.getDate() + Number(permitWait || 0))
    if (requestedDate < earliestDate) return earliestDate
    return requestedDate
  }

  function makeEndDate(startDate, length) {
    var date = new Date(startDate.getTime())
    date.setMonth(date.getMonth() + (length === '6 month' ? 6 : 12))
    return date
  }

  function makeDate(permitStartDate) {
    if (permitStartDate && permitStartDate.year !== '' && permitStartDate.month !== '' && permitStartDate.day !== '')
      return new Date(permitStartDate.year, permitStartDate.month - 1, permitStartDate.day)
    return new Date()
  }

  function makeCost(length, permitCostForNthPermit, permitsCosts) {
    let cost = permitCostForNthPermit || permitsCosts[permitsCosts.length - 1] || 0
    return (cost / (length === '6 month' ? 2 : 1)).toFixed(2)
  }

  const data = req.session.data
  const council = req.session.data.council
  const permitRequests = data.registerNumbers.map((registerNumber, i) => {
    let permitStartDate = data.permitStartDate || {}
    let requestedStartDate = makeDate(permitStartDate[data.permitStartChoice] && (permitStartDate[data.permitStartChoice][i] || permitStartDate[data.permitStartChoice][0]))
    let startDate = makeStartDate(council.permitWait, requestedStartDate)
    let length = data.permitLength === 'multi-lengths' ? data.permitLengths[i] : data.permitLength
    return {
      registerNumber: registerNumber,
      startDate: startDate,
      endDate: makeEndDate(startDate, length),
      length: length,
      cost: makeCost(length, council.permitsCosts[i], council.permitsCosts)
    }
  })

  req.session.data.permitRequestData = {
    permitRequests: permitRequests,
    totalSum: permitRequests.reduce((sum, permit) => sum + Number(permit.cost), 0).toFixed(2)
  }

  res.render('service-patterns/parking-permit/example-service/pre-payment', {
    data: permitRequests
  });
})

router.get('/service-patterns/concessionary-travel/example-service/add-poa', function(req, res) {
  req.session.skip_verify = true

  res.render('service-patterns/concessionary-travel/example-service/add-poa')
})

router.get('/service-patterns/concessionary-travel/example-service/photo/success', function(req, res) {
  res.render('service-patterns/concessionary-travel/example-service/photo/success', { skip_verify: req.session.skip_verify})
})

router.get('/service-patterns/concessionary-travel/example-service/add-poa', function(req, res) {
  req.session.skip_verify = true

  res.render('service-patterns/concessionary-travel/example-service/add-poa')
})

router.get('/service-patterns/concessionary-travel/example-service/photo/success', function(req, res) {
  res.render('service-patterns/concessionary-travel/example-service/photo/success', { skip_verify: req.session.skip_verify})
})

module.exports = router
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import { Route,Router, IndexRoute } from 'react-router';
import App from './containers/App';
import Home from './containers/Home';
import FaceContainer from './containers/FaceContainer';
import Setting from './containers/Setting';
import SignUp from './containers/SignUp';
import SignInContainer from './containers/SignInContainer';
import BlankContainer from './containers/BlankContainer';

export default (
	<Route path="/" component={App}>
		<IndexRoute component={Home} />
		<Route path="off" component={BlankContainer} />
		<Route path="home" component={Home} />
		<Route path="on" component={Home} />
		<Route path="login" component={FaceContainer} />
		<Route path="signup" component={SignUp} />
		<Route path="setting" component={Setting} />
	</Route>
);
<commit_msg>fix routes<commit_after>// @flow
import React from 'react';
import { Route,Router, IndexRoute } from 'react-router';
import App from './containers/App';
import Home from './containers/Home';
import FaceContainer from './containers/FaceContainer';
import SettingContainer from './containers/SettingContainer';
import SignUpContainer from './containers/SignUpContainer';
import SignInContainer from './containers/SignInContainer';
import BlankContainer from './containers/BlankContainer';

export default (
	<Route path="/" component={App}>
		<IndexRoute component={Home} />
		<Route path="off" component={BlankContainer} />
		<Route path="home" component={Home} />
		<Route path="on" component={Home} />
		<Route path="login" component={FaceContainer} />
		<Route path="signup" component={SignUpContainer} />
		<Route path="setting" component={SettingContainer} />
	</Route>
);
<|endoftext|>


<commit_before>define(['app', 'lodash', 'text!views/index.html','text!./redirect-dialog.html', 'views/index', 'providers/extended-route', 'authentication','ngDialog','ngCookies'], function(app, _, rootTemplate, redirectDialog) { 'use strict';
    var locationPath = window.location.pathname.toLowerCase().split('?')[0];
    app.config(['extendedRouteProvider', '$locationProvider',function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                             { template:    rootTemplate,  label:'Home',  resolveController: 'views/index', reloadOnSearch : false }).
            when('/home', { redirectTo: '/' }).

            when('/about',                       { templateUrl: 'views/about/index.html',         label:'Biodiversity',  resolveController: true }).
            when('/about/undb',                   { templateUrl: 'views/about/index.html',         label:'UNDB',          }).
            when('/about/goals',                  { templateUrl: 'views/about/goals.html',         label:'Goals',         }).
            when('/about/biodiversity',           { templateUrl: 'views/about/biodiversity.html',  label:'Biodiversity',  resolveController: true }).
            when('/about/iyb2010',                { templateUrl: 'views/about/iyb2010.html',       label:'IYB2010',       }).
            when('/about/sdgs',                   { templateUrl: 'views/about/sdgs.html',          label:'SDGs',          }).

            when('/actions',                      { redirectTo:  '/actions/worldwide' }).
            when('/actions/ccc',                  { templateUrl: 'views/actions/ccc.html',       label:'Commitments',              resolveController: true}).

            when('/actions/worldwide',            { templateUrl: 'views/actions/worldwide.html',        label:'Worldwide',            resolveController: true , reloadOnSearch : false}).
            when('/actions/country',              { templateUrl: 'views/actions/country.html',          label:'By Country',           resolveController: true }).
            when('/actions/countries/:code',      { templateUrl: 'views/actions/country-profile.html',  label :'Profile',             resolveController: true }).
            // when('/actions/countries/edit/:code', { templateUrl: 'views/actions/country-profile-form.html', label:'Edit Party Profile',   resolveController: true, resolve : { user : securize(["UNDBPublishingAuthority", "undb-administrator"]) } }).

           // when('/actions/un',                 { templateUrl: 'views/actions/un.html',               label:'By UN Organization',   resolveController: true }).
            when('/actions/calendar',             { templateUrl: 'views/actions/calendar.html',         label:'Calendar',             resolveController: true }).
            when('/actions/participate',          { templateUrl: 'views/actions/participate.html',      label:'Participate'           }).
            // when('/actions/submit',               { templateUrl: 'views/actions/submit.html',           label:'Participate',          resolveController: true, resolve : { user : securize(['User']) }, reloadOnSearch : false }).
            // when('/actions/register/:uid?',       { templateUrl: 'views/actions/submit-form.html',      label:'Form',                 resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actions/submit-form/:uid?',    { templateUrl: 'views/actions/submit-form.html',      label:'Form',                 resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actions/submit-form-done',     { templateUrl: 'views/actions/submit-form-done.html', label:'Thanks',               resolve : { user : securize(['User']) } }).
// when('/actions/submit', { redirectTo: '/dashboard/submit/event/new' }).
// when('/actions/register/:uid?', { redirectTo: '/dashboard/submit/event/:id' }).
// when('/actions/submit-form/:uid?', { redirectTo: '/dashboard/submit/event/:id' }).
// when('/actions/submit-form-done', { redirectTo: '/dashboard' }).

            when('/actions/:uid',                 { templateUrl: 'views/actions/action.html',           label:'Action',               resolveController: true }).

            when('/actors',                      { templateUrl: 'views/actors/index.html',            label:'Actors',                  resolveController: true}).
            when('/actors/abttf',                { templateUrl: 'views/actors/abttf.html',            label:'ABTTF',                   resolveController: true}).
            when('/actors/champions',            { templateUrl: 'views/actors/champions.html',        label:'Biodiversity Champions',  resolveController: true}).
            when('/actors/blg',                  { templateUrl: 'views/actors/blg.html',              label:'BLG',                     resolveController: true}).
            when('/actors/country',              { templateUrl: 'views/actors/country.html',          label:'By Country',           resolveController: true }).

            when('/actors/jlg',                  { templateUrl: 'views/actors/jlg.html',              label:'JLG' ,                    resolveController: true}).
            when('/actors/submit',               { templateUrl: 'views/actors/submit.html',           label:'Participate',             resolveController: true, resolve : { user : securize(['User']) }, reloadOnSearch : false }).
            when('/actors/partners',             { templateUrl: 'views/actors/partners.html',         label:'UNDB Partners',           resolveController: true, resolve : { user : currentUser() } }).
            when('/actors/partners/:uid',        { templateUrl: 'views/actors/actor.html',            label:'Actor',                   resolveController: true }).

            // when('/actors/partners/register', { redirectTo: '/dashboard/submit/undb-actor/new' }).
            // when('/actors/register?', { redirectTo: '/dashboard/submit/undb-actor/:id' }).
            // when('/actors/register/:uid', { redirectTo: '/dashboard/submit/undb-actor/:id' }).
            // when('/actors/partners/edit/:uid', { redirectTo: '/dashboard/submit/undb-actor/:id'}).
            // when('/actors/partners/register',    { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/register',             { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/register/:uid',        { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/partners/edit/:uid',   { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/submit-form-done',     { templateUrl: 'views/actors/submit-form-done.html', label:'Thanks',                  resolve : { user : securize(['User']) } }).

            when('/resources',                   { templateUrl: 'views/resources/index.html',           label:'Resources'         }).
            when('/resources/logo',              { templateUrl: 'views/resources/logo.html',            label:'Logo',                  resolveController: true}).
            when('/resources/materials',         { templateUrl: 'views/resources/materials.html',       label:'Printed Materials' }).
            when('/resources/multimedia',        { templateUrl: 'views/resources/multimedia.html',      label:'Multimedia',            resolveController: true}).
            when('/resources/multimedia/edit',   { templateUrl: 'views/resources/multimedia-form.html', label:'Multimedia',            resolveController: true}).
            when('/resources/waiver',            { templateUrl: 'views/resources/waiver.html',          label:'Waiver',                resolveController: true}).
            when('/resources/waiver/submit',     { templateUrl: 'views/resources/submit-waiver.html',   label:'Submit Waiver',         resolveController: true, resolve : { user : securize(['User']) } }).
            when('/resources/waiver/submit-done',{ templateUrl: 'views/resources/submit-form-done.html',label:'Submit Waiver done' }).
            when('/resources/un-logo',           { templateUrl: 'views/resources/un-logo.html',         label:'UN Logo Use' }).
            when('/resources/contact',           { templateUrl: 'views/resources/contact.html',         label:'Contact Us' }).

            when('/dashboard',                   { templateUrl: 'views/dashboard/index-dash.html',    controllerAs: 'dashCtrl',    resolveController: true ,resolve : { user : securize(['User']) }}).
            when('dashboard/submit/:schema',         { templateUrl: 'views/dashboard/record-list.html',  controllerAs: 'submitCtrl',  resolveController: true,resolve : { user : securize(['User']) } }).
            when('dashboard/submit/:schema/:id',     { templateUrl: 'views/dashboard/edit.html',         controllerAs: 'editCtrl',    resolveController: true ,resolve : { user : securize(['User']) }}).
            when('dashboard/submit/:schema/:id/view',{ templateUrl: 'views/dashboard/view.html',    controllerAs: 'viewCtrl',    resolveController: true,resolve : { user : securize(['Everyone']) } }).

            when('/help/404',                    { templateUrl: 'views/404.html',  controllerAs: 'notFoundCtrl',resolveController: true ,label : 'Not found',resolve : {path:currentPath}  }).
            when('/help/403',                    { templateUrl: 'views/403.html',   label : 'Forbidden' }).
            otherwise({ redirectTo: '/help/404' });
    }]);

    //============================================================
    //
    //
    //============================================================
    function currentUser() {

        return ['authentication', function (authentication) {

            return authentication.getUser();
        }];
    }
    //============================================================
    //
    //
    //============================================================
    function currentPath() {

        return locationPath;
    }
    //============================================================
    //
    //
    //============================================================
    function securize(requiredRoles) {

        return ['$q', '$rootScope', 'authentication', '$location', '$window','ngDialog','$cookies', function($q, $rootScope, authentication, $location, $window,ngDialog,$cookies) {

            return $q.when(authentication.getUser()).then(function (user) {

                var hasRole = !!_.intersection(user.roles, requiredRoles).length;

                if (!user.isAuthenticated) {
                    $rootScope.authRediectChange=authRediectChange;
                    if(!!_.intersection(requiredRoles, ['Everyone']).length)
                      return user;

                    if(!$cookies.get('redirectOnAuthMsg') || $cookies.get('redirectOnAuthMsg')==='false')
                        openDialog();
                    else
                        $window.location.href = authentication.accountsBaseUrl()+'/signin?returnurl='+encodeURIComponent($location.absUrl());

                    throw user; // stop route change!
                }
                else if (!hasRole)
                    $location.url('/403?returnurl='+encodeURIComponent($location.url()));

                return user;
            });

            //============================================================
            //
            //
            //============================================================
            function openDialog() {
                $rootScope.redirectOnAuthMsg=true;
                $cookies.put('redirectOnAuthMsg',true);
                ngDialog.open({
                      template: redirectDialog,
                      className: 'ngdialog-theme-default',
                      closeByDocument: false,
                      plain: true,
                      scope:$rootScope
                  }).closePromise.then(function(retVal){
                        if(retVal.value)
                          $window.location.href = authentication.accountsBaseUrl()+'/signin?returnurl='+encodeURIComponent($location.absUrl());
                        else
                          $window.history.back();
                  });
            }
            //============================================================
            //
            //
            //============================================================
            function authRediectChange(value) {
                $cookies.put('redirectOnAuthMsg',value);
            }//authRediectChange

        }];//return array
    }//securize

});
<commit_msg>fix broken routes<commit_after>define(['app', 'lodash', 'text!views/index.html','text!./redirect-dialog.html', 'views/index', 'providers/extended-route', 'authentication','ngDialog','ngCookies'], function(app, _, rootTemplate, redirectDialog) { 'use strict';
    var locationPath = window.location.pathname.toLowerCase().split('?')[0];
    app.config(['extendedRouteProvider', '$locationProvider',function($routeProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $locationProvider.hashPrefix('!');

        $routeProvider.
            when('/',                             { template:    rootTemplate,  label:'Home',  resolveController: 'views/index', reloadOnSearch : false }).
            when('/home', { redirectTo: '/' }).

            when('/about',                       { templateUrl: 'views/about/index.html',         label:'Biodiversity',  resolveController: true }).
            when('/about/undb',                   { templateUrl: 'views/about/index.html',         label:'UNDB',          }).
            when('/about/goals',                  { templateUrl: 'views/about/goals.html',         label:'Goals',         }).
            when('/about/biodiversity',           { templateUrl: 'views/about/biodiversity.html',  label:'Biodiversity',  resolveController: true }).
            when('/about/iyb2010',                { templateUrl: 'views/about/iyb2010.html',       label:'IYB2010',       }).
            when('/about/sdgs',                   { templateUrl: 'views/about/sdgs.html',          label:'SDGs',          }).

            when('/actions',                      { redirectTo:  '/actions/worldwide' }).
            when('/actions/ccc',                  { templateUrl: 'views/actions/ccc.html',       label:'Commitments',              resolveController: true}).

            when('/actions/worldwide',            { templateUrl: 'views/actions/worldwide.html',        label:'Worldwide',            resolveController: true , reloadOnSearch : false}).
            when('/actions/country',              { templateUrl: 'views/actions/country.html',          label:'By Country',           resolveController: true }).
            when('/actions/countries/:code',      { templateUrl: 'views/actions/country-profile.html',  label :'Profile',             resolveController: true }).
            // when('/actions/countries/edit/:code', { templateUrl: 'views/actions/country-profile-form.html', label:'Edit Party Profile',   resolveController: true, resolve : { user : securize(["UNDBPublishingAuthority", "undb-administrator"]) } }).

           // when('/actions/un',                 { templateUrl: 'views/actions/un.html',               label:'By UN Organization',   resolveController: true }).
            when('/actions/calendar',             { templateUrl: 'views/actions/calendar.html',         label:'Calendar',             resolveController: true }).
            when('/actions/participate',          { templateUrl: 'views/actions/participate.html',      label:'Participate'           }).
            // when('/actions/submit',               { templateUrl: 'views/actions/submit.html',           label:'Participate',          resolveController: true, resolve : { user : securize(['User']) }, reloadOnSearch : false }).
            // when('/actions/register/:uid?',       { templateUrl: 'views/actions/submit-form.html',      label:'Form',                 resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actions/submit-form/:uid?',    { templateUrl: 'views/actions/submit-form.html',      label:'Form',                 resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actions/submit-form-done',     { templateUrl: 'views/actions/submit-form-done.html', label:'Thanks',               resolve : { user : securize(['User']) } }).
// when('/actions/submit', { redirectTo: '/dashboard/submit/event/new' }).
// when('/actions/register/:uid?', { redirectTo: '/dashboard/submit/event/:id' }).
// when('/actions/submit-form/:uid?', { redirectTo: '/dashboard/submit/event/:id' }).
// when('/actions/submit-form-done', { redirectTo: '/dashboard' }).

            when('/actions/:uid',                 { templateUrl: 'views/actions/action.html',           label:'Action',               resolveController: true }).

            when('/actors',                      { templateUrl: 'views/actors/index.html',            label:'Actors',                  resolveController: true}).
            when('/actors/abttf',                { templateUrl: 'views/actors/abttf.html',            label:'ABTTF',                   resolveController: true}).
            when('/actors/champions',            { templateUrl: 'views/actors/champions.html',        label:'Biodiversity Champions',  resolveController: true}).
            when('/actors/blg',                  { templateUrl: 'views/actors/blg.html',              label:'BLG',                     resolveController: true}).
            when('/actors/country',              { templateUrl: 'views/actors/country.html',          label:'By Country',           resolveController: true }).

            when('/actors/jlg',                  { templateUrl: 'views/actors/jlg.html',              label:'JLG' ,                    resolveController: true}).
            when('/actors/submit',               { templateUrl: 'views/actors/submit.html',           label:'Participate',             resolveController: true, resolve : { user : securize(['User']) }, reloadOnSearch : false }).
            when('/actors/partners',             { templateUrl: 'views/actors/partners.html',         label:'UNDB Partners',           resolveController: true, resolve : { user : currentUser() } }).
            when('/actors/partners/:uid',        { templateUrl: 'views/actors/actor.html',            label:'Actor',                   resolveController: true }).

            // when('/actors/partners/register', { redirectTo: '/dashboard/submit/undb-actor/new' }).
            // when('/actors/register?', { redirectTo: '/dashboard/submit/undb-actor/:id' }).
            // when('/actors/register/:uid', { redirectTo: '/dashboard/submit/undb-actor/:id' }).
            // when('/actors/partners/edit/:uid', { redirectTo: '/dashboard/submit/undb-actor/:id'}).
            // when('/actors/partners/register',    { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/register',             { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/register/:uid',        { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/partners/edit/:uid',   { templateUrl: 'views/actors/submit-form.html',      label:'Become a UNDB Partner',   resolveController: true, resolve : { user : securize(['User']) } }).
            // when('/actors/submit-form-done',     { templateUrl: 'views/actors/submit-form-done.html', label:'Thanks',                  resolve : { user : securize(['User']) } }).

            when('/resources',                   { templateUrl: 'views/resources/index.html',           label:'Resources'         }).
            when('/resources/logo',              { templateUrl: 'views/resources/logo.html',            label:'Logo',                  resolveController: true}).
            when('/resources/materials',         { templateUrl: 'views/resources/materials.html',       label:'Printed Materials' }).
            when('/resources/multimedia',        { templateUrl: 'views/resources/multimedia.html',      label:'Multimedia',            resolveController: true}).
            when('/resources/multimedia/edit',   { templateUrl: 'views/resources/multimedia-form.html', label:'Multimedia',            resolveController: true}).
            when('/resources/waiver',            { templateUrl: 'views/resources/waiver.html',          label:'Waiver',                resolveController: true}).
            when('/resources/waiver/submit',     { templateUrl: 'views/resources/submit-waiver.html',   label:'Submit Waiver',         resolveController: true, resolve : { user : securize(['User']) } }).
            when('/resources/waiver/submit-done',{ templateUrl: 'views/resources/submit-form-done.html',label:'Submit Waiver done' }).
            when('/resources/un-logo',           { templateUrl: 'views/resources/un-logo.html',         label:'UN Logo Use' }).
            when('/resources/contact',           { templateUrl: 'views/resources/contact.html',         label:'Contact Us' }).

            when('/dashboard',                   { templateUrl: 'views/dashboard/index-dash.html',    controllerAs: 'dashCtrl',    resolveController: true ,resolve : { user : securize(['User']) }}).
            when('/dashboard/submit/:schema',         { templateUrl: 'views/dashboard/record-list.html',  controllerAs: 'submitCtrl',  resolveController: true,resolve : { user : securize(['User']) } }).
            when('/dashboard/submit/:schema/:id',     { templateUrl: 'views/dashboard/edit.html',         controllerAs: 'editCtrl',    resolveController: true ,resolve : { user : securize(['User']) }}).
            when('/dashboard/submit/:schema/:id/view',{ templateUrl: 'views/dashboard/view.html',    controllerAs: 'viewCtrl',    resolveController: true,resolve : { user : securize(['Everyone']) } }).

            when('/help/404',                    { templateUrl: 'views/404.html',  controllerAs: 'notFoundCtrl',resolveController: true ,label : 'Not found',resolve : {path:currentPath}  }).
            when('/help/403',                    { templateUrl: 'views/403.html',   label : 'Forbidden' }).
            otherwise({ redirectTo: '/help/404' });
    }]);

    //============================================================
    //
    //
    //============================================================
    function currentUser() {

        return ['authentication', function (authentication) {

            return authentication.getUser();
        }];
    }
    //============================================================
    //
    //
    //============================================================
    function currentPath() {

        return locationPath;
    }
    //============================================================
    //
    //
    //============================================================
    function securize(requiredRoles) {

        return ['$q', '$rootScope', 'authentication', '$location', '$window','ngDialog','$cookies', function($q, $rootScope, authentication, $location, $window,ngDialog,$cookies) {

            return $q.when(authentication.getUser()).then(function (user) {

                var hasRole = !!_.intersection(user.roles, requiredRoles).length;

                if (!user.isAuthenticated) {
                    $rootScope.authRediectChange=authRediectChange;
                    if(!!_.intersection(requiredRoles, ['Everyone']).length)
                      return user;

                    if(!$cookies.get('redirectOnAuthMsg') || $cookies.get('redirectOnAuthMsg')==='false')
                        openDialog();
                    else
                        $window.location.href = authentication.accountsBaseUrl()+'/signin?returnurl='+encodeURIComponent($location.absUrl());

                    throw user; // stop route change!
                }
                else if (!hasRole)
                    $location.url('/403?returnurl='+encodeURIComponent($location.url()));

                return user;
            });

            //============================================================
            //
            //
            //============================================================
            function openDialog() {
                $rootScope.redirectOnAuthMsg=true;
                $cookies.put('redirectOnAuthMsg',true);
                ngDialog.open({
                      template: redirectDialog,
                      className: 'ngdialog-theme-default',
                      closeByDocument: false,
                      plain: true,
                      scope:$rootScope
                  }).closePromise.then(function(retVal){
                        if(retVal.value)
                          $window.location.href = authentication.accountsBaseUrl()+'/signin?returnurl='+encodeURIComponent($location.absUrl());
                        else
                          $window.history.back();
                  });
            }
            //============================================================
            //
            //
            //============================================================
            function authRediectChange(value) {
                $cookies.put('redirectOnAuthMsg',value);
            }//authRediectChange

        }];//return array
    }//securize

});
<|endoftext|>


<commit_before>// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from './utils/asyncInjectors';

const errorLoading = (err) => {
  console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};

const loadModule = (cb) => (componentModule) => {
  cb(null, componentModule.default);
};

export default function createRoutes(store) {
  // create reusable async injectors using getAsyncInjectors factory
  const { injectReducer } = getAsyncInjectors(store);

  return [
    {
      path: '/index.html',
      name: 'home',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/HomePage/reducer'),
          import('containers/HomePage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('home', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/',
      name: 'home',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/HomePage/reducer'),
          import('containers/HomePage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('home', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/features',
      name: 'features',
      getComponent(nextState, cb) {
        import('containers/FeaturePage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: 'activityMaps',
      name: 'activityMaps',
      getComponent(location, cb) {
        import('containers/ActivityMapsPage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: 'pourbaixDiagrams',
      name: 'pourbaixDiagramsPage',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/PourbaixDiagramsPage/reducer'),
          import('containers/PourbaixDiagramsPage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('pourbaixDiagramsPage', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/energies',
      name: 'energiesPage',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/EnergiesPage/reducer'),
          import('containers/EnergiesPage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('energiesPage', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/scalingRelations',
      name: 'scalingRelationsPage',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/ScalingRelationsPage/reducer'),
          import('containers/ScalingRelationsPage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('scalingRelationsPage', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/publications',
      name: 'publications',
      getComponent(location, cb) {
        import('components/Publications')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/yourNextApp',
      name: 'yourNextApp',
      getComponent(location, cb) {
        import('components/YourNextApp')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/generalSearch',
      name: 'generalSearch',
      getComponent(location, cb) {
        import('components/GeneralSearch')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/graphQLConsole',
      name: 'graphQlapi',
      getComponent(location, cb) {
        import('components/GraphQlapi')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/plotlyDemo',
      name: 'plotlyDemo',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/PlotlyDemo/reducer'),
          import('containers/PlotlyDemo'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('plotlyDemo', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/catKitDemo(/:data)',
      name: 'catKitDemo',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/CatKitDemo/reducer'),
          import('containers/CatKitDemo'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('catKitDemo', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/catKitDemo(/:lattice/:latticeConstant/:composition)',
      name: 'catKitDemo',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/CatKitDemo/reducer'),
          import('containers/CatKitDemo'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('catKitDemo', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/profile(/:name)',
      name: 'profile',
      getComponent(location, cb) {
        import('containers/Profile')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: 'appsIndex',
      name: 'apps',
      getComponent(location, cb) {
        import('components/Apps')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/developerGuide',
      name: 'tutorial',
      getComponent(location, cb) {
        import('components/Tutorial')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/settings',
      name: 'settings',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/Settings/reducer'),
          import('containers/Settings'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('settings', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/upload',
      name: 'upload',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/Upload/reducer'),
          import('containers/Upload'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('upload', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: 'bulkGenerator',
      name: 'bulkGenerator',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/BulkGenerator/reducer'),
          import('containers/BulkGenerator'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('bulkGenerator', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/feedback',
      name: 'feedBackForm',
      getComponent(location, cb) {
        import('components/FeedBackForm')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/prototypeExplorer',
      name: 'prototypeExplorer',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/PrototypeExplorer/reducer'),
          import('containers/PrototypeExplorer'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('prototypeExplorer', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/plotlyFoo',
      name: 'plotlyFoo',
      getComponent(location, cb) {
        import('components/PlotlyFoo')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '*',
      name: 'notfound',
      getComponent(nextState, cb) {
        import('containers/NotFoundPage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    },
  ];
}
<commit_msg>Added route parameter for activityMaps<commit_after>// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from './utils/asyncInjectors';

const errorLoading = (err) => {
  console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};

const loadModule = (cb) => (componentModule) => {
  cb(null, componentModule.default);
};

export default function createRoutes(store) {
  // create reusable async injectors using getAsyncInjectors factory
  const { injectReducer } = getAsyncInjectors(store);

  return [
    {
      path: '/index.html',
      name: 'home',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/HomePage/reducer'),
          import('containers/HomePage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('home', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/',
      name: 'home',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/HomePage/reducer'),
          import('containers/HomePage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('home', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/features',
      name: 'features',
      getComponent(nextState, cb) {
        import('containers/FeaturePage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/activityMaps(/:reaction)',
      name: 'activityMaps',
      getComponent(location, cb) {
        import('containers/ActivityMapsPage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: 'pourbaixDiagrams',
      name: 'pourbaixDiagramsPage',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/PourbaixDiagramsPage/reducer'),
          import('containers/PourbaixDiagramsPage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('pourbaixDiagramsPage', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/energies',
      name: 'energiesPage',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/EnergiesPage/reducer'),
          import('containers/EnergiesPage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('energiesPage', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/scalingRelations',
      name: 'scalingRelationsPage',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/ScalingRelationsPage/reducer'),
          import('containers/ScalingRelationsPage'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('scalingRelationsPage', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/publications',
      name: 'publications',
      getComponent(location, cb) {
        import('components/Publications')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/yourNextApp',
      name: 'yourNextApp',
      getComponent(location, cb) {
        import('components/YourNextApp')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/generalSearch',
      name: 'generalSearch',
      getComponent(location, cb) {
        import('components/GeneralSearch')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/graphQLConsole',
      name: 'graphQlapi',
      getComponent(location, cb) {
        import('components/GraphQlapi')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/plotlyDemo',
      name: 'plotlyDemo',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/PlotlyDemo/reducer'),
          import('containers/PlotlyDemo'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('plotlyDemo', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/catKitDemo(/:data)',
      name: 'catKitDemo',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/CatKitDemo/reducer'),
          import('containers/CatKitDemo'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('catKitDemo', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/catKitDemo(/:lattice/:latticeConstant/:composition)',
      name: 'catKitDemo',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/CatKitDemo/reducer'),
          import('containers/CatKitDemo'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('catKitDemo', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/profile(/:name)',
      name: 'profile',
      getComponent(location, cb) {
        import('containers/Profile')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: 'appsIndex',
      name: 'apps',
      getComponent(location, cb) {
        import('components/Apps')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/developerGuide',
      name: 'tutorial',
      getComponent(location, cb) {
        import('components/Tutorial')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/settings',
      name: 'settings',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/Settings/reducer'),
          import('containers/Settings'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('settings', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/upload',
      name: 'upload',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/Upload/reducer'),
          import('containers/Upload'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('upload', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: 'bulkGenerator',
      name: 'bulkGenerator',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/BulkGenerator/reducer'),
          import('containers/BulkGenerator'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('bulkGenerator', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/feedback',
      name: 'feedBackForm',
      getComponent(location, cb) {
        import('components/FeedBackForm')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '/prototypeExplorer',
      name: 'prototypeExplorer',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          import('containers/PrototypeExplorer/reducer'),
          import('containers/PrototypeExplorer'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([reducer, component]) => {
          injectReducer('prototypeExplorer', reducer.default);
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    }, {
      path: '/plotlyFoo',
      name: 'plotlyFoo',
      getComponent(location, cb) {
        import('components/PlotlyFoo')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    }, {
      path: '*',
      name: 'notfound',
      getComponent(nextState, cb) {
        import('containers/NotFoundPage')
          .then(loadModule(cb))
          .catch(errorLoading);
      },
    },
  ];
}
<|endoftext|>


<commit_before>var Groups = require('../app/models/Groups'),
	Crypter = require('../app/utils/crypting'),
	Users = require('../app/models/Users');

module.exports = function (server)
{
	//GET routes
	//general
	server.route({
		method: 'GET',
		path: '/',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				//User logged in
				var groups = {};
				Groups.find({ 'isVisible': true }, function (err, groups)
				{
					if (err)
					{
						reply("Server Error");
						return;
					}
					reply.view('home', groups);
				});
			}
		}
	});
	server.route({
		method: 'GET',
		path: '/home',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				//User logged in
				var groups = {};
				Groups.find({ 'isVisible': true }, function (err, groups)
				{
					if (err)
					{
						reply("Server Error");
						return;
					}
					reply.view('home', { 'groups': groups });
				});
			}
		}
	});
	server.route({
		method: 'GET',
		path: '/groups',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				//User logged in
				var groups = {};
				Groups.find({ 'isVisible': true }, function (err, groups)
				{
					reply(groups);
				});
			}
		}
	});
	server.route(
	{
		method: 'POST',
		path: '/groups/created',
		handler: function (request, reply)
		{
			if (request.payload.alias != undefined)
			{
				console.log(request.payload);
				Groups.find({ 'createdBy': Crypter.decrypt(request.payload.alias) }, function (err, result)
				{
					if (err)
					{
						console.log(err);
						reply("Query failed");
						return;
					}
					reply(result);
				});
			}
		}
	});
	server.route(
	{
		method: 'GET',
		path: '/groups/{id}',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				Groups.find({ _id: request.params.id }, function (err, result)
				{
					console.log(result[0]);
					if (result[0].isPrivate)
					{
						var cookieB = JSON.parse(Crypter.decrypt(request.state['_b']));
						if (cookieB[result[0]._id])
						{
							reply.view('chat', { name: result[0].name, groupId: result[0]._id });
						} else
						{
							reply.redirect('/home');
						}
					} else
					{
						reply.view('chat', { name: result[0].name, groupId: result[0]._id });
					}
				});
			}
		}
	});
	server.route({
		method: 'GET',
		path: '/home.js',
		handler: function (request, reply)
		{
			reply.file('./public/scripts/home.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/chat.js',
		handler: function (request, reply)
		{
			reply.file('./public/scripts/chat.js');
		}
	});
	//resources
	server.route({
		method: 'GET',
		path: '/semantic.css',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/css/semantic.css');
		}
	});
	server.route({
		method: 'GET',
		path: '/semantic.min.css',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/css/semantic.min.css');
		}
	});
	server.route({
		method: 'GET',
		path: '/fonts/icons.woff',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/fonts/icons.woff');
		}
	});
	server.route({
		method: 'GET',
		path: '/fonts/icons.ttf',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/fonts/icons.ttf');
		}
	});
	server.route({
		method: 'GET',
		path: '/semantic.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/javascript/semantic.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/semantic.min.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/javascript/semantic.min.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/chatsy.css',
		handler: function (request, reply)
		{
			reply.file('./public/stylesheets/chatsy.css');
		}
	});
	server.route({
		method: 'GET',
		path: '/jquery.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/jquery/dist/jquery.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/jquery.min.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/jquery/dist/jquery.min.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/jquery.min.map',
		handler: function (request, reply)
		{
			reply.file('./bower_components/jquery/dist/jquery.min.map');
		}
	});

	//-----------------------------------------------------------------------
	//POST routes
	//general
	server.route({
		method: 'POST',
		path: '/',
		handler: function (request, reply)
		{
			if (request.payload.alias != undefined)
			{
				console.log(request.payload.alias);
				Users.find({ alias: request.payload.alias }, function (err, result)
				{
					console.log(result.length);
					if (result.length > 0)
					{
						reply("Failed - Alias already exists");
					} else
					{
						var newUser = new Users();
						newUser.alias = request.payload.alias;
						newUser.isPersistent = false;
						newUser.save(function (err)
						{
							if (err)
							{
								console.log(err);
								reply("Failed - Server error");
							} else
							{

								reply("Success").state('alias', Crypter.encrypt(request.payload.alias));
							}
						});
					}
				});

			} else
			{
				reply("Error");
			}
		}
	});
	server.route({
		method: 'POST',
		path: '/groups/create',
		handler: function (request, reply)
		{
			if (request.payload.alias != undefined)
			{
				var newGroup = new Groups();
				newGroup.name = request.payload.name;
				newGroup.description = request.payload.description;
				newGroup.passkey = newGroup.generateHash(request.payload.key);
				newGroup.createdBy = Crypter.decrypt(request.payload.alias);
				newGroup.isPrivate = request.payload.isPrivate;
				newGroup.isVisible = request.payload.isVisible;
				newGroup.save(function (err)
				{
					if (err)
					{
						reply(err.message);
					} else
					{
						reply("Success");
					}
				});
			} else
			{
				reply("Error");
			}
		}
	});
	server.route(
	{
		method: 'POST',
		path: '/joinauth',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				Groups.find({ _id: request.payload.groupId }, function (err, result)
				{
					if (err)
					{
						console.log(err);
						reply("Error");
					}
					if (result[0].validateKey(request.payload.passkey))
					{
						var cookieB = {};
						cookieB[result[0]._id] = true;
						console.log(cookieB);
						console.log(Crypter.encrypt(JSON.stringify(cookieB)));
						reply("Success").state('_b', Crypter.encrypt(JSON.stringify(cookieB)));
					} else
					{
						console.log("Validation Failed");
						reply("Failure");
					}
				});
			}
		}
	})

};
<commit_msg>-Adding redirects in routes to avoid code duplication<commit_after>var Groups = require('../app/models/Groups'),
	Crypter = require('../app/utils/crypting'),
	Users = require('../app/models/Users');

module.exports = function (server)
{
	//GET routes
	//general
	server.route({
		method: 'GET',
		path: '/',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				//User logged in
				reply.redirect('/home');
			}
		}
	});
	server.route({
		method: 'GET',
		path: '/home',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				//User logged in
				var groups = {};
				Groups.find({ 'isVisible': true }, function (err, groups)
				{
					if (err)
					{
						reply("Server Error");
						return;
					}
					reply.view('home', { 'groups': groups });
				});
			}
		}
	});
	server.route({
		method: 'GET',
		path: '/groups',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				//User logged in
				var groups = {};
				Groups.find({ 'isVisible': true }, function (err, groups)
				{
					reply(groups);
				});
			}
		}
	});
	server.route(
	{
		method: 'POST',
		path: '/groups/created',
		handler: function (request, reply)
		{
			if (request.payload.alias != undefined)
			{
				console.log(request.payload);
				Groups.find({ 'createdBy': Crypter.decrypt(request.payload.alias) }, function (err, result)
				{
					if (err)
					{
						console.log(err);
						reply("Query failed");
						return;
					}
					reply(result);
				});
			}
		}
	});
	server.route(
	{
		method: 'GET',
		path: '/groups/{id}',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				Groups.find({ _id: request.params.id }, function (err, result)
				{
					console.log(result[0]);
					if (result[0].isPrivate)
					{
						var cookieB = JSON.parse(Crypter.decrypt(request.state['_b']));
						if (cookieB[result[0]._id])
						{
							reply.view('chat', { name: result[0].name, groupId: result[0]._id });
						} else
						{
							reply.redirect('/home');
						}
					} else
					{
						reply.view('chat', { name: result[0].name, groupId: result[0]._id });
					}
				});
			}
		}
	});
	server.route({
		method: 'GET',
		path: '/home.js',
		handler: function (request, reply)
		{
			reply.file('./public/scripts/home.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/chat.js',
		handler: function (request, reply)
		{
			reply.file('./public/scripts/chat.js');
		}
	});
	//resources
	server.route({
		method: 'GET',
		path: '/semantic.css',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/css/semantic.css');
		}
	});
	server.route({
		method: 'GET',
		path: '/semantic.min.css',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/css/semantic.min.css');
		}
	});
	server.route({
		method: 'GET',
		path: '/fonts/icons.woff',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/fonts/icons.woff');
		}
	});
	server.route({
		method: 'GET',
		path: '/fonts/icons.ttf',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/fonts/icons.ttf');
		}
	});
	server.route({
		method: 'GET',
		path: '/semantic.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/javascript/semantic.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/semantic.min.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/semantic/build/packaged/javascript/semantic.min.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/chatsy.css',
		handler: function (request, reply)
		{
			reply.file('./public/stylesheets/chatsy.css');
		}
	});
	server.route({
		method: 'GET',
		path: '/jquery.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/jquery/dist/jquery.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/jquery.min.js',
		handler: function (request, reply)
		{
			reply.file('./bower_components/jquery/dist/jquery.min.js');
		}
	});
	server.route({
		method: 'GET',
		path: '/jquery.min.map',
		handler: function (request, reply)
		{
			reply.file('./bower_components/jquery/dist/jquery.min.map');
		}
	});

	//-----------------------------------------------------------------------
	//POST routes
	//general
	server.route({
		method: 'POST',
		path: '/',
		handler: function (request, reply)
		{
			if (request.payload.alias != undefined)
			{
				console.log(request.payload.alias);
				Users.find({ alias: request.payload.alias }, function (err, result)
				{
					console.log(result.length);
					if (result.length > 0)
					{
						reply("Failed - Alias already exists");
					} else
					{
						var newUser = new Users();
						newUser.alias = request.payload.alias;
						newUser.isPersistent = false;
						newUser.save(function (err)
						{
							if (err)
							{
								console.log(err);
								reply("Failed - Server error");
							} else
							{
								reply("Success").state('alias', Crypter.encrypt(request.payload.alias));
							}
						});
					}
				});
			} else
			{
				reply("Error");
			}
		}
	});
	server.route({
		method: 'POST',
		path: '/groups/create',
		handler: function (request, reply)
		{
			if (request.payload.alias != undefined)
			{
				var newGroup = new Groups();
				newGroup.name = request.payload.name;
				newGroup.description = request.payload.description;
				newGroup.passkey = newGroup.generateHash(request.payload.key);
				newGroup.createdBy = Crypter.decrypt(request.payload.alias);
				newGroup.isPrivate = request.payload.isPrivate;
				newGroup.isVisible = request.payload.isVisible;
				newGroup.save(function (err)
				{
					if (err)
					{
						reply(err.message);
					} else
					{
						reply("Success");
					}
				});
			} else
			{
				reply("Error");
			}
		}
	});
	server.route(
	{
		method: 'POST',
		path: '/joinauth',
		handler: function (request, reply)
		{
			if (request.state['alias'] == undefined)
			{
				//User not logged in
				reply.file('./views/index.html');
			} else
			{
				Groups.find({ _id: request.payload.groupId }, function (err, result)
				{
					if (err)
					{
						console.log(err);
						reply("Error");
					}
					if (result[0].validateKey(request.payload.passkey))
					{
						var cookieB = {};
						cookieB[result[0]._id] = true;
						console.log(cookieB);
						console.log(Crypter.encrypt(JSON.stringify(cookieB)));
						reply("Success").state('_b', Crypter.encrypt(JSON.stringify(cookieB)));
					} else
					{
						console.log("Validation Failed");
						reply("Failure");
					}
				});
			}
		}
	})

};
<|endoftext|>


<commit_before>var Employee = require('./models/employee');
var Appointment = require('./models/appointment');

module.exports = function(app) {

	// api
 	app.get('/api/employees', function(req, res) {
	    Employee.find(function(err, data) {
	    	if (err)
	      	res.send(err);

	      res.json(data);
	    });
  	});

 	app.get('/api/appointments', function(req, res) {
    Appointment.find(function(err, data) {

    	if (err)
      		res.send(err);

      	res.json(data);
    	});
  	});

	app.post('/api/employees', function(req, res) {
		Employee.create({
			name : req.body.name,
			address : req.body.address,
			type : req.body.type
		}, function(err, employee) {
			if (err)
				res.send(err);
		});

	});

	app.get('/api/salesperson-routes', function(req, res) {
		// add a check right here if the optimized routes are already in the database?
		// then don't run the algorithm

		// run algorithm

		// there will be a separate task for calculating the distance matrix..
		// just hard code it for now
		// this is old stuff
		//var homeAddresses=[[41.87355847,-87.79641662],[41.98512347,-87.65592603],[ 41.75050329,-87.69003923],[41.74313511, -87.64126162][41.98124939,-87.61216696],[41.77933782,-87.77089982]];
		//var appointments=[[[ 41.95304104, -87.66079453 ],[41.90056597,-87.4538938],[41.85340177, -87.51506404],[41.81984669,-87.52693874],[ 41.95472842,-87.7796233],[41.97387503,-87.58250468]],
		//[[ 41.80242171,-87.47432295],[41.87915987,-87.61111856],[41.8855845,-87.55396771],[41.94003661,-87.45577421],[41.78695588,-87.67820154],[41.86954838,-87.65298139]],
		//[[41.77982066,-87.66223627],[41.89893941, -87.61800847],[41.82592984,-87.76200356],[41.98791955,-87.5361794],[41.81677539,-87.64333341],[41.9154257,-87.69469442]]];
		//var officeAddress=[41.86928379,-87.5629177];

		// assume n salespeople and m customers
		// the first n rows of the sales
		// I am using a full distance matrix because im pretty sure thats how a real non-greedy algorithm would work.
		// and I don't care if it is more inefficient

		var n = 3;
		var m = n * 3;
		var nTotal = n + m + 1; // +1 for the office location

		// initialize stuff needed for algorithm
		// office is node 0
		// saleperson homes are nodes 1 -> n + 1
		// customer locations are nodes n + 1 -> n + 1 + m
		var salesmanLocation = new Array(n);
		var routes=new Array(n);
		for(var i = 0; i < n; i++)
		{
			routes[i]=new Array();
			routes[i].push(0);
			salesmanLocation[i] = 0; // the starting point is the office
		}

		// distance matrix
		var distanceMatrix = new Array(nTotal);
  	for (var i = 0; i < nTotal; i++)
  	{
    	distanceMatrix[i] = new Array(nTotal);
  	}

  	// fill distance matrix with garbage
  	for (var i = 0; i < nTotal; i++)
  	{
  		// we only need to fill up half the matrix
  		for (var j = 0; j <= i; j++)
  		{
  			if (i == j)
  			{
  				// nodes distance to itself is 0
  				distanceMatrix[i][j] = 0;
  			}
  			else
  			{
  				distanceMatrix[i][j] = Math.rand();
  			}
  		}
  	}

		var visited = new Array(m); // only need to mark customer nodes as visited
		for (var i = 0; i < m; i++) {
			visited[i] = 0; // nothing is visited
		}

		// for each time slot
		for(var appointment=0; appointment < 3; appointment++)//backwards
		{
			// for each salesman
			for(var salesperson = 0; salesperson < n; salesperson++)
			{
				// translate to location in distance matrix
				var translatedSalesperson = salesperson + 1;

				var origin = salesmanLocation[salesperson];//from last point
				var minDistance = Infinity;
				var bestDest = null;

				// for each customer destination
				for(var dest = 0; dest < m; dest++){
					// translate to location in distance matrix
					var translatedDest = dest + n + 1;

					distance=$scope.calculateDistance(origin,dest);
					if (distance < minDistance && !visited[dest])
					{
						minDistance=distance;
						bestDest=h;

					}
				}
				routes[j].push(appointments[j][bestDest]);
				visited[bestDest]=1;
				DistanceForSales[k]+=minDistance;

			}
			for(var s=0;s<salesNumber;s++)
			{
				DistanceForSales+=$scope.calculateDistance(salesmanLocation[s],officeAddress);
			}

		}
		console.log(routes)

		// return json blob of routes
	})

	/*
	// delete a todo
	app.delete('/api/todos/:todo_id', function(req, res) {
		Todo.remove({
			_id : req.params.todo_id
		}, function(err, todo) {
			if (err)
				res.send(err);

			getTodos(res);
		});
	});
*/

	// application -------------------------------------------------------------

	app.get('/', function(req, res) {
		res.render('index');
	});
	app.get('/results', function(req, res) {
		res.render('results');
	});
	app.get('/upload', function(req, res) {
		res.render('upload');
	});
	app.get('/manage', function(req, res) {
		res.render('addemployee');
	});
};<commit_msg>make a basic greedy algorithm, closes #29<commit_after>var Employee = require('./models/employee');
var Appointment = require('./models/appointment');

module.exports = function(app) {

	// api
 	app.get('/api/employees', function(req, res) {
	    Employee.find(function(err, data) {
	    	if (err)
	      	res.send(err);

	      res.json(data);
	    });
  	});

 	app.get('/api/appointments', function(req, res) {
    Appointment.find(function(err, data) {

    	if (err)
      		res.send(err);

      	res.json(data);
    	});
  	});

	app.post('/api/employees', function(req, res) {
		Employee.create({
			name : req.body.name,
			address : req.body.address,
			type : req.body.type
		}, function(err, employee) {
			if (err)
				res.send(err);
		});

	});

	app.get('/api/salesperson-routes', function(req, res) {
		// add a check right here if the optimized routes are already in the database?
		// then don't run the algorithm

		// run algorithm

		// there will be a separate task for calculating the distance matrix..
		// just hard code it for now
		// this is old stuff
		//var homeAddresses=[[41.87355847,-87.79641662],[41.98512347,-87.65592603],[ 41.75050329,-87.69003923],[41.74313511, -87.64126162][41.98124939,-87.61216696],[41.77933782,-87.77089982]];
		//var appointments=[[[ 41.95304104, -87.66079453 ],[41.90056597,-87.4538938],[41.85340177, -87.51506404],[41.81984669,-87.52693874],[ 41.95472842,-87.7796233],[41.97387503,-87.58250468]],
		//[[ 41.80242171,-87.47432295],[41.87915987,-87.61111856],[41.8855845,-87.55396771],[41.94003661,-87.45577421],[41.78695588,-87.67820154],[41.86954838,-87.65298139]],
		//[[41.77982066,-87.66223627],[41.89893941, -87.61800847],[41.82592984,-87.76200356],[41.98791955,-87.5361794],[41.81677539,-87.64333341],[41.9154257,-87.69469442]]];
		//var officeAddress=[41.86928379,-87.5629177];

		// assume n salespeople and m customers
		// the first n rows of the sales
		// I am using a full distance matrix because im pretty sure thats how a real non-greedy algorithm would work.
		// and I don't care if it is more inefficient

		var nSalespeople = 3;
		var nAppointments = nSalespeople * 3;
		var nTotal = nSalespeople + nAppointments + 1; // +1 for the office location

		// initialize stuff needed for algorithm
		// office is node 0
		// saleperson homes are nodes 1 -> n + 1
		// customer locations are nodes n + 1 -> n + 1 + m
		var salespersonLocation = new Array(nSalespeople);
		var routes=new Array(nSalespeople);
		for(var i = 0; i < nSalespeople; i++)
		{
			routes[i]=new Array();
			routes[i].push(0);
			salespersonLocation[i] = 0; // the starting point is the office
		}

		// distance matrix
		var distanceMatrix = new Array(nTotal);
  	for (var i = 0; i < nTotal; i++)
  	{
    	distanceMatrix[i] = new Array(nTotal);
  	}

  	// fill distance matrix with garbage
  	for (var i = 0; i < nTotal; i++)
  	{
  		// half of the matrix is same as the other half
  		for (var j = 0; j <= i; j++)
  		{
  			if (i == j)
  			{
  				// nodes distance to itself is 0
  				distanceMatrix[i][j] = 0;
  			}
  			else
  			{
  				var dist = Math.random();
  				distanceMatrix[i][j] = dist;
  				distanceMatrix[j][i] = dist;
  			}
  		}
  	}

		var visited = new Array(nAppointments); // only need to mark customer nodes as visited
		for (var i = 0; i < nAppointments; i++)
		{
			visited[i] = false; // nothing is visited
		}

		// for each time slot
		for(var appointment=0; appointment < 3; appointment++)
		{
			// for each salesman
			for(var salesperson = 0; salesperson < nSalespeople; salesperson++)
			{
				// translate to location in distance matrix
				var translatedSalespersonIdx = salesperson + 1;

				// origin does not need translated
				var origin = salespersonLocation[salesperson];//from last point
				var minDistance = Infinity;
				var bestDest = null;
				var bestTranslatedDest = null;

				// for each customer destination
				for(var dest = 0; dest < nAppointments; dest++)
				{
					// translate to location in distance matrix
					var translatedDestIdx = dest + nSalespeople + 1;
					// get distance from distance matrix
					distance = distanceMatrix[translatedSalespersonIdx][translatedDestIdx];
					if (distance < minDistance && !visited[dest])
					{
						minDistance = distance;
						bestTranslatedDest = translatedDestIdx;
						bestDest = dest;
					}
				}

				if (bestTranslatedDest) {
					routes[salesperson].push(bestTranslatedDest);
					visited[bestDest] = true;
					salespersonLocation[salesperson] = bestTranslatedDest;
				}
				else
				{
					console.log("something went wrong: ", bestDest);
				}
			}
		}

		// append salesperson home to the route
		for (var i = 0; i < nSalespeople; i++)
		{
			routes[i].push(i+1);
		}

		console.log(routes)

		// return json blob of routes

	})

	/*
	// delete a todo
	app.delete('/api/todos/:todo_id', function(req, res) {
		Todo.remove({
			_id : req.params.todo_id
		}, function(err, todo) {
			if (err)
				res.send(err);

			getTodos(res);
		});
	});
*/

	// application -------------------------------------------------------------

	app.get('/', function(req, res) {
		res.render('index');
	});
	app.get('/results', function(req, res) {
		res.render('results');
	});
	app.get('/upload', function(req, res) {
		res.render('upload');
	});
	app.get('/manage', function(req, res) {
		res.render('addemployee');
	});
};<|endoftext|>


<commit_before>import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/AppContainer';

import Auth from './containers/AuthContainer';
import About from './components/pages/About';
import Interests from './components/pages/Interests';
import Home from './components/pages/Home';
import Profile from './components/pages/Profile';
import PasswordRecovery from './components/pages/PasswordRecovery';
import Developers from './components/pages/Developer';
import Nonprofits from './components/pages/Nonprofit';
import NotFoundPage from './components/pages/NotFound';
// import ProjectFeed from './containers/ProjectFeedContainer';

export const routes = (
    <Route onUpdate={() => window.scrollTo(0, 0)} path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="/home" component={Home}/>
        <Route path="/about" component={About}/>
        <Route path="/developers" component={Developers} />
        <Route path="/nonprofits" component={Nonprofits} />
        <Route path="/profile" component={Profile} />
        <Route path="/recover" component={PasswordRecovery} />
        <Route component={Auth}>
            <Route path="/interests" component={Interests} />
            <Route path="/feed" component={Developers} />
        </Route>
        <Route path="*" component={NotFoundPage} notFound />
    </Route>
);

export default routes;
<commit_msg>Tested forgot password and changed URL link<commit_after>import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/AppContainer';

import Auth from './containers/AuthContainer';
import About from './components/pages/About';
import Interests from './components/pages/Interests';
import Home from './components/pages/Home';
import Profile from './components/pages/Profile';
import PasswordRecovery from './components/pages/PasswordRecovery';
import Developers from './components/pages/Developer';
import Nonprofits from './components/pages/Nonprofit';
import NotFoundPage from './components/pages/NotFound';
// import ProjectFeed from './containers/ProjectFeedContainer';

export const routes = (
    <Route onUpdate={() => window.scrollTo(0, 0)} path="/" component={App}>
        <IndexRoute component={Home}/>
        <Route path="/home" component={Home}/>
        <Route path="/about" component={About}/>
        <Route path="/developers" component={Developers} />
        <Route path="/nonprofits" component={Nonprofits} />
        <Route path="/profile" component={Profile} />
        <Route path="/forgot" component={PasswordRecovery} />
        <Route component={Auth}>
            <Route path="/interests" component={Interests} />
            <Route path="/feed" component={Developers} />
        </Route>
        <Route path="*" component={NotFoundPage} notFound />
    </Route>
);

export default routes;
<|endoftext|>


<commit_before>var config = require("config");
var Express = require("express");
var helmet = require("helmet");
var vhost = require("vhost");
var blog = require("./blog");
var brochure = require("./brochure");
var dashboard = require("./dashboard");
var cdn = require("./cdn");
var clfdate = require("helper/clfdate");

// Welcome to Blot. This is the Express application which listens on port 8080.
// NGINX listens on port 80 in front of Express app and proxies requests to
// port 8080. NGINX handles SSL termination, cached response delivery and
// compression. See ../config/nginx for more. Blot does the rest.
var Blot = Express();

// Removes a header otherwise added by Express. No wasted bytes
Blot.disable("x-powered-by");

// Trusts secure requests terminated by NGINX, as far as I know
Blot.set("trust proxy", "loopback");

// Prevent <iframes> embedding pages served by Blot
Blot.use(helmet.frameguard("allow-from", config.host));

Blot.use(function (req, res, next) {
  var init = Date.now();

	try {
		console.log(
			clfdate(),
			req.headers["x-request-id"] && req.headers["x-request-id"],
			"PID=" + process.pid,
			req.protocol + "://" + req.hostname + req.originalUrl,
			req.method
		);
	} catch (e) {
		console.error("Error: Failed to construct canonical log line:", e);
	}

	res.on("finish", function () {
		try {
			console.log(
				clfdate(),
				req.headers["x-request-id"] && req.headers["x-request-id"],
				res.statusCode,
				((Date.now() - init) / 1000).toFixed(3),
				"PID=" + process.pid,
				req.protocol + "://" + req.hostname + req.originalUrl
			);
		} catch (e) {
			console.error("Error: Failed to construct canonical log line:", e);
		}
	});

  next();
});

// Blot is composed of four sub applications.

// The CDN
// -------
// Serves static files generated by Blot e.g.
// thumbnails and cached images.
Blot.use(vhost(config.host, cdn));

// The Dashboard
// -------------
// Serve the dashboard and public site (the brochure)
// Webhooks from Dropbox and Stripe, git pushes are
// served by these two applications. The dashboard can
// only ever be served for request to the host
Blot.use(vhost(config.host, dashboard));

// The Brochure
// ------------
// The least important application. It serves the documentation
// and sign up page.
Blot.use(vhost(config.host, brochure));

// The Blogs
// ---------
// Serves the customers's blogs. It should come first because it's the
// most important. We don't know the hosts for all the blogs in
// advance so all requests hit this middleware.
Blot.use(blog);

// Monit, which we use to monitor the server's health, requests
// localhost/health to see if it should attempt to restart Blot.
// If you remove this, change monit.rc too.
Blot.use("/health", function (req, res) {
  res.send("OK");
});

module.exports = Blot;
<commit_msg>Auto-formatted code<commit_after>var config = require("config");
var Express = require("express");
var helmet = require("helmet");
var vhost = require("vhost");
var blog = require("./blog");
var brochure = require("./brochure");
var dashboard = require("./dashboard");
var cdn = require("./cdn");
var clfdate = require("helper/clfdate");

// Welcome to Blot. This is the Express application which listens on port 8080.
// NGINX listens on port 80 in front of Express app and proxies requests to
// port 8080. NGINX handles SSL termination, cached response delivery and
// compression. See ../config/nginx for more. Blot does the rest.
var Blot = Express();

// Removes a header otherwise added by Express. No wasted bytes
Blot.disable("x-powered-by");

// Trusts secure requests terminated by NGINX, as far as I know
Blot.set("trust proxy", "loopback");

// Prevent <iframes> embedding pages served by Blot
Blot.use(helmet.frameguard("allow-from", config.host));

Blot.use(function (req, res, next) {
  var init = Date.now();

  try {
    console.log(
      clfdate(),
      req.headers["x-request-id"] && req.headers["x-request-id"],
      "PID=" + process.pid,
      req.protocol + "://" + req.hostname + req.originalUrl,
      req.method
    );
  } catch (e) {
    console.error("Error: Failed to construct canonical log line:", e);
  }

  res.on("finish", function () {
    try {
      console.log(
        clfdate(),
        req.headers["x-request-id"] && req.headers["x-request-id"],
        res.statusCode,
        ((Date.now() - init) / 1000).toFixed(3),
        "PID=" + process.pid,
        req.protocol + "://" + req.hostname + req.originalUrl
      );
    } catch (e) {
      console.error("Error: Failed to construct canonical log line:", e);
    }
  });

  next();
});

// Blot is composed of four sub applications.

// The CDN
// -------
// Serves static files generated by Blot e.g.
// thumbnails and cached images.
Blot.use(vhost(config.host, cdn));

// The Dashboard
// -------------
// Serve the dashboard and public site (the brochure)
// Webhooks from Dropbox and Stripe, git pushes are
// served by these two applications. The dashboard can
// only ever be served for request to the host
Blot.use(vhost(config.host, dashboard));

// The Brochure
// ------------
// The least important application. It serves the documentation
// and sign up page.
Blot.use(vhost(config.host, brochure));

// The Blogs
// ---------
// Serves the customers's blogs. It should come first because it's the
// most important. We don't know the hosts for all the blogs in
// advance so all requests hit this middleware.
Blot.use(blog);

// Monit, which we use to monitor the server's health, requests
// localhost/health to see if it should attempt to restart Blot.
// If you remove this, change monit.rc too.
Blot.use("/health", function (req, res) {
  res.send("OK");
});

module.exports = Blot;
<|endoftext|>


<commit_before>import dotenv from 'dotenv';
import express from 'express';
import compression from 'compression';
import session from 'express-session';
import passport from 'passport';
import { Strategy } from 'passport-github';
import sessionFileStore from 'session-file-store';
import sapper from 'sapper';
import serve from 'serve-static';
import devalue from 'devalue';
import { Store } from 'svelte/store.js';
import { routes } from './manifest/server.js';

dotenv.config();

const FileStore = sessionFileStore(session);

passport.use(new Strategy({
	clientID: process.env.GITHUB_CLIENT_ID,
	clientSecret: process.env.GITHUB_CLIENT_SECRET,
	callbackURL: `${process.env.BASEURL}/auth/callback`,
	userAgent: 'svelte.technology'
}, (accessToken, refreshToken, profile, callback) => {
	return callback(null, {
		token: accessToken,
		id: profile.id,
		username: profile.username,
		displayName: profile.displayName,
		photo: profile.photos && profile.photos[0] && profile.photos[0].value
	});
}));

passport.serializeUser((user, cb) => {
	cb(null, user);
});

passport.deserializeUser((obj, cb) => {
	cb(null, obj);
});

express()
	.use(compression({ threshold: 0 }))

	.use(session({
		secret: 'svelte',
		resave: true,
		saveUninitialized: true,
		cookie: {
			maxAge: 31536000
		},
		store: new FileStore({
			path: process.env.NOW ? `/tmp/sessions` : `.sessions`
		})
	}))

	.use(passport.initialize())
	.use(passport.session())

	.get('/auth/login', (req, res, next) => {
		const { returnTo } = req.query;
		req.session.returnTo = returnTo ? decodeURIComponent(returnTo) : '/';
		next();
	}, passport.authenticate('github', { scope: ['gist', 'read:user'] }))

	.post('/auth/logout', (req, res) => {
		req.logout();
		res.end('ok');
	})

	.get('/auth/callback', passport.authenticate('github', { failureRedirect: '/auth/error' }), (req, res) => {
		const { id, username, displayName, photo } = req.session.passport && req.session.passport.user;

		res.set({ 'Content-Type': 'text/html; charset=utf-8' });
		res.end(`

		`);
	})

	.use(
		compression({ threshold: 0 }),
		serve('assets'),
		sapper({
			routes,
			store: req => {
				const user = req.session.passport && req.session.passport.user;

				return new Store({
					user: user && {
						// strip access token
						id: user.id,
						username: user.username,
						displayName: user.displayName,
						photo: user.photo
					},
					guide_contents: []
				});
			}
		})
	)

	.listen(process.env.PORT);<commit_msg>make auth stuff optional<commit_after>import dotenv from 'dotenv';
import express from 'express';
import compression from 'compression';
import session from 'express-session';
import passport from 'passport';
import { Strategy } from 'passport-github';
import sessionFileStore from 'session-file-store';
import sapper from 'sapper';
import serve from 'serve-static';
import devalue from 'devalue';
import { Store } from 'svelte/store.js';
import { routes } from './manifest/server.js';

dotenv.config();

const app = express();

if (process.env.GITHUB_CLIENT_ID) {
	const FileStore = sessionFileStore(session);

	passport.use(new Strategy({
		clientID: process.env.GITHUB_CLIENT_ID,
		clientSecret: process.env.GITHUB_CLIENT_SECRET,
		callbackURL: `${process.env.BASEURL}/auth/callback`,
		userAgent: 'svelte.technology'
	}, (accessToken, refreshToken, profile, callback) => {
		return callback(null, {
			token: accessToken,
			id: profile.id,
			username: profile.username,
			displayName: profile.displayName,
			photo: profile.photos && profile.photos[0] && profile.photos[0].value
		});
	}));

	passport.serializeUser((user, cb) => {
		cb(null, user);
	});

	passport.deserializeUser((obj, cb) => {
		cb(null, obj);
	});

	app
		.use(session({
			secret: 'svelte',
			resave: true,
			saveUninitialized: true,
			cookie: {
				maxAge: 31536000
			},
			store: new FileStore({
				path: process.env.NOW ? `/tmp/sessions` : `.sessions`
			})
		}))

		.use(passport.initialize())
		.use(passport.session())

		.get('/auth/login', (req, res, next) => {
			const { returnTo } = req.query;
			req.session.returnTo = returnTo ? decodeURIComponent(returnTo) : '/';
			next();
		}, passport.authenticate('github', { scope: ['gist', 'read:user'] }))

		.post('/auth/logout', (req, res) => {
			req.logout();
			res.end('ok');
		})

		.get('/auth/callback', passport.authenticate('github', { failureRedirect: '/auth/error' }), (req, res) => {
			const { id, username, displayName, photo } = req.session.passport && req.session.passport.user;

			res.set({ 'Content-Type': 'text/html; charset=utf-8' });
			res.end(`

			`);
		});
} else {
	app.get('/auth/login', (req, res) => {
		res.writeHead(500);
		res.end(`

Missing .env file

In order to use GitHub authentication, you will need to register an OAuth application with gist and read:user scopes, and create a .env file:

GITHUB_CLIENT_ID=[YOUR_APP_ID]\nGITHUB_CLIENT_SECRET=[YOUR_APP_SECRET]\nBASEURL=http://localhost:3000

The BASEURL variable should match the callback URL specified for your app.

		`);
	});
}

app.use(
	compression({ threshold: 0 }),
	serve('assets'),
	sapper({
		routes,
		store: req => {
			const user = req.session && req.session.passport && req.session.passport.user;

			return new Store({
				user: user && {
					// strip access token
					id: user.id,
					username: user.username,
					displayName: user.displayName,
					photo: user.photo
				},
				guide_contents: []
			});
		}
	})
).listen(process.env.PORT);<|endoftext|>