<commit_before>/* eslint no-console: ["error", { allow: ["log", "error"] }] */
import path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import express from 'express';
import webpackConfig from '../../webpack.config.dev';
import ajaxProxyRouter from './lib/ajaxProxyRouter';
import morgan from 'morgan';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from './auth/credentials';
import { upsert } from './lib/util';

delete process.env.BROWSER;

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 3000 : process.env.PORT;
const server = express();

// TODO: write tests for server.js

/**
 ******************************************
 passport stuff - TODO: Move into separate file
 ******************************************
 */
passport.serializeUser((user, done) => {
  const sessionUser = {
    first_name: user.first_name,
    last_name: user.last_name,
    email: user.email,
    photo_url: user.photo_url,
  };
  done(null, sessionUser);
});

passport.deserializeUser((sessionUser, done) => done(null, sessionUser));

passport.use(new GoogleStrategy(
  authConfig.google,
  (accessToken, refreshToken, profile, done) => {
    const params = {
      email: profile.emails[0].value,
      external_auth_type: 'google',
    };
    const data = {
      first_name: profile.name.givenName,
      last_name: profile.name.familyName,
      email: profile.emails.length && profile.emails[0].value,
      photo_url: profile.photos.length && profile.photos[0].value,
      external_auth_type: 'google',
      external_auth_id: profile.id,
    };

    upsert('/users', params, data)
      .then(resp => done(null, resp))
      .catch(err => done(err));
  }
));

/**
 ******************************************
 * helper functions
 ******************************************
 */
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    next();
  }
  res.redirect('/');
}

/**
 ******************************************
 * middlewares
 ******************************************
 */

// TODO: Move log format into server config file
// Log requests to stdout
server.use(
  morgan(':remote-addr - - :date[clf] :method :url HTTP/:http-version :status -')
);

server.use(cookieParser());

// TODO: move session config into server config file
server.use(session({
  secret: 'some',
  resave: true,
  saveUninitialized: true,
  cookie: { maxAge: 2419200000 },
}));

server.use(passport.initialize());

server.use(passport.session());

/**
 ******************************************
 * user auth endpoints
 ******************************************
 */

server.get('/auth/google',
  passport.authenticate('google', { scope: ['openid email profile'] })
);

server.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    res.redirect('/');
  }
);

server.get('/account', ensureAuthenticated, (req, res) => {
  res.send(req.user);
});

server.get('/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      console.log(err);
    } else {
      res.redirect('/');
    }
  });
});

/**
 ******************************************
 * api/ping endpoints
 ******************************************
 */

server.use('/api', ajaxProxyRouter());
server.get('/ping', (req, res) => {
  res.header('Content-Type', 'text/plain');
  res.send(new Date().toISOString());
});

/**
 ******************************************
 * serving front-end application
 ******************************************
 */

if (isDeveloping) {
  console.log('DEVELOPMENT');
  const compiler = webpack(webpackConfig);
  const middleware = webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    // https://webpack.github.io/docs/webpack-dev-middleware.html
    noInfo: true,
    // for hot-reloading with docker
    watchOptions: {
      poll: true,
    },
    stats: {
      colors: true,
    },
  });

  server.use(middleware);
  server.use(webpackHotMiddleware(compiler));
  server.use(express.static(path.join(__dirname, '../app')));
} else {
  console.log('PRODUCTION');
  server.use(express.static(path.join(__dirname, '../app')));
}

server.listen(port, '0.0.0.0', (err) => {
  if (err) {
    console.error(err);
  }
  console.log('Listening at http://0.0.0.0:%s/', port);
});
<commit_msg>- sending page on refresh, serving static assets<commit_after>/* eslint no-console: ["error", { allow: ["log", "error"] }] */
import path from 'path';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import express from 'express';
import webpackConfig from '../../webpack.config.dev';
import ajaxProxyRouter from './lib/ajaxProxyRouter';
import morgan from 'morgan';
import cookieParser from 'cookie-parser';
import session from 'express-session';
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from './auth/credentials';
import { upsert } from './lib/util';

delete process.env.BROWSER;

const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 3000 : process.env.PORT;
const server = express();

// TODO: write tests for server.js

/**
 ******************************************
 passport stuff - TODO: Move into separate file
 ******************************************
 */
passport.serializeUser((user, done) => {
  const sessionUser = {
    first_name: user.first_name,
    last_name: user.last_name,
    email: user.email,
    photo_url: user.photo_url,
  };
  done(null, sessionUser);
});

passport.deserializeUser((sessionUser, done) => done(null, sessionUser));

passport.use(new GoogleStrategy(
  authConfig.google,
  (accessToken, refreshToken, profile, done) => {
    const params = {
      email: profile.emails[0].value,
      external_auth_type: 'google',
    };
    const data = {
      first_name: profile.name.givenName,
      last_name: profile.name.familyName,
      email: profile.emails.length && profile.emails[0].value,
      photo_url: profile.photos.length && profile.photos[0].value,
      external_auth_type: 'google',
      external_auth_id: profile.id,
    };

    upsert('/users', params, data)
      .then(resp => done(null, resp))
      .catch(err => done(err));
  }
));

/**
 ******************************************
 * helper functions
 ******************************************
 */
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    next();
  }
  res.redirect('/');
}

/**
 ******************************************
 * middlewares
 ******************************************
 */

// TODO: Move log format into server config file
// Log requests to stdout
server.use(
  morgan(':remote-addr - - :date[clf] :method :url HTTP/:http-version :status -')
);

server.use(cookieParser());

// TODO: move session config into server config file
server.use(session({
  secret: 'some',
  resave: true,
  saveUninitialized: true,
  cookie: { maxAge: 2419200000 },
}));

server.use(passport.initialize());

server.use(passport.session());

/**
 ******************************************
 * user auth endpoints
 ******************************************
 */

server.get('/auth/google',
  passport.authenticate('google', { scope: ['openid email profile'] })
);

server.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    res.redirect('/');
  }
);

server.get('/account', ensureAuthenticated, (req, res) => {
  res.send(req.user);
});

server.get('/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      console.log(err);
    } else {
      res.redirect('/');
    }
  });
});

/**
 ******************************************
 * api/ping endpoints
 ******************************************
 */

server.use('/api', ajaxProxyRouter());
server.get('/ping', (req, res) => {
  res.header('Content-Type', 'text/plain');
  res.send(new Date().toISOString());
});

/**
 ******************************************
 * serving front-end application
 ******************************************
 */

if (isDeveloping) {
  console.log('DEVELOPMENT');
  const compiler = webpack(webpackConfig);
  const middleware = webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    // https://webpack.github.io/docs/webpack-dev-middleware.html
    noInfo: true,
    // for hot-reloading with docker
    watchOptions: {
      poll: true,
    },
    stats: {
      colors: true,
    },
  });

  server.use(middleware);
  server.use(webpackHotMiddleware(compiler));

  // serving the static assets
  server.use(express.static(path.join(__dirname, '../app')));
  server.use('/*', (req, res) => {
    res.sendFile(path.join(__dirname, '../app/index.html'));
  });
} else {
  console.log('PRODUCTION');
  server.use(express.static(path.join(__dirname, '../app')));
}

server.listen(port, '0.0.0.0', (err) => {
  if (err) {
    console.error(err);
  }
  console.log('Listening at http://0.0.0.0:%s/', port);
});
<|endoftext|>


<commit_before>import 'babel-polyfill'

import path from 'path'
import { Server } from 'http'
import Express from 'express' // eslint-disable-line
import React from 'react'
import { renderToString } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import csshook from 'css-modules-require-hook/preset' // eslint-disable-line

import routes from '../shared/views/routes'
import NotFoundPage from '../shared/views/PageNotFound/PageNotFound'
import rootReducer from '../shared/views/rootReducer'

const app = new Express()
const server = new Server(app)
console.log(process.cwd(),'<---------------------------------------------')

if (process.env.SSLONLY === 'true') {
  app.use((req, res, next) => {
    if (req.header('x-forwarded-proto') !== 'https') {
      return res.redirect(`https://${req.get('Host')}${req.url}`)
    }
    return next()
  })
}

app.get('/static/sw.js', (req, res) => {
  res.set('Service-Worker-Allowed', '/demo')
  return res.sendFile(path.resolve(process.cwd(), 'dist/static/sw.js'))
})

// define the folder that will be used for static assets
app.use(Express.static(path.resolve(process.cwd(), 'dist')))

// universal routing and rendering
app.get('*', (req, res) => {
  const store = createStore(rootReducer)
  const initialState = store.getState()
  match(
    { routes, location: req.url },
    (err, redirectLocation, renderProps) => {
      // in case of error display the error message
      if (err) {
        return res.status(500).send(err.message)
      }

      // in case of redirect propagate the redirect to the browser
      if (redirectLocation) {
        return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
      }

      // generate the React markup for the current route
      let markup
      if (renderProps) {
        // get base url
        renderProps.location.baseUrl = req.headers.host //eslint-disable-line
        // console.log('render props', renderProps)
        // console.log('req url', req.headers.host)
        // if the current route matched we have renderProps
        markup = renderToString(
          <Provider store={store}>
            <RouterContext {...renderProps} />
          </Provider>)
      } else {
        // otherwise we can render a 404 page
        markup = renderToString(<NotFoundPage />)
        res.status(404)
      }

      // render the index template with the embedded React markup
      return res.send(renderFullPage(markup, initialState))
    }
  )
})

// TODO: We should use FS to read the index.html generated by webpack
// and insert the html in there.
function renderFullPage(html, preloadedState) {
  return `
  <!doctype html>

      <title>Indepth Demo</title>
      <base href="/" />
      <meta charset="utf-8">
      <meta http-equiv="cache-control" content="no-cache">
      <meta http-equiv="Expires" content="0">
      <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"/>
      <meta name="apple-mobile-web-app-capable" content="yes">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css"/>
      <link rel="stylesheet" href="/common.css"/>
      <link rel="manifest" href="/static/manifest.json">
      <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,400i,700|Roboto|Material+Icons">

${html}

    `
}

const port = process.env.PORT || 3000
const env = process.env.NODE_ENV || 'production'
server.listen(port, err => {
  if (err) {
    return console.error(err)
  }
  return console.info(`Server running on http://localhost:${port} [${env}]`)
})
<commit_msg>Fix SW<commit_after>import 'babel-polyfill'

import path from 'path'
import { Server } from 'http'
import Express from 'express' // eslint-disable-line
import React from 'react'
import { renderToString } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import csshook from 'css-modules-require-hook/preset' // eslint-disable-line

import routes from '../shared/views/routes'
import NotFoundPage from '../shared/views/PageNotFound/PageNotFound'
import rootReducer from '../shared/views/rootReducer'

const app = new Express()
const server = new Server(app)

if (process.env.SSLONLY === 'true') {
  app.use((req, res, next) => {
    if (req.header('x-forwarded-proto') !== 'https') {
      return res.redirect(`https://${req.get('Host')}${req.url}`)
    }
    return next()
  })
}

app.get('/static/sw.js', (req, res) => {
  res.set('Service-Worker-Allowed', '/demo')
  return res.sendFile(path.resolve(process.cwd(), 'dist/static/sw.js'))
})

// define the folder that will be used for static assets
app.use(Express.static(path.resolve(process.cwd(), 'dist')))

// universal routing and rendering
app.get('*', (req, res) => {
  const store = createStore(rootReducer)
  const initialState = store.getState()
  match(
    { routes, location: req.url },
    (err, redirectLocation, renderProps) => {
      // in case of error display the error message
      if (err) {
        return res.status(500).send(err.message)
      }

      // in case of redirect propagate the redirect to the browser
      if (redirectLocation) {
        return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
      }

      // generate the React markup for the current route
      let markup
      if (renderProps) {
        // get base url
        renderProps.location.baseUrl = req.headers.host //eslint-disable-line
        // console.log('render props', renderProps)
        // console.log('req url', req.headers.host)
        // if the current route matched we have renderProps
        markup = renderToString(
          <Provider store={store}>
            <RouterContext {...renderProps} />
          </Provider>)
      } else {
        // otherwise we can render a 404 page
        markup = renderToString(<NotFoundPage />)
        res.status(404)
      }

      // render the index template with the embedded React markup
      return res.send(renderFullPage(markup, initialState))
    }
  )
})

// TODO: We should use FS to read the index.html generated by webpack
// and insert the html in there.
function renderFullPage(html, preloadedState) {
  return `
  <!doctype html>

      <title>Indepth Demo</title>
      <base href="/" />
      <meta charset="utf-8">
      <meta http-equiv="cache-control" content="no-cache">
      <meta http-equiv="Expires" content="0">
      <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"/>
      <meta name="apple-mobile-web-app-capable" content="yes">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css"/>
      <link rel="stylesheet" href="/common.css"/>
      <link rel="manifest" href="/static/manifest.json">
      <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,400i,700|Roboto|Material+Icons">

${html}

    `
}

const port = process.env.PORT || 3000
const env = process.env.NODE_ENV || 'production'
server.listen(port, err => {
  if (err) {
    return console.error(err)
  }
  return console.info(`Server running on http://localhost:${port} [${env}]`)
})
<|endoftext|>


<commit_before>console.log( "=== simpread theme load ===" )

import 'github';
import 'newsprint';
import 'gothic';

const flag   = "sr-rd-theme-",
      themes = {};

/**
 * Theme class
 *
 * @class
 */

class Theme {

    /**
     * Change theme
     *
     * @param {string} theme name
     */
    Change( theme ) {
        findThemeStyle( function( name, css, $target ) {
            if ( name == theme ) {
                $target.html( themes[theme] );
            } else {
                $target.html( `sr-rd-theme-${name}` + "{}" );
            }
        });
    }

    constructor() {
        findThemeStyle( function( name, content ) {
            themes[name] = content;
        });
    }
}

/**
 * Find theme style tag
 *
 * @return {function} param1: theme name; param2: theme css; param3: theme style tag jquery object
 */
function findThemeStyle( callback ) {
    $( "head" ).find( "style" ).map( (index, item) => {
        const $target = $(item),
              css     = $target.text();
        if ( css.startsWith( flag ) ) {
            const arr  = css.replace( flag, "" ).match( /\w+/ ),
                  name = arr[ arr.length - 1 ];
            callback( name, css, $target );
        }
    });
}

const theme = new Theme();

export default theme;<commit_msg>Add new property.<commit_after>console.log( "=== simpread theme load ===" )

import 'github';
import 'newsprint';
import 'gothic';

const flag   = "sr-rd-theme-",
      themes = {},
      color  = [
        "251, 251, 251,  1",
        "243, 242, 238, 1",
        "252, 252, 252, 1"
       ],
       names = [ "github", "newsprint", "gothic" ];

/**
 * Theme class
 *
 * @class
 */

class Theme {

    get colors() {
        return  color;
    }

    get names() {
        return names;
    }

    /**
     * Change theme
     *
     * @param {string} theme name
     */
    Change( theme ) {
        findThemeStyle( function( name, css, $target ) {
            if ( name == theme ) {
                $target.html( themes[theme] );
            } else {
                $target.html( `sr-rd-theme-${name}` + "{}" );
            }
        });
    }

    constructor() {
        findThemeStyle( function( name, content ) {
            themes[name] = content;
        });
    }
}

/**
 * Find theme style tag
 *
 * @return {function} param1: theme name; param2: theme css; param3: theme style tag jquery object
 */
function findThemeStyle( callback ) {
    $( "head" ).find( "style" ).map( (index, item) => {
        const $target = $(item),
              css     = $target.text();
        if ( css.startsWith( flag ) ) {
            const arr  = css.replace( flag, "" ).match( /\w+/ ),
                  name = arr[ arr.length - 1 ];
            callback( name, css, $target );
        }
    });
}

const theme = new Theme();

export default theme;<|endoftext|>


<commit_before>import React from 'react';
import {Route, IndexRoute} from 'react-router';

import App from './components/App.js';
import EditInvoice from './components/invoice/EditInvoice.js';
import InvoiceList from './components/invoice/InvoiceList.js';
import ClientList from './components/client/ClientList.js';
import EditClient from './components/client/EditClient.js';
import EditConfig from './components/config/EditConfig.js';

const Routes = (
  <Route path="/" component={App}>
    <IndexRoute component={InvoiceList} />
    <Route path="/invoice/create" component={EditInvoice} />
    <Route path="/invoice/:id" component={EditInvoice} />

    <Route path="/clients" component={ClientList} />
    <Route path="/client/create" component={EditClient} />
    <Route path="/client/:id" component={EditClient} />

    <Route path="/config" component={EditConfig} />
  </Route>
);

export default Routes;
<commit_msg>routing: unknown path -> show invoicelist<commit_after>import React from 'react';
import {Route, IndexRoute} from 'react-router';

import App from './components/App.js';
import EditInvoice from './components/invoice/EditInvoice.js';
import InvoiceList from './components/invoice/InvoiceList.js';
import ClientList from './components/client/ClientList.js';
import EditClient from './components/client/EditClient.js';
import EditConfig from './components/config/EditConfig.js';

const Routes = (
  <Route path="/" component={App}>
    <IndexRoute component={InvoiceList} />
    <Route path="/invoice/create" component={EditInvoice} />
    <Route path="/invoice/:id" component={EditInvoice} />

    <Route path="/clients" component={ClientList} />
    <Route path="/client/create" component={EditClient} />
    <Route path="/client/:id" component={EditClient} />

    <Route path="/config" component={EditConfig} />

    <Route path="*" component={InvoiceList}/>
  </Route>
);

export default Routes;
<|endoftext|>


<commit_before>require('env2')(`${__dirname}/../.env`);
const sendMail = require('./send-email');

module.exports = [
  {
    method: 'GET',
    path: '/',
    handler: (request, reply) => {
      const data = {
        isWelcome: true,
        next: '/avatar'
      };
      reply.view('welcome', data);
    }
  },
  {
    method: 'GET',
    path: '/avatar',
    handler: (request, reply) => {
      const data = {
        isAvatar: true,
        prev: '/',
        next: '/introduction'
       };
      reply.view('choose-an-avatar', data);
    }
  },
  {
    method: 'GET',
    path: '/introduction',
    handler: (request, reply) => {
      const data =  {
        prev: '/avatar',
        next: '/eating'
      };
      reply.view('introduction', data);
    }
  },
  {
    method: 'GET',
    path: '/eating',
    handler: (request, reply) => {
      const data =  {
        prev: '/introduction',
        next: '/feelings'
      };
      reply.view('eating', data);
    }
  },
  {
    method: 'GET',
    path: '/feelings',
    handler: (request, reply) => {
      const data =  {
        prev: '/eating',
        next: '/personality'
      };
      reply.view('feelings', data);
    }
  },
  {
    method: 'GET',
    path: '/personality',
    handler: (request, reply) => {
      const data =  {
        prev: '/feelings',
        next: '/hobbies'
      };
      reply.view('personality', data);
    }
  },
  {
    method: 'GET',
    path: '/hobbies',
    handler: (request, reply) => {
      const data =  {
        prev: '/personality',
        next: '/sleep'
      };
      reply.view('hobbies', data);
    }
  },
  {
    method: 'GET',
    path: '/sleep',
    handler: (request, reply) => {
      const data =  {
        prev: '/hobbies',
        next: '/friends'
      };
      reply.view('sleep', data);
    }
  },
  {
    method: 'GET',
    path: '/friends',
    handler: (request, reply) => {
      const data =  {
        prev: '/sleep',
        next: '/school'
      };
      reply.view('friends', data);
    }
  },
  {
    method: 'GET',
    path: '/school',
    handler: (request, reply) => {
      const data =  {
        prev: '/friends',
        next: '/home'
      };
      reply.view('school', data);
    }
  },
  {
    method: 'GET',
    path: '/home',
    handler: (request, reply) => {
      const data =  {
        prev: '/school',
        next: '/finished'
      };
      reply.view('home', data);
    }
  },
  {
    method: 'GET',
    path: '/finished',
    handler: (request, reply) => {
      const data =  {
        isEnd: true,
        prev: '/home'
      };
      reply.view('finished', data);
    }
  },
  {
    method: 'GET',
    path: '/info',
    handler: (request, reply) => {
      var data =  {
        isEnd: true,
        prev: '/finished'
      };
      reply.view('info', data);
    }
  },
  {
    method: 'POST',
    path: '/finished',
    handler: (request, reply) => {
      if (process.env.NODE_ENV === 'testing'){
        reply();
        return;
      }
      const { emailAddress, sessionStorage } = request.payload;
      sendMail(emailAddress, sessionStorage, function(err, info){
        if (err){
          console.log(err);
          reply({status: 'Email not sent'});
        }
        else {
          console.log(info);
          reply({status: 'Email sent'});
        }
      });
    }
  },
  {
    method: 'GET',
    path: '/{file*}',
    handler: {
      directory: {
        path: 'public'
      }
    }
  },
  {
    method: 'GET',
    path: '/public/jquery.min.js',
    handler: {
      file: {
        path: 'node_modules/jquery/dist/jquery.min.js'
      }
    }
  },
  {
    method: 'GET',
    path: '/public/anime.min.js',
    handler: {
      file: {
        path: 'node_modules/animejs/anime.min.js'
      }
    }
  },
  {
    method: 'GET',
    path: '/public/materialize/{file*}',
    handler: {
      directory: {
        path: 'node_modules/materialize-css/dist'
      }
    }
  }
];
<commit_msg>Move eating page between friends and home pages.<commit_after>require('env2')(`${__dirname}/../.env`);
const sendMail = require('./send-email');

module.exports = [
  {
    method: 'GET',
    path: '/',
    handler: (request, reply) => {
      const data = {
        isWelcome: true,
        next: '/avatar'
      };
      reply.view('welcome', data);
    }
  },
  {
    method: 'GET',
    path: '/avatar',
    handler: (request, reply) => {
      const data = {
        isAvatar: true,
        prev: '/',
        next: '/introduction'
       };
      reply.view('choose-an-avatar', data);
    }
  },
  {
    method: 'GET',
    path: '/introduction',
    handler: (request, reply) => {
      const data =  {
        prev: '/avatar',
        next: '/feelings'
      };
      reply.view('introduction', data);
    }
  },
  {
    method: 'GET',
    path: '/feelings',
    handler: (request, reply) => {
      const data =  {
        prev: '/introduction',
        next: '/personality'
      };
      reply.view('feelings', data);
    }
  },
  {
    method: 'GET',
    path: '/personality',
    handler: (request, reply) => {
      const data =  {
        prev: '/feelings',
        next: '/hobbies'
      };
      reply.view('personality', data);
    }
  },
  {
    method: 'GET',
    path: '/hobbies',
    handler: (request, reply) => {
      const data =  {
        prev: '/personality',
        next: '/sleep'
      };
      reply.view('hobbies', data);
    }
  },
  {
    method: 'GET',
    path: '/sleep',
    handler: (request, reply) => {
      const data =  {
        prev: '/hobbies',
        next: '/friends'
      };
      reply.view('sleep', data);
    }
  },
  {
    method: 'GET',
    path: '/friends',
    handler: (request, reply) => {
      const data =  {
        prev: '/sleep',
        next: '/school'
      };
      reply.view('friends', data);
    }
  },
  {
    method: 'GET',
    path: '/school',
    handler: (request, reply) => {
      const data =  {
        prev: '/friends',
        next: '/eating'
      };
      reply.view('school', data);
    }
  },
  {
    method: 'GET',
    path: '/eating',
    handler: (request, reply) => {
      const data =  {
        prev: '/school',
        next: '/home'
      };
      reply.view('eating', data);
    }
  },
  {
    method: 'GET',
    path: '/home',
    handler: (request, reply) => {
      const data =  {
        prev: '/eating',
        next: '/finished'
      };
      reply.view('home', data);
    }
  },
  {
    method: 'GET',
    path: '/finished',
    handler: (request, reply) => {
      const data =  {
        isEnd: true,
        prev: '/home'
      };
      reply.view('finished', data);
    }
  },
  {
    method: 'GET',
    path: '/info',
    handler: (request, reply) => {
      var data =  {
        isEnd: true,
        prev: '/finished'
      };
      reply.view('info', data);
    }
  },
  {
    method: 'POST',
    path: '/finished',
    handler: (request, reply) => {
      if (process.env.NODE_ENV === 'testing'){
        reply();
        return;
      }
      const { emailAddress, sessionStorage } = request.payload;
      sendMail(emailAddress, sessionStorage, function(err, info){
        if (err){
          console.log(err);
          reply({status: 'Email not sent'});
        }
        else {
          console.log(info);
          reply({status: 'Email sent'});
        }
      });
    }
  },
  {
    method: 'GET',
    path: '/{file*}',
    handler: {
      directory: {
        path: 'public'
      }
    }
  },
  {
    method: 'GET',
    path: '/public/jquery.min.js',
    handler: {
      file: {
        path: 'node_modules/jquery/dist/jquery.min.js'
      }
    }
  },
  {
    method: 'GET',
    path: '/public/anime.min.js',
    handler: {
      file: {
        path: 'node_modules/animejs/anime.min.js'
      }
    }
  },
  {
    method: 'GET',
    path: '/public/materialize/{file*}',
    handler: {
      directory: {
        path: 'node_modules/materialize-css/dist'
      }
    }
  }
];
<|endoftext|>


<commit_before>module.exports = {
  'GET /' : 'main.index',
};

/*
# Normal controllers

The following maps the `/` URL to the `index()` method on the controller at `controllers/main.js`.

```js
module.exports = {
 'GET /' : 'main.index'
};
```

This can also be written as:

```js
module.exports = {
 'GET /' : {
  controller: 'main.index'
 }
};

```

_Note: Supported request methods are: GET, POST, PUT, DEL, OPTIONS and HEAD_.

You can specify one or more middleware which should get run before running the controller method:

```js
module.exports = {
 'GET /' : ['accessControl', 'main.index']
};
```

_Note that when an array is provided, as above, the last item is always expected to be the controller method which is
meant to handle the request_.

You can also write the above as:

```js
module.exports = {
 'GET /' : {
    middleware: ['accessControl'],
    controller: 'main.index'
 }
};
```

In fact, you can even specify other controller methods as middleware:

```js
module.exports = {
  'GET /' : {
    middleware: ['accessControl', 'user.load'],
    controller: 'main.index'
  }
};
```

If a specified middleware item is in the form `module.methodName` then it is assumed to be a method on a controller.
Otherwise it is expected to be the name of a middleware module in the middleware folder.

For the above example, Waigo will process the request in the following order:

  - Load `support/middleware/acccessControl.js` and pass request to its
  - Load `controllers/user.js` and pass request to its `load` method
  - Load `controllers/main.js` and pass request to its `index` method

*/

<commit_msg>Further documentation on middleware.<commit_after>module.exports = {
  'GET /' : 'main.index',
};

/*
# Normal controllers

The following maps the `/` URL to the `index()` method on the controller at `controllers/main.js`.

```js
module.exports = {
 'GET /' : 'main.index'
};
```

This can also be written as:

```js
module.exports = {
 'GET /' : {
  controller: 'main.index'
 }
};

```

_Note: Supported request methods are: GET, POST, PUT, DEL, OPTIONS and HEAD_.

You can specify one or more middleware which should get run before running the controller method:

```js
module.exports = {
 'GET /' : ['accessControl', 'main.index']
};
```

_Note that when an array is provided, as above, the last item is always expected to be the controller method which is
meant to handle the request_.

You can also write the above as:

```js
module.exports = {
 'GET /' : {
    middleware: ['accessControl'],
    controller: 'main.index'
 }
};
```

In fact, you can even specify other controller methods as middleware:

```js
module.exports = {
  'GET /' : {
    middleware: ['accessControl', 'user.load'],
    controller: 'main.index'
  }
};
```

If a specified middleware item is in the form `module.methodName` then it is assumed to be a method on a controller.
Otherwise it is expected to be the name of a middleware module in the middleware folder.

For the above example, Waigo will process the request in the following order:

  - Load `support/middleware/acccessControl.js` and pass request to its
  - Load `controllers/user.js` and pass request to its `load` method
  - Load `controllers/main.js` and pass request to its `index` method

For POST and PUT requests and the like you may wish to enable the [`bodyParser`] and [`csrf`] middleware layers. There
are many readily [available middleware]() layers for Waigo.

*/

<|endoftext|>


<commit_before>import React from 'react';
import App from './components/App';
import {Router, Route} from 'react-router';
import history from './shared';
import Counter from './components/Counter/Counter';

export default (
	<Route path="/" component={App}>
		<Route path="counter" component={Counter}></Route>
	</Route>
)
<commit_msg>update<commit_after>import React from 'react';
import App from './components/app';
import {Router, Route} from 'react-router';
import history from './shared';
import Counter from './components/Counter/Counter';

export default (
	<Route path="/" component={App}>
		<Route path="counter" component={Counter}></Route>
	</Route>
)
<|endoftext|>


<commit_before>/* jslint node:true */

'use strict';

exports = module.exports = {
    auth: auth,
    login: login,
    logout: logout,
    profile: profile,
    getAll: getAll,
    get: get,
    add: add,
    put: put,
    del: del,
    getTags: getTags,
    settingsSave: settingsSave,
    settingsGet: settingsGet,
    exportThings: exportThings,
    importThings: importThings,
    healthcheck: healthcheck,
    fileAdd: fileAdd,
    fileGet: fileGet,

    public: {
        users: publicUsers,
        getAll: publicGetAll,
        getThing: publicGetThing,
        getFile: publicGetFile,
        getRSS: publicGetRSS
    }
};

var assert = require('assert'),
    checksum = require('checksum'),
    config = require('./config.js'),
    fs = require('fs'),
    path = require('path'),
    logic = require('./logic.js'),
    mkdirp = require('mkdirp'),
    path = require('path'),
    rss = require('rss'),
    settings = require('./database/settings.js'),
    tags = require('./database/tags.js'),
    tar = require('tar-fs'),
    tokens = require('./database/tokens.js'),
    users = require('./users.js'),
    uuid = require('uuid'),
    HttpError = require('connect-lastmile').HttpError,
    HttpSuccess = require('connect-lastmile').HttpSuccess;

function healthcheck(req, res, next) {
    next(new HttpSuccess(200, {}));
}

function auth(req, res, next) {
    if (!req.query.token) return next(new HttpError(401, 'missing token'));

    tokens.get(req.query.token, function (error, result) {
        if (error) return next(new HttpError(401, 'invalid credentials'));

        req.token = req.query.token;
        req.userId = result.userId;

        next();
    });
}

function welcomeIfNeeded(userId, callback) {
    assert.strictEqual(typeof userId, 'string');
    assert.strictEqual(typeof callback, 'function');

    logic.getAllLean(userId, function (error, result) {
        if (error) return callback(error);
        if (result.length > 0) return callback(null);

        logic.imp(userId, require('../things.json'), callback);
    });
}
function login(req, res, next) {
    if (typeof req.body.username !== 'string' || !req.body.username) return next(new HttpError(400, 'missing username'));
    if (typeof req.body.password !== 'string' || !req.body.password) return next(new HttpError(400, 'missing password'));

    users.verify(req.body.username, req.body.password, function (error, result) {
        if (error) return next(new HttpError(500, error));
        if (!result) return next(new HttpError(401, 'invalid credentials'));

        var token = uuid.v4();
        tokens.add(token, '', result.user.id, function (error) {
            if (error) return next(new HttpError(500, error));
            next(new HttpSuccess(201, { token: token, user: result.user }));

            // TODO remove this eventually
            // check for old data to import
            if (logic.hasOldData) {
                logic.importThings(result.user.id, logic.hasOldData, function (error) {
                    if (error) return console.error('Failed to import old data', error);

                    logic.cleanupOldData(function (error) {
                        if (error) return console.error('Failed to cleanup old data', error);

                        console.log('Importing old data for user %s done', result.user.id);
                    });
                });
            } else {
                welcomeIfNeeded(result.user.id, function (error) {
                    if (error) console.error(error);

                    console.log('Seed welcome data for user %s', result.user.id);
                });
            }
        });
    });
}

function logout(req, res, next) {
    tokens.del(req.token, function (error) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, {}));
    });
}

function profile(req, res, next) {
    users.profile(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));

        var out = {
            mailbox: process.env.MAIL_TO ? (process.env.MAIL_IMAP_USERNAME + '+' + result.username + '@' + process.env.MAIL_DOMAIN) : null,
            user: result
        };

        next(new HttpSuccess(200, out));
    });
}

function getAll(req, res, next) {
    var query = {};

    if (req.query && req.query.filter) {
        query = {
            $text: { $search: String(req.query.filter) }
        };
    }

    var skip = isNaN(parseInt(req.query.skip)) ? 0 : parseInt(req.query.skip);
    var limit = isNaN(parseInt(req.query.limit)) ? 10 : parseInt(req.query.limit);

    logic.getAll(req.userId, query, skip, limit, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { things: result }));
    });
}

function get(req, res, next) {
    logic.get(req.userId, req.params.id, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { thing: result }));
    });
}

function add(req, res, next) {
    if (typeof req.body.content !== 'string' || !req.body.content) return next(new HttpError(400, 'content must be a string'));
    if (req.body.attachments && !Array.isArray(req.body.attachments)) return next(new HttpError(400, 'attachments must be an array'));

    if (!req.body.attachments) req.body.attachments = [];

    logic.add(req.userId, req.body.content, req.body.attachments, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(201, { thing: result }));
    });
}

function put(req, res, next) {
    if (typeof req.body.content !== 'string' || !req.body.content) return next(new HttpError(400, 'content must be a string'));
    if (req.body.attachments && !Array.isArray(req.body.attachments)) return next(new HttpError(400, 'attachments must be an array'));
    if (req.body.public && typeof req.body.public !== 'boolean') return next(new HttpError(400, 'public must be a boolean'));

    if (!req.body.attachments) req.body.attachments = [];

    req.body.public = !!req.body.public;

    logic.put(req.userId, req.params.id, req.body.content, req.body.attachments, req.body.public, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(201, { thing: result }));
    });
}

function del(req, res, next) {
    logic.del(req.userId, req.params.id, function (error) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, {}));
    });
}

function getTags(req, res, next) {
    tags.get(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { tags: result }));
    });
}

function settingsSave(req, res, next) {
    settings.put(req.userId, req.body.settings, function (error) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(202, {}));
    });
}

function settingsGet(req, res, next) {
    settings.get(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { settings: result }));
    });
}

function exportThings(req, res, next) {
    // Just to make sure the folder exists in case a user has never uploaded an attachment
    var attachmentFolder = path.join(config.attachmentDir, req.userId);
    mkdirp.sync(attachmentFolder);

    logic.exp(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));

        var out = tar.pack(attachmentFolder, {
            map: function (header) {
                header.name = 'attachments/' + header.name;
                return header;
            }
        });

        // add the db dump
        out.entry({ name: 'things.json' }, JSON.stringify(result, null, 4));

        res.attachment('guacamoly-export.tar');
        out.pipe(res);
    });
}

function importThings(req, res, next) {
    if (!req.files || !req.files[0]) return next(new HttpError('400', 'missing file'));

    logic.importThings(req.userId, req.files[0].path, function (error) {
        if (error) return next(new HttpError(400, error));

        next(new HttpSuccess(200, {}));
    });
}

function fileAdd(req, res, next) {
    if (!req.files || !req.files[0]) return next(new HttpError('400', 'missing file'));

    var file = req.files[0];
    var fileName = checksum(file.buffer) + path.extname(file.originalname);
    var attachmentFolder = path.join(config.attachmentDir, req.userId);

    // ensure the directory exists
    mkdirp.sync(attachmentFolder);

    fs.writeFile(path.join(attachmentFolder, fileName), file.buffer, function (error) {
        if (error) return next(new HttpError(500, error));

        var type = file.mimetype.indexOf('image/') === 0 ? logic.TYPE_IMAGE : logic.TYPE_UNKNOWN;

        next(new HttpSuccess(201, { identifier: fileName, fileName: file.originalname, type: type }));
    });
}

function fileGet(req, res) {
    res.sendFile(req.params.identifier, { root: path.join(config.attachmentDir, req.params.userId) });
}

function publicGetThing(req, res, next) {
    logic.getPublic(req.params.userId, req.params.thingId, function (error, result) {
        if (error === 'not allowed') return next(new HttpError(403, 'not allowed'));
        if (error) return next(new HttpError(500, error));

        next(new HttpSuccess(200, { thing: result }));
    });
}

function publicGetAll(req, res, next) {
    var query = {};

    if (req.query && req.query.filter) {
        query = {
            $text: { $search: String(req.query.filter) }
        };
    }

    var skip = isNaN(parseInt(req.query.skip)) ? 0 : parseInt(req.query.skip);
    var limit = isNaN(parseInt(req.query.limit)) ? 10 : parseInt(req.query.limit);

    logic.getAllPublic(req.params.userId, query, skip, limit, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { things: result }));
    });
}

function publicGetFile(req, res) {
    res.sendFile(req.params.fileId, { root: path.join(config.attachmentDir, req.params.userId) });
}

function publicUsers(req, res, next) {
    users.list(function (error, result) {
        if (error) return next(new HttpError(500, error));

        next(new HttpSuccess(200, { users: result }));
    });
}

function publicGetRSS(req, res, next) {
    var query = {};

    users.profile(req.params.userId, function (error, user) {
        if (error) return next(new HttpError(500, error));

        settings.get(req.params.userId, function (error, config) {
            if (error) return next(new HttpError(500, error));

            logic.getAllPublic(req.params.userId, query, 0, 50, function (error, result) {
                if (error) return next(new HttpError(500, error));

                // TODO
                var webServer = '/';

                var feed = new rss({
                    title: config.title,
                    image_url: webServer + '/img/logo128.png',
                    site_url: webServer
                });

                // generate the rss feed items
                result.forEach(function (r) {
                    var title = r.content.split('\n').filter(function (l) { return !!l.trim(); })[0];

                    feed.item({
                        title: title,
                        url: webServer + '/blog/' + 'TODO', // TODO
                        author: user.displayName + '( ' + user.username + ' )',
                        date: new Date(r.createdAt),
                        description: r.richContent
                    });
                });

                res.type('application/rss+xml').status(200).send(feed.xml());
            });
        });
    });
}
<commit_msg>Relayout the code a bit<commit_after>/* jslint node:true */

'use strict';

exports = module.exports = {
    auth: auth,
    login: login,
    logout: logout,
    profile: profile,
    getAll: getAll,
    get: get,
    add: add,
    put: put,
    del: del,
    getTags: getTags,
    settingsSave: settingsSave,
    settingsGet: settingsGet,
    exportThings: exportThings,
    importThings: importThings,
    healthcheck: healthcheck,
    fileAdd: fileAdd,
    fileGet: fileGet,

    public: {
        users: publicUsers,
        getAll: publicGetAll,
        getThing: publicGetThing,
        getFile: publicGetFile,
        getRSS: publicGetRSS
    }
};

var assert = require('assert'),
    checksum = require('checksum'),
    config = require('./config.js'),
    fs = require('fs'),
    path = require('path'),
    logic = require('./logic.js'),
    mkdirp = require('mkdirp'),
    path = require('path'),
    rss = require('rss'),
    settings = require('./database/settings.js'),
    tags = require('./database/tags.js'),
    tar = require('tar-fs'),
    tokens = require('./database/tokens.js'),
    users = require('./users.js'),
    uuid = require('uuid'),
    HttpError = require('connect-lastmile').HttpError,
    HttpSuccess = require('connect-lastmile').HttpSuccess;

function healthcheck(req, res, next) {
    next(new HttpSuccess(200, {}));
}

function auth(req, res, next) {
    if (!req.query.token) return next(new HttpError(401, 'missing token'));

    tokens.get(req.query.token, function (error, result) {
        if (error) return next(new HttpError(401, 'invalid credentials'));

        req.token = req.query.token;
        req.userId = result.userId;

        next();
    });
}

function welcomeIfNeeded(userId, callback) {
    assert.strictEqual(typeof userId, 'string');
    assert.strictEqual(typeof callback, 'function');

    logic.getAllLean(userId, function (error, result) {
        if (error) return callback(error);
        if (result.length > 0) return callback(null);

        logic.imp(userId, require('../things.json'), callback);
    });
}
function login(req, res, next) {
    if (typeof req.body.username !== 'string' || !req.body.username) return next(new HttpError(400, 'missing username'));
    if (typeof req.body.password !== 'string' || !req.body.password) return next(new HttpError(400, 'missing password'));

    users.verify(req.body.username, req.body.password, function (error, result) {
        if (error) return next(new HttpError(500, error));
        if (!result) return next(new HttpError(401, 'invalid credentials'));

        var token = uuid.v4();
        tokens.add(token, '', result.user.id, function (error) {
            if (error) return next(new HttpError(500, error));
            next(new HttpSuccess(201, { token: token, user: result.user }));

            // TODO remove this eventually
            // check for old data to import
            if (logic.hasOldData) {
                logic.importThings(result.user.id, logic.hasOldData, function (error) {
                    if (error) return console.error('Failed to import old data', error);

                    logic.cleanupOldData(function (error) {
                        if (error) return console.error('Failed to cleanup old data', error);

                        console.log('Importing old data for user %s done', result.user.id);
                    });
                });
            } else {
                welcomeIfNeeded(result.user.id, function (error) {
                    if (error) console.error(error);

                    console.log('Seed welcome data for user %s', result.user.id);
                });
            }
        });
    });
}

function logout(req, res, next) {
    tokens.del(req.token, function (error) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, {}));
    });
}

function profile(req, res, next) {
    users.profile(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));

        var out = {
            mailbox: process.env.MAIL_TO ? (process.env.MAIL_IMAP_USERNAME + '+' + result.username + '@' + process.env.MAIL_DOMAIN) : null,
            user: result
        };

        next(new HttpSuccess(200, out));
    });
}

function getAll(req, res, next) {
    var query = {};

    if (req.query && req.query.filter) {
        query = {
            $text: { $search: String(req.query.filter) }
        };
    }

    var skip = isNaN(parseInt(req.query.skip)) ? 0 : parseInt(req.query.skip);
    var limit = isNaN(parseInt(req.query.limit)) ? 10 : parseInt(req.query.limit);

    logic.getAll(req.userId, query, skip, limit, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { things: result }));
    });
}

function get(req, res, next) {
    logic.get(req.userId, req.params.id, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { thing: result }));
    });
}

function add(req, res, next) {
    if (typeof req.body.content !== 'string' || !req.body.content) return next(new HttpError(400, 'content must be a string'));
    if (req.body.attachments && !Array.isArray(req.body.attachments)) return next(new HttpError(400, 'attachments must be an array'));

    if (!req.body.attachments) req.body.attachments = [];

    logic.add(req.userId, req.body.content, req.body.attachments, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(201, { thing: result }));
    });
}

function put(req, res, next) {
    if (typeof req.body.content !== 'string' || !req.body.content) return next(new HttpError(400, 'content must be a string'));
    if (req.body.attachments && !Array.isArray(req.body.attachments)) return next(new HttpError(400, 'attachments must be an array'));
    if (req.body.public && typeof req.body.public !== 'boolean') return next(new HttpError(400, 'public must be a boolean'));

    if (!req.body.attachments) req.body.attachments = [];

    req.body.public = !!req.body.public;

    logic.put(req.userId, req.params.id, req.body.content, req.body.attachments, req.body.public, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(201, { thing: result }));
    });
}

function del(req, res, next) {
    logic.del(req.userId, req.params.id, function (error) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, {}));
    });
}

function getTags(req, res, next) {
    tags.get(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { tags: result }));
    });
}

function settingsSave(req, res, next) {
    settings.put(req.userId, req.body.settings, function (error) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(202, {}));
    });
}

function settingsGet(req, res, next) {
    settings.get(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { settings: result }));
    });
}

function exportThings(req, res, next) {
    // Just to make sure the folder exists in case a user has never uploaded an attachment
    var attachmentFolder = path.join(config.attachmentDir, req.userId);
    mkdirp.sync(attachmentFolder);

    logic.exp(req.userId, function (error, result) {
        if (error) return next(new HttpError(500, error));

        var out = tar.pack(attachmentFolder, {
            map: function (header) {
                header.name = 'attachments/' + header.name;
                return header;
            }
        });

        // add the db dump
        out.entry({ name: 'things.json' }, JSON.stringify(result, null, 4));

        res.attachment('guacamoly-export.tar');
        out.pipe(res);
    });
}

function importThings(req, res, next) {
    if (!req.files || !req.files[0]) return next(new HttpError('400', 'missing file'));

    logic.importThings(req.userId, req.files[0].path, function (error) {
        if (error) return next(new HttpError(400, error));

        next(new HttpSuccess(200, {}));
    });
}

function fileAdd(req, res, next) {
    if (!req.files || !req.files[0]) return next(new HttpError('400', 'missing file'));

    var file = req.files[0];
    var fileName = checksum(file.buffer) + path.extname(file.originalname);
    var attachmentFolder = path.join(config.attachmentDir, req.userId);

    // ensure the directory exists
    mkdirp.sync(attachmentFolder);

    fs.writeFile(path.join(attachmentFolder, fileName), file.buffer, function (error) {
        if (error) return next(new HttpError(500, error));

        var type = file.mimetype.indexOf('image/') === 0 ? logic.TYPE_IMAGE : logic.TYPE_UNKNOWN;

        next(new HttpSuccess(201, { identifier: fileName, fileName: file.originalname, type: type }));
    });
}

function fileGet(req, res) {
    res.sendFile(req.params.identifier, { root: path.join(config.attachmentDir, req.params.userId) });
}

function publicGetThing(req, res, next) {
    logic.getPublic(req.params.userId, req.params.thingId, function (error, result) {
        if (error === 'not allowed') return next(new HttpError(403, 'not allowed'));
        if (error) return next(new HttpError(500, error));

        next(new HttpSuccess(200, { thing: result }));
    });
}

function publicGetAll(req, res, next) {
    var query = {};

    if (req.query && req.query.filter) {
        query = {
            $text: { $search: String(req.query.filter) }
        };
    }

    var skip = isNaN(parseInt(req.query.skip)) ? 0 : parseInt(req.query.skip);
    var limit = isNaN(parseInt(req.query.limit)) ? 10 : parseInt(req.query.limit);

    logic.getAllPublic(req.params.userId, query, skip, limit, function (error, result) {
        if (error) return next(new HttpError(500, error));
        next(new HttpSuccess(200, { things: result }));
    });
}

function publicGetFile(req, res) {
    res.sendFile(req.params.fileId, { root: path.join(config.attachmentDir, req.params.userId) });
}

function publicUsers(req, res, next) {
    users.list(function (error, result) {
        if (error) return next(new HttpError(500, error));

        next(new HttpSuccess(200, { users: result }));
    });
}

function publicGetRSS(req, res, next) {
    assert.strictEqual(typeof req.params.userId, 'string');

    users.profile(req.params.userId, function (error, user) {
        if (error) return next(new HttpError(500, error));

        settings.get(req.params.userId, function (error, config) {
            if (error) return next(new HttpError(500, error));

            logic.getAllPublic(req.params.userId, {}, 0, 50, function (error, result) {
                if (error) return next(new HttpError(500, error));

                // TODO
                var webServer = '/';

                var feed = new rss({
                    title: config.title,
                    image_url: webServer + '/img/logo128.png',
                    site_url: webServer
                });

                // generate the rss feed items
                result.forEach(function (r) {
                    var title = r.content.split('\n').filter(function (l) { return !!l.trim(); })[0];

                    feed.item({
                        title: title,
                        url: webServer + '/blog/' + 'TODO', // TODO
                        author: user.displayName + '( ' + user.username + ' )',
                        date: new Date(r.createdAt),
                        description: r.richContent
                    });
                });

                res.type('application/rss+xml').status(200).send(feed.xml());
            });
        });
    });
}
<|endoftext|>


<commit_before>const typeDefinitions = `

enum LeagueName {
  ELITE
  LOC
  PARALIGA
}

type League {
  name: String,
  players: [Player]
}

type Player {
  name: String
  stats: Stats
  matches(filter: MatchFilter): [Match]
}

type Stats {
  points: Int
  gamesPlayed: Int
  gamesWon: Int
  gamesDraw: Int
  gamesLost: Int
  goalsInFavor: Int
  goalsAgains: Int
  goalDifference: Int
}

type Match {
  home: MatchTeam
  away: MatchTeam
}

type MatchTeam {
  player: Player
  score: Int
}

enum MatchFilter {
  WON
  LOST
  DRAW
  UNPLAYED
  ALL
}

type Query {
  league(name: LeagueName!): League
  leagues: [League]
}

schema {
  query: Query
}
`

export default [typeDefinitions]
<commit_msg>add team and PLAYED filter<commit_after>const typeDefinitions = `

enum LeagueName {
  ELITE
  LOC
  PARALIGA
}

type League {
  name: String,
  players: [Player]
}

type Player {
  name: String
  team: String
  stats: Stats
  matches(filter: MatchFilter): [Match]
}

type Stats {
  points: Int
  gamesPlayed: Int
  gamesWon: Int
  gamesDraw: Int
  gamesLost: Int
  goalsInFavor: Int
  goalsAgains: Int
  goalDifference: Int
}

type Match {
  home: MatchTeam
  away: MatchTeam
}

type MatchTeam {
  player: Player,
  score: Int
}

enum MatchFilter {
  WON
  LOST
  DRAW
  PLAYED
  UNPLAYED
  ALL
}

type Query {
  league(name: LeagueName!): League
  leagues: [League]
}

schema {
  query: Query
}
`

export default [typeDefinitions]
<|endoftext|>


<commit_before>class SchemaValidatorError extends Error {
  constructor(message) {
    super();
    this.message = message;
  }
}

class Reject {
  constructor(message) {
    this.message = message;
  }
  toError(name, value) {
    const stringValue = JSON.stringify(value);
    return new SchemaValidatorError(`${name} ${this.message}, but got ${stringValue}`);
  }
}

class Break {
  constructor(value) {
    this.value = value;
  }
}

// schema object
const createSchemaClass = plugins => {
  class Schema {
    constructor(validators, context) {
      this._validators = validators || [];
      this.context = context || {
        name: 'value'
      };
    }
    _init(validators, context) {
      return new Schema(validators, context);
    }
    empty() {
      return this._init();
    }
    reject(message) {
      return new Reject(message);
    }
    break_(value) {
      return new Break(value);
    }
    _withContext(additional) {
      return this._init(this._validators, Object.assign({}, this.context, additional || {}));
    }
    name(name) {
      return this._withContext({
        name: name
      });
    }
    _first(validator) {
      return this._init([validator].concat(this._validators), this.context);
    }
    _last(validator) {
      return this._init(this._validators.concat([validator]), this.context);
    }
    first(f) {
      return this._first({
        _validate: f
      });
    }
    then(f) {
      return this._last({
        _validate: value => {
          const newValue = f(value);
          if (newValue instanceof Schema) {
            return newValue._validate(value);
          }
          return newValue;
        }
      });
    }
    check(f) {
      return this.then(value => {
        let result = f(value);
        if (result instanceof Schema) {
          result = result._validate(value);
        }
        if (result instanceof Reject) {
          return result;
        }
        return value;
      });
    }
    when(checkerSchema, thenSchema, elseSchema) {
      return this.then(value => {
        if (checkerSchema._isValid(value)) {
          return thenSchema;
        }
        if (elseSchema) {
          return elseSchema;
        }
        return value;
      });
    }
    try_(schema, catchSchema) {
      return this.then(value => {
        let result = schema._validate(value);
        if (result instanceof Reject) {
          return catchSchema || value;
        }
        return result;
      });
    }
    validate(value) {
      const newValue = this._validate(value);
      if (newValue instanceof Reject) {
        throw newValue.toError(this.context.name, value);
      } else if (newValue instanceof Break) {
        return newValue.value;
      }
      return newValue;
    }
    _isValid(value) {
      const newValue = this._validate(value);
      return !(newValue instanceof Reject);
    }
    _validate(value) {
      return validateHelp(this._validators, 0, this.context.name, value);
    }
    _validateAll(items, f) {
      const newItems = [];
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const itemSchema = f(item, i);
        const result = itemSchema._validate(item);
        if (result instanceof Reject) {
          return result;
        }
        newItems.push(item);
      }
      return newItems;
    }
  }
  plugins.forEach(plugin => addPlugin(Schema.prototype, plugin));
  return Schema;
}

function validateHelp(validators, i, name, value) {
  if (i >= validators.length) {
    return value;
  }
  const validator = validators[i];
  const newValue = validator._validate(value);
  if (newValue instanceof Reject) {
    return newValue;
  } else if (newValue instanceof Break) {
    return newValue.value;
  }
  return validateHelp(validators, i + 1, name, newValue);
}

function addPlugin(prototype, plugin) {
  Object.keys(plugin).forEach(key => {
    if (prototype[key]) {
      throw new Error(`PluginError: Function ${key} is already defined.`);
    }
    const f = plugin[key];
    if (typeof f !== 'function') {
      throw new Error(`PluginError: Plugin ${key} is mulformed. Value should be a function.`);
    }
    prototype[key] = f;
  });
}

module.exports = {
  createClass: createSchemaClass,
  SchemaValidatorError: SchemaValidatorError,
};
<commit_msg>refactor schema class<commit_after>class SchemaValidatorError extends Error {
  constructor(message) {
    super();
    this.message = message;
  }
}

class Reject {
  constructor(message) {
    this.message = message;
  }
  toError(name, value) {
    const stringValue = JSON.stringify(value);
    return new SchemaValidatorError(`${name} ${this.message}, but got ${stringValue}`);
  }
}

class Break {
  constructor(value) {
    this.value = value;
  }
}

// schema object
const createSchemaClass = plugins => {
  class Schema {
    constructor(validators, context) {
      this._validators = validators || [];
      this.context = context || {
        name: 'value'
      };
    }
    empty() {
      return init();
    }
    reject(message) {
      return new Reject(message);
    }
    break_(value) {
      return new Break(value);
    }
    _withContext(additional) {
      return init(this._validators, Object.assign({}, this.context, additional || {}));
    }
    name(name) {
      return this._withContext({
        name: name
      });
    }
    _first(validator) {
      return init([validator].concat(this._validators), this.context);
    }
    _last(validator) {
      return init(this._validators.concat([validator]), this.context);
    }
    first(f) {
      return this._first({
        _validate: wrapValidate(f)
      });
    }
    then(f) {
      return this._last({
        _validate: wrapValidate(f)
      });
    }
    _when(schema, f) {
      return this.then(value => {
        let result = schema._validate(value);
        return f(value, result);
      });
    }
    when(checkerSchema, thenSchema, elseSchema) {
      return this._when(checkerSchema, (original, result) => {
        if (result instanceof Reject) {
          return elseSchema || original;
        }
        return thenSchema;
      });
    }
    _check(checkerSchema) {
      return this._when(checkerSchema, (original, result) => {
        if (result instanceof Reject) {
          return result
        }
        return original;
      });
    }
    check(f) {
      return this._check(this.empty().then(f));
    }
    try_(schema, catchSchema) {
      return this._when(schema, (original, result) => {
        if (result instanceof Reject) {
          return catchSchema || original;
        }
        return result;
      });
    }
    _validate(value) {
      return validateHelp(this._validators, 0, this.context.name, value);
    }
    validate(value) {
      const newValue = this._validate(value);
      if (newValue instanceof Reject) {
        throw newValue.toError(this.context.name, value);
      } else if (newValue instanceof Break) {
        return newValue.value;
      }
      return newValue;
    }
    _validateAll(items, toItemSchema) {
      const newItems = [];
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const itemSchema = toItemSchema(item, i);
        const result = itemSchema._validate(item);
        if (result instanceof Reject) {
          return result;
        }
        newItems.push(item);
      }
      return newItems;
    }
  }

  function init(validators, context) {
    return new Schema(validators, context);
  }

  function wrapValidate(f) {
    return value => {
      const newValue = f(value);
      if (newValue instanceof Schema) {
        return newValue._validate(value);
      }
      return newValue;
    };
  }
  plugins.forEach(plugin => addPlugin(Schema.prototype, plugin));
  return Schema;
}

function validateHelp(validators, i, name, value) {
  if (i >= validators.length) {
    return value;
  }
  const validator = validators[i];
  const newValue = validator._validate(value);
  if (newValue instanceof Reject) {
    return newValue;
  } else if (newValue instanceof Break) {
    return newValue.value;
  }
  return validateHelp(validators, i + 1, name, newValue);
}

function addPlugin(prototype, plugin) {
  Object.keys(plugin).forEach(key => {
    if (prototype[key]) {
      throw new Error(`PluginError: Function ${key} is already defined.`);
    }
    const f = plugin[key];
    if (typeof f !== 'function') {
      throw new Error(`PluginError: Plugin ${key} is mulformed. Value should be a function.`);
    }
    prototype[key] = f;
  });
}

module.exports = {
  createClass: createSchemaClass,
  SchemaValidatorError: SchemaValidatorError,
};
<|endoftext|>


<commit_before>(function ($) {
    //-----------------------+
    // Better val() function |
    //-----------------------+
    $.fn.valInternal = jQuery.fn.val;
    $.fn.val = function (val) {
        if (!this.length) {
            return;
        }

        var type = this.attr('type');
        type = type ? type : this.get(0).tagName.toLowerCase();
        switch (type) {
            case 'checkbox':
                if (arguments.length) {
                    this.prop('checked', !!val);
                } else {
                    return this.is(':checked') ? $.fn.valInternal.call(this) : '';
                }
                break;
            default:
                if (arguments.length) {
                    return $.fn.valInternal.call(this, val);
                } else {
                    return $.fn.valInternal.call(this);
                }
        }
    };

    //-------+
    // Setup |
    //-------+
    $.ajaxSetup({async: false});

    //-----------------+
    // Selects Command |
    //-----------------+
    $(document).on('mouseover', '#command', function () {
        // select text
        this.select();
    });
    $(document).on('mouseout', '#command', function () {
        // deselect text
        this.selectionStart = this.selectionEnd;
    });

    //------+
    // Init |
    //------+
    var URL = document.URL.replace(/(\/index.html.*)|(\/)$/, '');
    window.form = $('#form').get(0);
    form.values = {};
    form.options = $('#options').get(0);
    form.modules = {};
    form.task.onChange = [];
    form.command = '';

    //-----------+
    // Functions |
    //-----------+

    // Load form options
    form.options.load = function (name) {
        $.get(URL + '/' + name + '/~builder/options.html', function (response) {
            form.options.innerHTML += response;
        });
    };

    // Add command argument
    form.setCommand = function (cond, name, value) {
        form.command += cond ? ' -' + name + (value ? ' ' + value : '') : '';
    };

    // Invoke module update
    form.update = function (modules) {
        modules.forEach(function (module) {
            if (form.modules[module] && form.modules[module].onUpdate) {
                form.modules[module].onUpdate();
            }
        });
    };

    //--------------------+
    // Handle form update |
    //--------------------+
    var update = function (event) {
        if (event) {
            // task select
            if ($(event.target).is('[name=task]')) {
                change();
                return;
            }
        }

        // command update
        form.command = URL;
        var task = '/' + form.task.value;
        form.command += task + ' -qO- | sh -s --';

        // no interaction
        form.setCommand(form.no_interaction.checked, 'n');

        // environment
        form.setCommand(form.env.value, form.env.value);

        // switch support
        console.log(form.support);
        if (form.support[form.support.value] === "wbpo") {
            // support WBPO
            form.setCommand(true, 'with-wbpo');
        }

        // support Webino
        if (form.support[form.support.value] !== "webino") {
            form.setCommand(true, 'without-webino');
        }

        // admin email
        form.setCommand(form.admin_email.value, 'admin-email', form.admin_email.value);

        // update module options
        if (form.modules[form.task.value] && form.modules[form.task.value].options) {
            form.update(form.modules[form.task.value].options);
        }

        // update command
        $('#command').val('wget ' + form.command);
    };

    //--------------------+
    // Handle task select |
    //--------------------+
    var change = function () {
        // store form values
        $(form).find('input,select').each(function (n, node) {
            var el = $(node);
            node.name && (form.values[node.name] = el.val());
        });

        // load options
        form.options.innerHTML = '';
        if (form.modules[form.task.value] && form.modules[form.task.value].options) {
            form.modules[form.task.value].options.forEach(function (module) {
                form.options.load(module);
            });
        }

        // restore form values
        for (var key in form.values) {
            if (form.values.hasOwnProperty(key)) {
                $(form).find('[name='+ key +']').val(form.values[key]);
            }
        }

        // update command
        update();
    };

    //------------------+
    // Bind form update |
    //------------------+
    $(document).on('change', 'form', update);
    $(document).on('keyup', 'form', update);

    //------------+
    // Init tasks |
    //------------+
    $(form.task).find('option:not(:disabled)').each(function () {
        this.value && $.get(URL + '/' + this.value + '/~builder/script.js');
    });

    //------------+
    // Initialize |
    //------------+
    change();

})(jQuery);
<commit_msg>Support WIP<commit_after>(function ($) {
    //-----------------------+
    // Better val() function |
    //-----------------------+
    $.fn.valInternal = jQuery.fn.val;
    $.fn.val = function (val) {
        if (!this.length) {
            return;
        }

        var type = this.attr('type');
        type = type ? type : this.get(0).tagName.toLowerCase();
        switch (type) {
            case 'checkbox':
            case 'radio':
                if (arguments.length) {
                    this.prop('checked', !!val);
                } else {
                    return this.is(':checked') ? $.fn.valInternal.call(this) : '';
                }
                break;
            default:
                if (arguments.length) {
                    return $.fn.valInternal.call(this, val);
                } else {
                    return $.fn.valInternal.call(this);
                }
        }
    };

    //-------+
    // Setup |
    //-------+
    $.ajaxSetup({async: false});

    //-----------------+
    // Selects Command |
    //-----------------+
    $(document).on('mouseover', '#command', function () {
        // select text
        this.select();
    });
    $(document).on('mouseout', '#command', function () {
        // deselect text
        this.selectionStart = this.selectionEnd;
    });

    //------+
    // Init |
    //------+
    var URL = document.URL.replace(/(\/index.html.*)|(\/)$/, '');
    window.form = $('#form').get(0);
    form.values = {};
    form.options = $('#options').get(0);
    form.modules = {};
    form.task.onChange = [];
    form.command = '';

    //-----------+
    // Functions |
    //-----------+

    // Load form options
    form.options.load = function (name) {
        $.get(URL + '/' + name + '/~builder/options.html', function (response) {
            form.options.innerHTML += response;
        });
    };

    // Add command argument
    form.setCommand = function (cond, name, value) {
        form.command += cond ? ' -' + name + (value ? ' ' + value : '') : '';
    };

    // Invoke module update
    form.update = function (modules) {
        modules.forEach(function (module) {
            if (form.modules[module] && form.modules[module].onUpdate) {
                form.modules[module].onUpdate();
            }
        });
    };

    //--------------------+
    // Handle form update |
    //--------------------+
    var update = function (event) {
        if (event) {
            // task select
            if ($(event.target).is('[name=task]')) {
                change();
                return;
            }
        }

        // command update
        form.command = URL;
        var task = '/' + form.task.value;
        form.command += task + ' -qO- | sh -s --';

        // no interaction
        form.setCommand(form.no_interaction.checked, 'n');

        // environment
        form.setCommand(form.env.value, form.env.value);

        // switch support
        var support = $(form.support).val();
        if (support === "wbpo") {
            // support WBPO
            form.setCommand(true, 'with-wbpo');
        }

        // support Webino
        if (support !== "webino") {
            form.setCommand(true, 'without-webino');
        }

        // admin email
        form.setCommand(form.admin_email.value, 'admin-email', form.admin_email.value);

        // update module options
        if (form.modules[form.task.value] && form.modules[form.task.value].options) {
            form.update(form.modules[form.task.value].options);
        }

        // update command
        $('#command').val('wget ' + form.command);
    };

    //--------------------+
    // Handle task select |
    //--------------------+
    var change = function () {
        // store form values
        $(form).find('input,select').each(function (n, node) {
            var el = $(node);
            node.name && (form.values[node.name] = el.val());
        });

        // load options
        form.options.innerHTML = '';
        if (form.modules[form.task.value] && form.modules[form.task.value].options) {
            form.modules[form.task.value].options.forEach(function (module) {
                form.options.load(module);
            });
        }

        // restore form values
        for (var key in form.values) {
            if (form.values.hasOwnProperty(key)) {
                $(form).find('[name='+ key +']').val(form.values[key]);
            }
        }

        // update command
        update();
    };

    //------------------+
    // Bind form update |
    //------------------+
    $(document).on('change', 'form', update);
    $(document).on('keyup', 'form', update);

    //------------+
    // Init tasks |
    //------------+
    $(form.task).find('option:not(:disabled)').each(function () {
        this.value && $.get(URL + '/' + this.value + '/~builder/script.js');
    });

    //------------+
    // Initialize |
    //------------+
    change();

})(jQuery);
<|endoftext|>


<commit_before>import { partial, partialRight } from 'lodash'
import { add, find, flow, get, getOr, orderBy, reverse } from 'lodash/fp'
import { getSelect } from 'cape-select'
import { createSelector } from 'reselect'

// NOTE: These all act on history state directly. Redux slice needs to be selected first.

export const getHistoryItems = get('key')
export const getActiveId = get('activeKey')
export const getFirstId = get('firstKey')
export const getLastId = get('lastKey')

export const getHistoryItem = partial(getSelect, getHistoryItems)

export const selectActive = getHistoryItem(getActiveId)
export const selectActiveKey = selectActive
export const selectFirst = getHistoryItem(getFirstId)
export const selectFirstKey = selectFirst
export const selectLast = getHistoryItem(getLastId)
export const selectLastKey = selectLast

export const getIndex = partialRight(flow, getOr(0, 'index'))

export const selectActiveIndex = getIndex(selectActive)
export const getKeyIndex = selectActiveIndex
export const getFirstIndex = getIndex(selectFirst)
export const getLastIndex = getIndex(selectLast)

export const selectPrevIndex = flow(selectActiveIndex, add(-1))
export const selectNextIndex = flow(selectActiveIndex, add(1))
export const getLength = selectNextIndex

export function historyMatch(reduxHistory, windowHistory) {
  if (!windowHistory || !windowHistory.id) throw new Error('Missing window.history.state')
  const activeKey = selectActiveKey(reduxHistory)
  return activeKey.id === windowHistory.id
}
export function browserHistory(reduxHistory) {
  return {
    ...selectActiveKey(reduxHistory),
    length: getLength(reduxHistory),
  }
}
export function lengthMatch(reduxHistory, windowHistory) {
  return getLength(reduxHistory) === windowHistory.length
}
export const sortedHistoryItems = createSelector(
  getHistoryItems,
  orderBy('index', 'asc')
)
export const sortedHistoryItemsDesc = flow(sortedHistoryItems, reverse)
export const selectPrevious = getSelect(sortedHistoryItems, selectPrevIndex)
export function findDifferentPage(isDifferentFunc) {
  return flow(sortedHistoryItemsDesc, find(isDifferentFunc))
}
<commit_msg>selectActive is a better name<commit_after>import { partial, partialRight } from 'lodash'
import { add, find, flow, get, getOr, orderBy, reverse } from 'lodash/fp'
import { getSelect } from 'cape-select'
import { createSelector } from 'reselect'

// NOTE: These all act on history state directly. Redux slice needs to be selected first.

export const getHistoryItems = get('key')
export const getActiveId = get('activeKey')
export const getFirstId = get('firstKey')
export const getLastId = get('lastKey')

export const getHistoryItem = partial(getSelect, getHistoryItems)

export const selectActive = getHistoryItem(getActiveId)
export const selectActiveKey = selectActive
export const selectFirst = getHistoryItem(getFirstId)
export const selectFirstKey = selectFirst
export const selectLast = getHistoryItem(getLastId)
export const selectLastKey = selectLast

export const getIndex = partialRight(flow, getOr(0, 'index'))

export const selectActiveIndex = getIndex(selectActive)
export const getKeyIndex = selectActiveIndex
export const getFirstIndex = getIndex(selectFirst)
export const getLastIndex = getIndex(selectLast)

export const selectPrevIndex = flow(selectActiveIndex, add(-1))
export const selectNextIndex = flow(selectActiveIndex, add(1))
export const getLength = selectNextIndex

export function historyMatch(reduxHistory, windowHistory) {
  if (!windowHistory || !windowHistory.id) throw new Error('Missing window.history.state')
  const activeKey = selectActive(reduxHistory)
  return activeKey.id === windowHistory.id
}
export function browserHistory(reduxHistory) {
  return {
    ...selectActive(reduxHistory),
    length: getLength(reduxHistory),
  }
}
export function lengthMatch(reduxHistory, windowHistory) {
  return getLength(reduxHistory) === windowHistory.length
}
export const sortedHistoryItems = createSelector(
  getHistoryItems,
  orderBy('index', 'asc')
)
export const sortedHistoryItemsDesc = flow(sortedHistoryItems, reverse)
export const selectPrevious = getSelect(sortedHistoryItems, selectPrevIndex)
export function findDifferentPage(isDifferentFunc) {
  return flow(sortedHistoryItemsDesc, find(isDifferentFunc))
}
<|endoftext|>


<commit_before>var express = require('express'),
    path = require('path'),
    http = require('http'),
    mongoose = require('mongoose'),
    cookie = require('cookie'),
    connect = require('connect'),
	passport = require('passport'),
	LocalStrategy = require('passport-local').Strategy;

var config = require('./config.js'),
    log = require('./log.js'),
    routes = require('./routes'),
    protocol = require('./protocol.js'),
    User = require('./models/user.js');

// establish mongodb connection
mongoose.connection.on('error', log.error.bind(log, 'connection error:'));
mongoose.connect('mongodb://' + config.mongodb.host + ':' + config.mongodb.port + '/test');

// create app, http server and websocket server instances
var app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

var MongoStore = require('connect-mongo')(express);
var sessionStore = new MongoStore({
    //mongoose_connection: mongoose.connections[0]
    db: 'test'
});

// all environments
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session({
    key: config.session.name,
    secret: config.session.secret,
    store: sessionStore
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(require('less-middleware')({
    src: path.join(__dirname, 'public'),
    compress: true
}));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

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

// passport config
var Account = require('./models/user');
passport.use(new LocalStrategy(Account.authenticate()));
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

// websocket stuff below
io.configure(function() {
    io.set('authorization', function(data, callback) {
        if (!data.headers.cookie) {
            return callback('Session cookie required.', false);
        }

        var cookies = cookie.parse(data.headers.cookie),
            signedCookie = cookies[config.session.name],
            sid = connect.utils.parseSignedCookie(signedCookie,
                      config.session.secret);

        if (signedCookie == sid) {
            return callback('Invalid session cookie.', false);
        }

        sessionStore.get(sid, function(err, session) {
            if (err || !session) {
                return callback('Unable to retrieve session.', false);
            } else {
                data.session = session;
                data.sessionId = sid;

                /*
                if (!data.session.user_id) {
                    return callback('You need to be logged in.', false);
                }
                */

                //User.findById(

                data.user = new User({
                    alias: 'testUser'
                });

                return callback(null, true);
            }
        });
    });
});

io.configure('production', function() {
    io.enable('browser client minification');
    io.enable('browser client etag');
    io.enable('browser client gzip');
    io.set('log level', 1);
});

protocol(io);

// start to listen for incoming connections
server.listen(config.port, function() {
    log.info('Express server listening on port %d', config.port);
});

<commit_msg>Simplify passport usage<commit_after>var express = require('express'),
    path = require('path'),
    http = require('http'),
    mongoose = require('mongoose'),
    cookie = require('cookie'),
    connect = require('connect'),
	passport = require('passport');

var config = require('./config.js'),
    log = require('./log.js'),
    routes = require('./routes'),
    protocol = require('./protocol.js'),
    User = require('./models/user.js');

// establish mongodb connection
mongoose.connection.on('error', log.error.bind(log, 'connection error:'));
mongoose.connect('mongodb://' + config.mongodb.host + ':' + config.mongodb.port + '/test');

// create app, http server and websocket server instances
var app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server);

var MongoStore = require('connect-mongo')(express);
var sessionStore = new MongoStore({
    //mongoose_connection: mongoose.connections[0]
    db: 'test'
});

// all environments
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session({
    key: config.session.name,
    secret: config.session.secret,
    store: sessionStore
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(require('less-middleware')({
    src: path.join(__dirname, 'public'),
    compress: true
}));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

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

// passport config
var Account = require('./models/user');
passport.use(Account.createStrategy());
passport.serializeUser(Account.serializeUser());
passport.deserializeUser(Account.deserializeUser());

// websocket stuff below
io.configure(function() {
    io.set('authorization', function(data, callback) {
        if (!data.headers.cookie) {
            return callback('Session cookie required.', false);
        }

        var cookies = cookie.parse(data.headers.cookie),
            signedCookie = cookies[config.session.name],
            sid = connect.utils.parseSignedCookie(signedCookie,
                      config.session.secret);

        if (signedCookie == sid) {
            return callback('Invalid session cookie.', false);
        }

        sessionStore.get(sid, function(err, session) {
            if (err || !session) {
                return callback('Unable to retrieve session.', false);
            } else {
                data.session = session;
                data.sessionId = sid;

                /*
                if (!data.session.user_id) {
                    return callback('You need to be logged in.', false);
                }
                */

                //User.findById(

                data.user = new User({
                    alias: 'testUser'
                });

                return callback(null, true);
            }
        });
    });
});

io.configure('production', function() {
    io.enable('browser client minification');
    io.enable('browser client etag');
    io.enable('browser client gzip');
    io.set('log level', 1);
});

protocol(io);

// start to listen for incoming connections
server.listen(config.port, function() {
    log.info('Express server listening on port %d', config.port);
});

<|endoftext|>