<commit_before>// # Configuración de rutas
// Configuración de las rutas de la API de Polleitor
'use strict';
//Desarrollado por la Oficina de Software Libre bajo licencia MIT

// ## Dependencias
// * **jwt:** JSON Web Tokens, para generar los tokens de sesión
// * **Useragent:** Lee el valor _useragent_ para identificar usuarios
// * **Express:** Framework web
var jwt = require('jsonwebtoken');
var useragent = require('useragent');
var express = require('express');

// ### Dependencias locales
// * [**Config**](./config.html): Configuración general de Polleitor
var config = require('./config');

// ## Rutas
module.exports = function(app, handler) {
    // Middleware para crear/verificar el token
    app.use(function(req, res, next) {
        //Obtener el token
        var ses = req.session;

        //Verificar el token, creándolo si no existe
        if (ses.token) {
            jwt.verify(ses.token, config.secret, function(err, value) {
                if (err) {
                    return res.json(403, {
                        success: false,
                        message: 'Failed to verify the token. Unauthorized access.'
                    });
                } else {
                    next();
                }
            });
        } else {
            var agent = useragent.parse(req.headers['user-agent']);
            var dev_id = (agent.toAgent() +
                '_' + agent.os.toString() + '_' +
                agent.device.toString()).replace(/\s/g, '');
            var value = 'ID:' + req.params.id + '_' + dev_id;

            //Crea el token
            var token = jwt.sign(value, config.secret);
            ses.token = token;

            next();
        }
    });
    // Middleware para comprobar que el poll dado existe
    app.use('/:poll', function(req, res, next) {
        var poll = req.params.poll;

        if (!handler.checkPoll(poll)) {
            res.status(404).json({
                error: 'Poll ' + poll + ' not found.'
            });
        } else {
            next();
        }
    });

    // GET `/:poll`: Devuelve las preguntas y posibles respuestas del poll
    app.get('/:poll', function(req, res) {
        var questions = handler.getPoll(req.params.poll);

        if (!questions) {
            return res.status(404).json({
                status: 404,
                error: 'Not poll found.',
                poll: req.params.poll
            });
        } else {
            res.json(questions);
        }
    });

    //GET `/:poll/resultados` Muestra el poll y los resultados
    app.get('/:poll/resultados', function(req, res) {
        var answers = handler.getAnswersPoll(req.params.poll);

        if (!answers) {
            return res.status(404).json({
                error: 'Poll ' + req.params.poll + ' not found.'
            });
        } else {
            return res.json(answers);
        }
    });

    /*app.get('/:poll/p/:f', function(req, res) {
            var token = req.session.token;

            var agent = useragent.parse(req.headers['user-agent']);
            var dev_id = (agent.toAgent() +
                '_' + agent.os.toString() + '_' +
                agent.device.toString()).replace(/\s/g, '');
            var value = 'ID:' + req.params.id + '_' + dev_id;

            var db_collection = req.db_collection; // Código repetido
            db_collection.insert({
                client: {
                    dev_id: dev_id,
                    token: token
                }
            });
            db.saveDatabase();

            console.log(req.params);
            var poll_to_send = {};
            poll_to_send[req.params.id] = req.poll;
            res.header('Content-Type', 'application/javascript');
            res.send(req.params.f + '( ' + JSON.stringify(poll_to_send) + ')');
        });*/

    /*app.put('/:poll/:pregunta/:respuesta', function(req, res) {
        var token = req.session.token;

        var r = handler.answerQuestion(req.params.poll, req.params.pregunta, req.params.respuesta, token);

        if (r) {
            return res.json({
                status: 'OK',
                ok: true,
                poll: req.params.poll,
                pregunta: req.params.pregunta
            });
        } else {
            return res.json({
                status: 'FAIL',
                ok: false,
                poll: req.params.poll,
                pregunta: req.params.pregunta
            });
        }
    });*/

    // PUT `/:poll` responde al poll
    app.put('/:poll', function(req, res) {
        var token = req.session.token;
        var answers = req.body.answers;
        var poll = req.params.poll;

        var correct = 0;
        var incorrect = 0;

        for (var i = 0; i < answers.length; i++) {
            var r = handler.answerQuestion(poll, answers[i].id, answers[i].answer, token);
            if (r) correct++;
            else incorrect++;
        }

        return res.status(200).json({
            poll: req.params.poll,
            updates: correct,
            failedUpdates: incorrect
        });
    });
};

// **Exports:** function(app,handler)
// Función para añadir las rutas a la app express dada junto con el manejador de base de datos _handler_
<commit_msg>Log cancamusero de respuestas<commit_after>// # Configuración de rutas
// Configuración de las rutas de la API de Polleitor
'use strict';
//Desarrollado por la Oficina de Software Libre bajo licencia MIT

// ## Dependencias
// * **jwt:** JSON Web Tokens, para generar los tokens de sesión
// * **Useragent:** Lee el valor _useragent_ para identificar usuarios
// * **Express:** Framework web
var jwt = require('jsonwebtoken');
var useragent = require('useragent');
var express = require('express');

// ### Dependencias locales
// * [**Config**](./config.html): Configuración general de Polleitor
var config = require('./config');

// ## Rutas
module.exports = function(app, handler) {
    // Middleware para crear/verificar el token
    app.use(function(req, res, next) {
        //Obtener el token
        var ses = req.session;

        //Verificar el token, creándolo si no existe
        if (ses.token) {
            jwt.verify(ses.token, config.secret, function(err, value) {
                if (err) {
                    return res.json(403, {
                        success: false,
                        message: 'Failed to verify the token. Unauthorized access.'
                    });
                } else {
                    next();
                }
            });
        } else {
            var agent = useragent.parse(req.headers['user-agent']);
            var dev_id = (agent.toAgent() +
                '_' + agent.os.toString() + '_' +
                agent.device.toString()).replace(/\s/g, '');
            var value = 'ID:' + req.params.id + '_' + dev_id;

            //Crea el token
            var token = jwt.sign(value, config.secret);
            ses.token = token;

            next();
        }
    });
    // Middleware para comprobar que el poll dado existe
    app.use('/:poll', function(req, res, next) {
        var poll = req.params.poll;

        if (!handler.checkPoll(poll)) {
            res.status(404).json({
                error: 'Poll ' + poll + ' not found.'
            });
        } else {
            next();
        }
    });

    // GET `/:poll`: Devuelve las preguntas y posibles respuestas del poll
    app.get('/:poll', function(req, res) {
        var questions = handler.getPoll(req.params.poll);

        if (!questions) {
            return res.status(404).json({
                status: 404,
                error: 'Not poll found.',
                poll: req.params.poll
            });
        } else {
            res.json(questions);
        }
    });

    //GET `/:poll/resultados` Muestra el poll y los resultados
    app.get('/:poll/resultados', function(req, res) {
        var answers = handler.getAnswersPoll(req.params.poll);

        if (!answers) {
            return res.status(404).json({
                error: 'Poll ' + req.params.poll + ' not found.'
            });
        } else {
            return res.json(answers);
        }
    });

    /*app.get('/:poll/p/:f', function(req, res) {
            var token = req.session.token;

            var agent = useragent.parse(req.headers['user-agent']);
            var dev_id = (agent.toAgent() +
                '_' + agent.os.toString() + '_' +
                agent.device.toString()).replace(/\s/g, '');
            var value = 'ID:' + req.params.id + '_' + dev_id;

            var db_collection = req.db_collection; // Código repetido
            db_collection.insert({
                client: {
                    dev_id: dev_id,
                    token: token
                }
            });
            db.saveDatabase();

            console.log(req.params);
            var poll_to_send = {};
            poll_to_send[req.params.id] = req.poll;
            res.header('Content-Type', 'application/javascript');
            res.send(req.params.f + '( ' + JSON.stringify(poll_to_send) + ')');
        });*/

    /*app.put('/:poll/:pregunta/:respuesta', function(req, res) {
        var token = req.session.token;

        var r = handler.answerQuestion(req.params.poll, req.params.pregunta, req.params.respuesta, token);

        if (r) {
            return res.json({
                status: 'OK',
                ok: true,
                poll: req.params.poll,
                pregunta: req.params.pregunta
            });
        } else {
            return res.json({
                status: 'FAIL',
                ok: false,
                poll: req.params.poll,
                pregunta: req.params.pregunta
            });
        }
    });*/

    // PUT `/:poll` responde al poll
    app.put('/:poll', function(req, res) {
        var token = req.session.token;
        var answers = req.body.answers;
        var poll = req.params.poll;

        var correct = 0;
        var incorrect = 0;
        for (var i = 0; i < answers.length; i++) {
            var r = handler.answerQuestion(poll, answers[i].id, answers[i].answer, token);
            if (r) correct++;
            else incorrect++;
            console.log(JSON.stringify({
                poll: req.params.poll,
                id: answers[i].id,
                answer: answers[i].answer,
                updated: correct,
                failed: incorrect
            }));
        }

        return res.status(200).json({
            poll: req.params.poll,
            updates: correct,
            failedUpdates: incorrect
        });
    });
};

// **Exports:** function(app,handler)
// Función para añadir las rutas a la app express dada junto con el manejador de base de datos _handler_
<|endoftext|>


<commit_before>/* eslint flowtype-errors/show-errors: 0 */
import React from 'react';
import { Switch, Route } from 'react-router';
import App from './containers/App';
import HomePage from './containers/HomePage';
import CounterPage from './containers/CounterPage';

export default () => (
  <App>

Sup

    <Switch>
      <Route path="/counter" component={CounterPage} />
      <Route path="/" component={HomePage} />
    </Switch>
  </App>
);
<commit_msg>Does it?<commit_after>/* eslint flowtype-errors/show-errors: 0 */
import React from "react";
import { Switch, Route } from "react-router";
import App from "./containers/App";
import HomePage from "./containers/HomePage";
import CounterPage from "./containers/CounterPage";

export default () =>
  <App>
    <Switch>
      <Route path="/counter" component={CounterPage} />
      <Route path="/" component={HomePage} />
    </Switch>
  </App>;
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import {Router, Route, browserHistory} from 'react-router'

import App from './components/App'
import Home from './components/Home'
import About from './components/About'
import NotFound from './components/NotFound'
import Edit from './components/Edit'
import TranslatorPage from './components/TranslatorPage'

import NewTerm from './components/admin/NewTerm'
import EditUser from './components/admin/EditUser'
import EditUserPassword from './components/admin/EditUserPassword'

function unauthorizedAccess (replace) {
  replace('/not_authorized')
  browserHistory.replace('/not_authorized')
}

function unpermittedAccess (replace) {
  replace('/not_permitted')
  browserHistory.replace('/not_permitted')
}

function checkAuth (nextState, replace, callback, store, role) {
  const auth = store.getState().auth
  if(auth.loggedIn && (!role || (auth.userInfo.data && auth.userInfo.data.role === role))) {
    callback()
    return
  }
  if(auth.userInfo.promise) {
    auth.userInfo.promise.then(response => {
      if (!auth.loggedIn) {
        unauthorizedAccess(replace)
      }
      if (role && (!response || !response.result || response.result.role !== role)) {
        unpermittedAccess(replace)
      }
      callback()
    })
  }
  else {
    unauthorizedAccess(replace)
  }
}

const getRoutes = (store) => ({
  component: App,
  childRoutes: [
    { path: '/', exactly: true, component: Home },
    { path: '/about', exactly: true, component: About },
    { path: '/edit', exactly: true, component: Edit },
    {
      path: '/newTerm',
      exactly: true,
      component: NewTerm,
      onEnter: (...args) => checkAuth(...args, store, 'admin')
    },
    { path: '/translator/:id', exactly: true, component: TranslatorPage },
    {
      path: '/translator/:id/edit',
      exactly: true,
      component: EditUser,
      onEnter: (...args) => checkAuth(...args, store, 'admin')
    },
    {
      path: '/translator/:id/edit/password',
      exactly: true,
      component: EditUserPassword,
      onEnter: (...args) => checkAuth(...args, store, 'admin')
    },
    { path: '/not_authorized', exactly: true, component: NotFound },
    { path: '/not_permitted', exactly: true, component: NotFound },
    { path: '*', component: NotFound }
  ]
});

export default getRoutes
<commit_msg>checkAuth fix<commit_after>import React, {Component} from 'react'
import {Router, Route, browserHistory} from 'react-router'

import App from './components/App'
import Home from './components/Home'
import About from './components/About'
import NotFound from './components/NotFound'
import Edit from './components/Edit'
import TranslatorPage from './components/TranslatorPage'

import NewTerm from './components/admin/NewTerm'
import EditUser from './components/admin/EditUser'
import EditUserPassword from './components/admin/EditUserPassword'

function unauthorizedAccess (replace) {
  replace('/not_authorized')
  browserHistory.replace('/not_authorized')
}

function unpermittedAccess (replace) {
  replace('/not_permitted')
  browserHistory.replace('/not_permitted')
}

function checkAuth (nextState, replace, callback, store, role) {
  let auth = store.getState().auth
  if(auth.loggedIn && (!role || (auth.userInfo.data && auth.userInfo.data.role === role))) {
    callback()
    return
  }
  if(auth.userInfo.promise) {
    auth.userInfo.promise.then(() => {
      auth = store.getState().auth
      const userInfo = auth.userInfo.data
      if (!auth.loggedIn) {
        unauthorizedAccess(replace)
      }
      if (role && (!userInfo || userInfo.role !== role)) {
        unpermittedAccess(replace)
      }
      callback()
    })
  }
  else {
    unauthorizedAccess(replace)
  }
}

const getRoutes = (store) => ({
  component: App,
  childRoutes: [
    { path: '/', exactly: true, component: Home },
    { path: '/about', exactly: true, component: About },
    { path: '/edit', exactly: true, component: Edit },
    {
      path: '/newTerm',
      exactly: true,
      component: NewTerm,
      onEnter: (...args) => checkAuth(...args, store, 'admin')
    },
    { path: '/translator/:id', exactly: true, component: TranslatorPage },
    {
      path: '/translator/:id/edit',
      exactly: true,
      component: EditUser,
      onEnter: (...args) => checkAuth(...args, store, 'admin')
    },
    {
      path: '/translator/:id/edit/password',
      exactly: true,
      component: EditUserPassword,
      onEnter: (...args) => checkAuth(...args, store, 'admin')
    },
    { path: '/not_authorized', exactly: true, component: NotFound },
    { path: '/not_permitted', exactly: true, component: NotFound },
    { path: '*', component: NotFound }
  ]
});

export default getRoutes
<|endoftext|>


<commit_before>// app/routes.js
module.exports = function(app, passport) {

	// =====================================
	// HOME PAGE (with login links) ========
	// =====================================
	app.get('/', function(req, res) {
		res.render('index.ejs'); // load the index.ejs file
	});

	// =====================================
	// LOGIN ===============================
	// =====================================
	// show the login form
	app.get('/login', function(req, res) {

		// render the page and pass in any flash data if it exists
		res.render('login.ejs', { message: req.flash('loginMessage') });
	});

	// process the login form
	app.post('/login', passport.authenticate('local-login', {
		successRedirect : '/profile', // redirect to the secure profile section
		failureRedirect : '/login', // redirect back to the signup page if there is an error
		failureFlash : true // allow flash messages
	}));

	// =====================================
	// SIGNUP ==============================
	// =====================================
	// show the signup form
	app.get('/signup', function(req, res) {

		// render the page and pass in any flash data if it exists
		res.render('signup.ejs', { message: req.flash('loginMessage') });
	});

	// process the signup form
	app.post('/signup', passport.authenticate('local-signup', {
		successRedirect : '/profile', // redirect to the secure profile section
		failureRedirect : '/signup', // redirect back to the signup page if there is an error
		failureFlash : true // allow flash messages
	}));

	// =====================================
	// PROFILE SECTION =========================
	// =====================================
	// we will want this protected so you have to be logged in to visit
	// we will use route middleware to verify this (the isLoggedIn function)
	app.get('/profile', isLoggedIn, function(req, res) {
		res.render('profile.ejs', {
			user : req.user // get the user out of session and pass to template
		});
	});

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

// route middleware to make sure
function isLoggedIn(req, res, next) {

	// if user is authenticated in the session, carry on
	if (req.isAuthenticated())
		return next();

	// if they aren't redirect them to the home page
	res.redirect('/');
}<commit_msg>Update routes.js<commit_after>// app/routes.js
module.exports = function(app, passport) {

	// =====================================
	// HOME PAGE (with login links) ========
	// =====================================
	app.get('/', function(req, res) {
		res.render('index.ejs'); // load the index.ejs file
	});

	// =====================================
	// LOGIN ===============================
	// =====================================
	// show the login form
	app.get('/login', function(req, res) {

		// render the page and pass in any flash data if it exists
		res.render('login.ejs', { message: req.flash('loginMessage') });
	});

	// process the login form
	app.post('/login', passport.authenticate('local-login', {
		successRedirect : '/profile', // redirect to the secure profile section
		failureRedirect : '/login', // redirect back to the signup page if there is an error
		failureFlash : true // allow flash messages
	}));

	// =====================================
	// SIGNUP ==============================
	// =====================================
	// show the signup form
	app.get('/signup', function(req, res) {

		// render the page and pass in any flash data if it exists
		res.render('signup.ejs', { message: req.flash('signupMessage') });
	});

	// process the signup form
	app.post('/signup', passport.authenticate('local-signup', {
		successRedirect : '/profile', // redirect to the secure profile section
		failureRedirect : '/signup', // redirect back to the signup page if there is an error
		failureFlash : true // allow flash messages
	}));

	// =====================================
	// PROFILE SECTION =========================
	// =====================================
	// we will want this protected so you have to be logged in to visit
	// we will use route middleware to verify this (the isLoggedIn function)
	app.get('/profile', isLoggedIn, function(req, res) {
		res.render('profile.ejs', {
			user : req.user // get the user out of session and pass to template
		});
	});

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

// route middleware to make sure
function isLoggedIn(req, res, next) {

	// if user is authenticated in the session, carry on
	if (req.isAuthenticated())
		return next();

	// if they aren't redirect them to the home page
	res.redirect('/');
}
<|endoftext|>


<commit_before>let isLoggedIn = require('./middlewares/isLoggedIn');
let util = require('util');
let Twitter = require('twitter');
let then = require('express-then');

let scope = 'email';
let posts = require('../data/posts');

let networks = {
    twitter: {
        network: {
            icon: 'twitter',
            name: 'Twitter',
            class: 'btn-info'
        }
    }
};

module.exports = (app) => {
    let passport = app.passport;
    let twitterConfig = app.config.auth.twitter;

    app.get('/', (req, res) => res.render('index.ejs'));

    app.get('/profile', isLoggedIn, (req, res) => {
        res.render('profile.ejs', {
            user: req.user,
            message: req.flash('error')
        })
    });

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

    app.get('/login', (req, res) => {
        res.render('login.ejs', {message: req.flash('error')})
    });

    app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    }));

    app.get('/signup', (req, res) => {
        res.render('signup.ejs', {message: req.flash('error') })
    });

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/profile',
        failureRedirect: '/signup',
        failureFlash: true
    }));

    app.get('/auth/facebook', passport.authenticate('facebook', {scope}));

    app.get('/auth/facebook/callback', passport.authenticate('facebook', {
        successRedirect: '/profile',
        failureRedirect: '/profile',
        failureFlash: true
    }));

    app.get('/auth/twitter', passport.authenticate('twitter', {scope}));

    app.get('/auth/twitter/callback', passport.authenticate('twitter', {
        successRedirect: '/profile',
        failureRedirect: '/profile',
        failureFlash: true
    }));

    app.get('/timeline', isLoggedIn, then(async (req, res) => {
        var twitterClient = new Twitter({
            consumer_key: twitterConfig.consumerKey,
            consumer_secret: twitterConfig.consumerSecret,
            access_token_key: req.user.twitter.token,
            access_token_secret: req.user.twitter.secret
        });

        let [tweets] = await twitterClient.promise.get('/statuses/home_timeline.json', {count: 20});

        posts = tweets.map(tweet => {
            return {
                id: tweet.id,
                image: tweet.user.profile_image_url,
                text: tweet.text,
                name: tweet.user.name,
                username: "@" + tweet.user.screen_name,
                liked: tweet.favorited,
                network: networks.twitter.network
            }
        });

        res.render('timeline.ejs', {
            message: req.flash('error'),
            posts: posts

        })
    }));

    app.get('/compose', isLoggedIn, (req, res) => {
        res.render('compose.ejs', {
            message: req.flash('error')
        })
    });

    app.post('/compose', isLoggedIn, then(async (req, res) => {
        let text = req.body.reply;

        if (text.length > 140){
            return req.flash('error', 'Status is over 140 characters')
        }
        if (!text){
            req.flash('error', 'Status cannot be empty')
        }

        var twitterClient = new Twitter({
            consumer_key: twitterConfig.consumerKey,
            consumer_secret: twitterConfig.consumerSecret,
            access_token_key: req.user.twitter.token,
            access_token_secret: req.user.twitter.secret
        });

        await twitterClient.promise.post('/statuses/update', {status : text});

        res.redirect('/timeline');
    }));
};
<commit_msg>added like/unlike<commit_after>let isLoggedIn = require('./middlewares/isLoggedIn');
let util = require('util');
let Twitter = require('twitter');
let then = require('express-then');

let scope = 'email';
let posts = require('../data/posts');

let networks = {
    twitter: {
        network: {
            icon: 'twitter',
            name: 'Twitter',
            class: 'btn-info'
        }
    }
};

module.exports = (app) => {
    let passport = app.passport;
    let twitterConfig = app.config.auth.twitter;

    app.get('/', (req, res) => res.render('index.ejs'));

    app.get('/profile', isLoggedIn, (req, res) => {
        res.render('profile.ejs', {
            user: req.user,
            message: req.flash('error')
        })
    });

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

    app.get('/login', (req, res) => {
        res.render('login.ejs', {message: req.flash('error')})
    });

    app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    }));

    app.get('/signup', (req, res) => {
        res.render('signup.ejs', {message: req.flash('error') })
    });

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/profile',
        failureRedirect: '/signup',
        failureFlash: true
    }));

    app.get('/auth/facebook', passport.authenticate('facebook', {scope}));

    app.get('/auth/facebook/callback', passport.authenticate('facebook', {
        successRedirect: '/profile',
        failureRedirect: '/profile',
        failureFlash: true
    }));

    app.get('/auth/twitter', passport.authenticate('twitter', {scope}));

    app.get('/auth/twitter/callback', passport.authenticate('twitter', {
        successRedirect: '/profile',
        failureRedirect: '/profile',
        failureFlash: true
    }));

    app.get('/timeline', isLoggedIn, then(async (req, res) => {
        var twitterClient = new Twitter({
            consumer_key: twitterConfig.consumerKey,
            consumer_secret: twitterConfig.consumerSecret,
            access_token_key: req.user.twitter.token,
            access_token_secret: req.user.twitter.secret
        });

        let [tweets] = await twitterClient.promise.get('/statuses/home_timeline.json', {count: 20});

        posts = tweets.map(tweet => {
            return {
                id: tweet.id_str,
                image: tweet.user.profile_image_url,
                text: tweet.text,
                name: tweet.user.name,
                username: "@" + tweet.user.screen_name,
                liked: tweet.favorited,
                network: networks.twitter.network
            }
        });

        res.render('timeline.ejs', {
            message: req.flash('error'),
            posts: posts

        })
    }));

    app.get('/compose', isLoggedIn, (req, res) => {
        res.render('compose.ejs', {
            message: req.flash('error')
        })
    });

    app.post('/compose', isLoggedIn, then(async (req, res) => {
        let text = req.body.reply;

        if (text.length > 140){
            return req.flash('error', 'Status is over 140 characters')
        }
        if (!text){
            req.flash('error', 'Status cannot be empty')
        }

        var twitterClient = new Twitter({
            consumer_key: twitterConfig.consumerKey,
            consumer_secret: twitterConfig.consumerSecret,
            access_token_key: req.user.twitter.token,
            access_token_secret: req.user.twitter.secret
        });

        await twitterClient.promise.post('/statuses/update', {status: text});

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

    app.post('/like/:id', isLoggedIn, then(async(req, res) =>{
        let twitterClient = new Twitter({
            consumer_key: twitterConfig.consumerKey,
            consumer_secret: twitterConfig.consumerSecret,
            access_token_key: req.user.twitter.token,
            access_token_secret: req.user.twitter.secret
        });

        let id = req.params.id;
        await twitterClient.promise.post('/favorites/create', {id});
        res.end()
    }));

    app.post('/unlike/:id', isLoggedIn, then(async(req, res) =>{
        let twitterClient = new Twitter({
            consumer_key: twitterConfig.consumerKey,
            consumer_secret: twitterConfig.consumerSecret,
            access_token_key: req.user.twitter.token,
            access_token_secret: req.user.twitter.secret
        });

        let id = req.params.id;
        await twitterClient.promise.post('/favorites/destroy', {id});
        res.end()
    }))

};
<|endoftext|>


<commit_before>define(['app', 'jquery', 'lodash', 'text!./redirect-dialog.html','providers/extended-route', 'ngRoute', 'authentication', 'ngDialog','ngCookies'], function(app, $, _,redirectDialog) { 'use strict';

    var locationPath = window.location.pathname.toLowerCase().split('?')[0];

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

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

        // /decisions/cop/*
        if(/^\/decisions\/cop($|\/.*)/.test(locationPath))
            registerRoutes_CopDecisions($routeProvider);

        // /management/decisions/*
        if(/^\/management\/decisions($|\/.*)/.test(locationPath))
            registerRoutes_ManagementDecisions($routeProvider);

        // /insession/*
        if(/^\/insession($|\/.*)/.test(locationPath))
            registerRoutes_insession($routeProvider);

        // /conferences/**
        if(/^\/conferences($|\/.*)/.test(locationPath))
            registerRoutes_conferences($routeProvider);

        // /aichi-targets/*
        if(/^\/aichi-targets($|\/.*)/.test(locationPath))
            registerRoutes_aichiTargets($routeProvider);

        // /kronos/*
        if(/^\/kronos\/list-of-participants($|\/.*)/.test(locationPath))
            registerRoutes_kronos($routeProvider);

        //bbi/*
        if(/^\/biobridge($|\/.*)/.test(locationPath))
            registerRoutes_bbi($routeProvider);

        $routeProvider.when('/403', { templateUrl: '/app/views/403.html' });
        $routeProvider.when('/404', { templateUrl: '/app/views/404.html' }).otherwise({redirectTo: '/404'});
    }
  ]);

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_CopDecisions(routeProvider) {

      $('base').attr('href', '/decisions/cop/'); // allow full page reload outside of  /decisions/*

      //routeProvider.when('/cop', { templateUrl: 'views/decisions/search.html', resolveController: true });
      routeProvider.when('/:session',                      { templateUrl: 'views/decisions/list.html', resolveController: true });
      routeProvider.when('/:session/:decision',            { templateUrl: 'views/decisions/view.html', resolveController: true });
      routeProvider.when('/:session/:decision/:paragraph', { templateUrl: 'views/decisions/paragraph.html', resolveController: true });
      //routeProvider.when('/', { templateUrl: 'views/decisions/search.html', resolveController: true });
  }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_ManagementDecisions(routeProvider) {

      $("base").attr('href', '/management/decisions/'); // allow full page reload outside of  /decisions/*

      routeProvider.when('/',                 { templateUrl: 'views/decisions/index.html', resolveController: true, resolve : { user : securize(["Administrator","DecisionTrackingTool"]) } } );
      routeProvider.when('/:meeting/:number', { templateUrl: 'views/decisions/edit.html',  resolveController: true, resolve : { user : securize(["Administrator","DecisionTrackingTool"]) } } );
  }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_insession(routeProvider) {

      $("base").attr('href', '/insession/'); // allow full page reload outside of  /insession/*

      routeProvider
      .when('/',           { template : '

', resolve: { r: function() { window.location='/conferences/2016'; } } })
      .when('/management', { templateUrl : 'views/meetings/documents/in-session/management.html', resolveController : true, resolve : { user : securize(["Administrator","EditorialService"]) } } )
      .when('/:meeting',   { templateUrl : 'views/meetings/documents/in-session/meeting-id.html', resolveController : true, progress : { stop : false } } );
    }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_conferences(routeProvider) {

      $("base").attr('href', '/conferences/'); // allow full page reload outside of  /insession/*

      routeProvider
      .when('/',                        { redirectTo: '/2016' })
      .when('/2016',                    { templateUrl : 'views/meetings/cop13/index.html'})
      .when('/2016/cop-13-hls/documents',{templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'COP13-HLS' }), meeting: resolveLiteral('COP13-HLS') }, reloadOnSearch:false })
      .when('/2016/cop-13/documents',   { templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'COP-13'    }), meeting: resolveLiteral('COP-13')    }, reloadOnSearch:false })
      .when('/2016/cp-mop-8/documents', { templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'MOP-08'    }), meeting: resolveLiteral('MOP-08')    }, reloadOnSearch:false })
      .when('/2016/np-mop-2/documents', { templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'NP-MOP-02' }), meeting: resolveLiteral('NP-MOP-02') }, reloadOnSearch:false })
      .when('/2016/schedules',          { redirectTo: '/2016/cop-13/documents' })

      .when('/management/import-translations',     { templateUrl : 'views/meetings/documents/management/translations.html', resolveController : true, resolve : { user : securize(["Administrator","EditorialService"]) } })
      .when('/management/:meeting/documents/:id',  { templateUrl : 'views/meetings/documents/management/document-id.html',  resolveController : true, resolve : { user : securize(["Administrator","EditorialService"]) }, reloadOnSearch:false });
    }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_aichiTargets(routeProvider) {

      $("base").attr('href', '/aichi-targets/'); // allow full page reload outside of  /insession/*

      routeProvider
        .when('/',                  { templateUrl: 'views/aichi-targets/index.html',    controllerAs: 'indexCtrl',   resolveController: true })
        .when('/target/:targetId',  { templateUrl: 'views/aichi-targets/index-id.html', controllerAs: 'indexIdCtrl', resolveController: true });
  }

  //============================================================
  //
  //s
  //============================================================
  function registerRoutes_kronos(routeProvider) {

      $("base").attr('href', '/kronos/list-of-participants/'); // allow full page reload outside of  /insession/*

      routeProvider
        .when('/',                  { templateUrl: 'views/meetings/participants/index.html',    controllerAs: 'indexCtrl',   resolveController: true, resolve: { user : securize(["Administrator","KronosAdministrator", "ScbdStaff"]) }  });
  }

    //============================================================
    //
    //
    //============================================================
    function resolveLiteral(value) {
        return function() { return value; };
    }

    //============================================================
    //
    //
    //============================================================
    function injectRouteParams(params) {
        return ['$route', function($route) {
            return _.defaults($route.current.params, params);
        }];
    }

    //============================================================
    //
    //
    //============================================================
    function registerRoutes_bbi(routeProvider) {

        $("base").attr('href', '/biobridge/'); // allow full page reload outside of  /insession/*

        routeProvider
          .when('/',                       { templateUrl: 'views/bbi/index-bbi.html',        controllerAs: 'indexCtrl',   resolveController: true })
          .when('/platform/submit/:schema',         { templateUrl: 'views/bbi/management/record-list.html',  controllerAs: 'submitCtrl',  resolveController: true,resolve : { user : securize(['User']) } })
          .when('/platform/submit/:schema/:id',     { templateUrl: 'views/bbi/management/edit.html',         controllerAs: 'editCtrl',    resolveController: true ,resolve : { user : securize(['User']) }})
          .when('/platform/submit/:schema/:id/view',{ templateUrl: 'views/bbi/management/view.html',    controllerAs: 'viewCtrl',    resolveController: true,resolve : { user : securize(['Everyone']) } })
          .when('/platform/dashboard'              ,{ templateUrl: 'views/bbi/management/index.html',    controllerAs: 'dashCtrl',    resolveController: true ,resolve : { user : securize(['User']) }})
          .when('/platform/search',                { templateUrl: 'views/bbi/management/search.html',  controllerAs: 'searchCtrl',   resolveController: true, reloadOnSearch : false})
          .when('/platform/tools',                  { templateUrl: 'views/bbi/management/tools.html',  controllerAs: 'toolsCtrl',  resolveController: true, resolve : { user : securize(['User']) }})
          .when('/platform/about',                  { templateUrl: 'views/bbi/management/about/index.html',  controllerAs: 'pAboutCtrl',  resolveController: true, resolve : { user : securize(['User']) }})
          .when('/platform/dashboard'              ,{ templateUrl: 'views/bbi/management/index.html',    controllerAs: 'dashCtrl',    resolveController: true ,resolve : { user : securize(['User']) }})
          .when('/platform/:schema',                       { templateUrl: 'views/bbi/management/search.html',  controllerAs: 'searchCtrl',   resolveController: true, reloadOnSearch : false})

          .when('/about',                  { templateUrl: 'views/bbi/about/index.html',  controllerAs: 'initCtrl',  resolveController: true})
          .when('/about/framework',        { templateUrl: 'views/bbi/about/framework.html',  controllerAs: 'frameworkCtrl',  resolveController: true})
          .when('/about/plan',             { templateUrl: 'views/bbi/about/plan.html',  controllerAs: 'planCtrl',  resolveController: true})
          .when('/about/partners',         { templateUrl: 'views/bbi/about/partners.html',  controllerAs: 'partnersCtrl',  resolveController: true})

          .when('/participation',                { templateUrl: 'views/bbi/participation/index.html',  controllerAs: 'participationCtrl',  resolveController: true})
          .when('/participation/request',        { templateUrl: 'views/bbi/participation/request.html',  controllerAs: 'requestCtrl',  resolveController: true})
          .when('/participation/provide',        { templateUrl: 'views/bbi/participation/provide.html',  controllerAs: 'provideCtrl',  resolveController: true})
          .when('/participation/opportunity',    { templateUrl: 'views/bbi/participation/opportunity.html',  controllerAs: 'opportunityCtrl',  resolveController: true})

          .when('/projects',                { templateUrl: 'views/bbi/pilot-projects/index.html',  controllerAs: 'pilotCtrl',  resolveController: true})
          .when('/projects/selected',       { templateUrl: 'views/bbi/pilot-projects/selected.html',  controllerAs: 'selectedCtrl',  resolveController: true})

          // .when('/proposals',                     { templateUrl: 'views/bbi/search.html',  controllerAs: 'searchCtrl',  resolveController: true})

          .when('/resources',                     { templateUrl: 'views/bbi/resources.html',  controllerAs: 'resoCtrl',  resolveController: true})
          .when('/faq',                           { templateUrl: 'views/bbi/faq.html',  controllerAs: 'faqCtrl',  resolveController: true})
          .when('/contact',                       { templateUrl: 'views/bbi/contact.html',  controllerAs: 'contCtrl',  resolveController: true})

          .when('/comms',                         { templateUrl: 'views/bbi/comms/index.html'    ,  controllerAs: 'commsCtrl',  resolveController: true})
          .when('/comms/panel',                   { templateUrl: 'views/bbi/comms/panel.html',  controllerAs: 'panelCtrl',   resolveController: true})
          .when('/search',                        { templateUrl: 'views/bbi/search.html',  controllerAs: 'searchCtrl',   resolveController: true, reloadOnSearch : false})
          .when('/platform',                        { templateUrl: 'views/bbi/platform.html',  controllerAs: 'pltfCtrl',   resolveController: true, reloadOnSearch : false})

          .when('/forums/bbi/:threadId',           { templateUrl: 'views/bbi/forums/post-list-view.html',  resolveController: true,resolve : { user : securize(['User'])},forumId:17490,forumListUrl:'/biobridge/forums/bbi', text:'BBI'} ) //,
          .when('/forums/bbi',                    { templateUrl: 'views/bbi/forums/thread-list-view.html',    resolveController: true,resolve : { user : securize(['User'])}, forumId:17490, postUrl:'/biobridge/forums/bbi', text:'BBI' } )

    }

    //============================================================
    //
    //
    //============================================================
    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>routes update - unique file names from translation<commit_after>define(['app', 'jquery', 'lodash', 'text!./redirect-dialog.html','providers/extended-route', 'ngRoute', 'authentication', 'ngDialog','ngCookies'], function(app, $, _,redirectDialog) { 'use strict';

    var locationPath = window.location.pathname.toLowerCase().split('?')[0];

    app.config(['extendedRouteProvider', '$locationProvider', function($routeProvider, $locationProvider) {

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

        // /decisions/cop/*
        if(/^\/decisions\/cop($|\/.*)/.test(locationPath))
            registerRoutes_CopDecisions($routeProvider);

        // /management/decisions/*
        if(/^\/management\/decisions($|\/.*)/.test(locationPath))
            registerRoutes_ManagementDecisions($routeProvider);

        // /insession/*
        if(/^\/insession($|\/.*)/.test(locationPath))
            registerRoutes_insession($routeProvider);

        // /conferences/**
        if(/^\/conferences($|\/.*)/.test(locationPath))
            registerRoutes_conferences($routeProvider);

        // /aichi-targets/*
        if(/^\/aichi-targets($|\/.*)/.test(locationPath))
            registerRoutes_aichiTargets($routeProvider);

        // /kronos/*
        if(/^\/kronos\/list-of-participants($|\/.*)/.test(locationPath))
            registerRoutes_kronos($routeProvider);

        //bbi/*
        if(/^\/biobridge($|\/.*)/.test(locationPath))
            registerRoutes_bbi($routeProvider);

        $routeProvider.when('/403', { templateUrl: '/app/views/403.html' });
        $routeProvider.when('/404', { templateUrl: '/app/views/404.html' }).otherwise({redirectTo: '/404'});
    }
  ]);

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_CopDecisions(routeProvider) {

      $('base').attr('href', '/decisions/cop/'); // allow full page reload outside of  /decisions/*

      //routeProvider.when('/cop', { templateUrl: 'views/decisions/search.html', resolveController: true });
      routeProvider.when('/:session',                      { templateUrl: 'views/decisions/list.html', resolveController: true });
      routeProvider.when('/:session/:decision',            { templateUrl: 'views/decisions/view.html', resolveController: true });
      routeProvider.when('/:session/:decision/:paragraph', { templateUrl: 'views/decisions/paragraph.html', resolveController: true });
      //routeProvider.when('/', { templateUrl: 'views/decisions/search.html', resolveController: true });
  }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_ManagementDecisions(routeProvider) {

      $("base").attr('href', '/management/decisions/'); // allow full page reload outside of  /decisions/*

      routeProvider.when('/',                 { templateUrl: 'views/decisions/index.html', resolveController: true, resolve : { user : securize(["Administrator","DecisionTrackingTool"]) } } );
      routeProvider.when('/:meeting/:number', { templateUrl: 'views/decisions/edit.html',  resolveController: true, resolve : { user : securize(["Administrator","DecisionTrackingTool"]) } } );
  }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_insession(routeProvider) {

      $("base").attr('href', '/insession/'); // allow full page reload outside of  /insession/*

      routeProvider
      .when('/',           { template : '

', resolve: { r: function() { window.location='/conferences/2016'; } } })
      .when('/management', { templateUrl : 'views/meetings/documents/in-session/management.html', resolveController : true, resolve : { user : securize(["Administrator","EditorialService"]) } } )
      .when('/:meeting',   { templateUrl : 'views/meetings/documents/in-session/meeting-id.html', resolveController : true, progress : { stop : false } } );
    }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_conferences(routeProvider) {

      $("base").attr('href', '/conferences/'); // allow full page reload outside of  /insession/*

      routeProvider
      .when('/',                        { redirectTo: '/2016' })
      .when('/2016',                    { templateUrl : 'views/meetings/cop13/index.html'})
      .when('/2016/cop-13-hls/documents',{templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'COP13-HLS' }), meeting: resolveLiteral('COP13-HLS') }, reloadOnSearch:false })
      .when('/2016/cop-13/documents',   { templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'COP-13'    }), meeting: resolveLiteral('COP-13')    }, reloadOnSearch:false })
      .when('/2016/cp-mop-8/documents', { templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'MOP-08'    }), meeting: resolveLiteral('MOP-08')    }, reloadOnSearch:false })
      .when('/2016/np-mop-2/documents', { templateUrl : 'views/meetings/documents/documents.html', resolveController : true, resolve: { routePrams: injectRouteParams({ meetingId: 'NP-MOP-02' }), meeting: resolveLiteral('NP-MOP-02') }, reloadOnSearch:false })
      .when('/2016/schedules',          { redirectTo: '/2016/cop-13/documents' })

      .when('/management/import-translations',     { templateUrl : 'views/meetings/documents/management/translations.html', resolveController : true, resolve : { user : securize(["Administrator","EditorialService"]) } })
      .when('/management/:meeting/documents/:id',  { templateUrl : 'views/meetings/documents/management/document-id.html',  resolveController : true, resolve : { user : securize(["Administrator","EditorialService"]) }, reloadOnSearch:false });
    }

  //============================================================
  //
  //
  //============================================================
  function registerRoutes_aichiTargets(routeProvider) {

      $("base").attr('href', '/aichi-targets/'); // allow full page reload outside of  /insession/*

      routeProvider
        .when('/',                  { templateUrl: 'views/aichi-targets/index.html',    controllerAs: 'indexCtrl',   resolveController: true })
        .when('/target/:targetId',  { templateUrl: 'views/aichi-targets/index-id.html', controllerAs: 'indexIdCtrl', resolveController: true });
  }

  //============================================================
  //
  //s
  //============================================================
  function registerRoutes_kronos(routeProvider) {

      $("base").attr('href', '/kronos/list-of-participants/'); // allow full page reload outside of  /insession/*

      routeProvider
        .when('/',                  { templateUrl: 'views/meetings/participants/index.html',    controllerAs: 'indexCtrl',   resolveController: true, resolve: { user : securize(["Administrator","KronosAdministrator", "ScbdStaff"]) }  });
  }

    //============================================================
    //
    //
    //============================================================
    function resolveLiteral(value) {
        return function() { return value; };
    }

    //============================================================
    //
    //
    //============================================================
    function injectRouteParams(params) {
        return ['$route', function($route) {
            return _.defaults($route.current.params, params);
        }];
    }

    //============================================================
    //
    //
    //============================================================
    function registerRoutes_bbi(routeProvider) {

        $("base").attr('href', '/biobridge/'); // allow full page reload outside of  /insession/*

        routeProvider
          .when('/',                       { templateUrl: 'views/bbi/index-bbi.html',        controllerAs: 'indexCtrl',   resolveController: true })
          .when('/platform/submit/:schema',         { templateUrl: 'views/bbi/management/record-list.html',  controllerAs: 'submitCtrl',  resolveController: true,resolve : { user : securize(['User']) } })
          .when('/platform/submit/:schema/:id',     { templateUrl: 'views/bbi/management/edit.html',         controllerAs: 'editCtrl',    resolveController: true ,resolve : { user : securize(['User']) }})
          .when('/platform/submit/:schema/:id/view',{ templateUrl: 'views/bbi/management/view.html',    controllerAs: 'viewCtrl',    resolveController: true,resolve : { user : securize(['Everyone']) } })
          .when('/platform/dashboard'              ,{ templateUrl: 'views/bbi/management/index-man.html',    controllerAs: 'dashCtrl',    resolveController: true ,resolve : { user : securize(['User']) }})
          .when('/platform/search',                { templateUrl: 'views/bbi/management/search.html',  controllerAs: 'searchCtrl',   resolveController: true, reloadOnSearch : false})
          .when('/platform/tools',                  { templateUrl: 'views/bbi/management/tools.html',  controllerAs: 'toolsCtrl',  resolveController: true})
          .when('/platform/about',                  { templateUrl: 'views/bbi/management/about/index.html',  controllerAs: 'pAboutCtrl',  resolveController: true})
          .when('/platform/:schema',                       { templateUrl: 'views/bbi/management/search.html',  controllerAs: 'searchCtrl',   resolveController: true, reloadOnSearch : false})

          .when('/about',                  { templateUrl: 'views/bbi/about/index-about.html',  controllerAs: 'initCtrl',  resolveController: true})
          .when('/about/framework',        { templateUrl: 'views/bbi/about/framework.html',  controllerAs: 'frameworkCtrl',  resolveController: true})
          .when('/about/plan',             { templateUrl: 'views/bbi/about/plan.html',  controllerAs: 'planCtrl',  resolveController: true})
          .when('/about/partners',         { templateUrl: 'views/bbi/about/partners.html',  controllerAs: 'partnersCtrl',  resolveController: true})

          .when('/participation',                { templateUrl: 'views/bbi/participation/index-part.html',  controllerAs: 'participationCtrl',  resolveController: true})
          .when('/participation/request',        { templateUrl: 'views/bbi/participation/request.html',  controllerAs: 'requestCtrl',  resolveController: true})
          .when('/participation/provide',        { templateUrl: 'views/bbi/participation/provide.html',  controllerAs: 'provideCtrl',  resolveController: true})
          .when('/participation/opportunity',    { templateUrl: 'views/bbi/participation/opportunity.html',  controllerAs: 'opportunityCtrl',  resolveController: true})

          .when('/projects',                { templateUrl: 'views/bbi/pilot-projects/index-proj.html',  controllerAs: 'pilotCtrl',  resolveController: true})
          .when('/projects/selected',       { templateUrl: 'views/bbi/pilot-projects/selected.html',  controllerAs: 'selectedCtrl',  resolveController: true})

          // .when('/proposals',                     { templateUrl: 'views/bbi/search.html',  controllerAs: 'searchCtrl',  resolveController: true})

          .when('/resources',                     { templateUrl: 'views/bbi/resources.html',  controllerAs: 'resoCtrl',  resolveController: true})
          .when('/faq',                           { templateUrl: 'views/bbi/faq.html',  controllerAs: 'faqCtrl',  resolveController: true})
          .when('/contact',                       { templateUrl: 'views/bbi/contact.html',  controllerAs: 'contCtrl',  resolveController: true})

          .when('/comms',                         { templateUrl: 'views/bbi/comms/index-comm.html'    ,  controllerAs: 'commsCtrl',  resolveController: true})
          .when('/comms/panel',                   { templateUrl: 'views/bbi/comms/panel.html',  controllerAs: 'panelCtrl',   resolveController: true})
          .when('/search',                        { templateUrl: 'views/bbi/search.html',  controllerAs: 'searchCtrl',   resolveController: true, reloadOnSearch : false})
          .when('/platform',                      { templateUrl: 'views/bbi/platform.html',  controllerAs: 'pltfCtrl',   resolveController: true, reloadOnSearch : false})

          .when('/forums/bbi/:threadId',          { templateUrl: 'views/bbi/forums/post-list-view.html',  resolveController: true,resolve : { user : securize(['User'])},forumId:17490,forumListUrl:'/biobridge/forums/bbi', text:'BBI'} ) //,
          .when('/forums/bbi',                    { templateUrl: 'views/bbi/forums/thread-list-view.html',    resolveController: true,resolve : { user : securize(['User'])}, forumId:17490, postUrl:'/biobridge/forums/bbi', text:'BBI' } )

    }

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

couchTests.view_errors = function(debug) {
  var db = new CouchDB("test_suite_db");
  db.deleteDb();
  db.createDb();
  if (debug) debugger;

  var doc = {integer: 1, string: "1", array: [1, 2, 3]};
  T(db.save(doc).ok);

  // emitting a key value that is undefined should result in that row not
  // being included in the view results
  var results = db.query(function(doc) {
    emit(doc.undef, null);
  });
  T(results.total_rows == 0);

  // if a view function throws an exception, its results are not included in
  // the view index, but the view does not itself raise an error
  var results = db.query(function(doc) {
    doc.undef(); // throws an error
  });
  T(results.total_rows == 0);

  // if a view function includes an undefined value in the emitted key or
  // value, an error is logged and the result is not included in the view
  // index, and the view itself does not raise an error
  var results = db.query(function(doc) {
    emit([doc._id, doc.undef], null);
  });
  T(results.total_rows == 0);

  // querying a view with invalid params should give a resonable error message
  var xhr = CouchDB.request("POST", "/test_suite_db/_temp_view?startkey=foo", {
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify({language: "javascript",
      map : "function(doc){emit(doc.integer)}"
    })
  });
  T(JSON.parse(xhr.responseText).error == "invalid_json");

  // views should ignore Content-Type, like the rest of CouchDB
  var xhr = CouchDB.request("POST", "/test_suite_db/_temp_view", {
    headers: {"Content-Type": "application/x-www-form-urlencoded"},
    body: JSON.stringify({language: "javascript",
      map : "function(doc){}"
    })
  });
  T(xhr.status == 200);

  var map = function (doc) {emit(doc.integer, doc.integer);};

  try {
      db.query(map, null, {group: true});
      T(0 == 1);
  } catch(e) {
      T(e.error == "query_parse_error");
  }

  // reduce=false on map views doesn't work, so group=true will
  // never throw for temp reduce views.

  var designDoc = {
    _id:"_design/test",
    language: "javascript",
    views: {
      "no_reduce": {map:"function(doc) {emit(doc._id, null);}"},
      "with_reduce": {
        map:"function (doc) {emit(doc.integer, doc.integer)};",
        reduce:"function (keys, values) { return sum(values); };"}
    }
  };
  T(db.save(designDoc).ok);

  var designDoc2 = {
    _id:"_design/testbig",
    language: "javascript",
    views: {
      "reduce_too_big"  : {
        map:"function (doc) {emit(doc.integer, doc.integer)};",
        reduce:"function (keys, values) { var chars = []; for (var i=0; i < 1000; i++) {chars.push('wazzap');};return chars; };"}
    }
  };
  T(db.save(designDoc2).ok);

  try {
      db.view("test/no_reduce", {group: true});
      T(0 == 1);
  } catch(e) {
      T(e.error == "query_parse_error");
  }

  try {
    db.view("test/no_reduce", {reduce: true});
    T(0 == 1);
  } catch(e) {
    T(db.last_req.status == 400);
    T(e.error == "query_parse_error");
  }

  try {
      db.view("test/with_reduce", {group: true, reduce: false});
      T(0 == 1);
  } catch(e) {
      T(e.error == "query_parse_error");
  }

  // Check error responses for invalid multi-get bodies.
  var path = "/test_suite_db/_design/test/_view/no_reduce";
  var xhr = CouchDB.request("POST", path, {body: "[]"});
  T(xhr.status == 400);
  result = JSON.parse(xhr.responseText);
  T(result.error == "bad_request");
  T(result.reason == "Request body must be a JSON object");
  var data = "{\"keys\": 1}";
  xhr = CouchDB.request("POST", path, {body:data});
  T(xhr.status == 400);
  result = JSON.parse(xhr.responseText);
  T(result.error == "bad_request");
  T(result.reason == "`keys` member must be a array.");

  // if the reduce grows to fast, throw an overflow error
  var path = "/test_suite_db/_design/testbig/_view/reduce_too_big";
  xhr = CouchDB.request("GET", path);
  T(xhr.status == 500);
  result = JSON.parse(xhr.responseText);
  T(result.error == "reduce_overflow_error");
};
<commit_msg>Test and fix for infinite loops in view_servers, fix for crashed OS processes causing leaked erlang processes and fix for view server crashing when view group process terminates.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.

couchTests.view_errors = function(debug) {
  var db = new CouchDB("test_suite_db");
  db.deleteDb();
  db.createDb();
  if (debug) debugger;

  run_on_modified_server(
    [{section: "couchdb",
      key: "os_process_timeout",
      value: "500"}],
    function() {
      var doc = {integer: 1, string: "1", array: [1, 2, 3]};
      T(db.save(doc).ok);

      // emitting a key value that is undefined should result in that row not
      // being included in the view results
      var results = db.query(function(doc) {
        emit(doc.undef, null);
      });
      T(results.total_rows == 0);

      // if a view function throws an exception, its results are not included in
      // the view index, but the view does not itself raise an error
      var results = db.query(function(doc) {
        doc.undef(); // throws an error
      });
      T(results.total_rows == 0);

      // if a view function includes an undefined value in the emitted key or
      // value, an error is logged and the result is not included in the view
      // index, and the view itself does not raise an error
      var results = db.query(function(doc) {
        emit([doc._id, doc.undef], null);
      });
      T(results.total_rows == 0);

      // querying a view with invalid params should give a resonable error message
      var xhr = CouchDB.request("POST", "/test_suite_db/_temp_view?startkey=foo", {
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({language: "javascript",
          map : "function(doc){emit(doc.integer)}"
        })
      });
      T(JSON.parse(xhr.responseText).error == "invalid_json");

      // views should ignore Content-Type, like the rest of CouchDB
      var xhr = CouchDB.request("POST", "/test_suite_db/_temp_view", {
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body: JSON.stringify({language: "javascript",
          map : "function(doc){}"
        })
      });
      T(xhr.status == 200);

      var map = function (doc) {emit(doc.integer, doc.integer);};

      try {
          db.query(map, null, {group: true});
          T(0 == 1);
      } catch(e) {
          T(e.error == "query_parse_error");
      }

      // reduce=false on map views doesn't work, so group=true will
      // never throw for temp reduce views.

      var designDoc = {
        _id:"_design/test",
        language: "javascript",
        views: {
          "no_reduce": {map:"function(doc) {emit(doc._id, null);}"},
          "with_reduce": {
            map:"function (doc) {emit(doc.integer, doc.integer)};",
            reduce:"function (keys, values) { return sum(values); };"}
        }
      };
      T(db.save(designDoc).ok);

      var designDoc2 = {
        _id:"_design/testbig",
        language: "javascript",
        views: {
          "reduce_too_big"  : {
            map:"function (doc) {emit(doc.integer, doc.integer)};",
            reduce:"function (keys, values) { var chars = []; for (var i=0; i < 1000; i++) {chars.push('wazzap');};return chars; };"}
        }
      };
      T(db.save(designDoc2).ok);

      try {
          db.view("test/no_reduce", {group: true});
          T(0 == 1);
      } catch(e) {
          T(e.error == "query_parse_error");
      }

      try {
        db.view("test/no_reduce", {reduce: true});
        T(0 == 1);
      } catch(e) {
        T(db.last_req.status == 400);
        T(e.error == "query_parse_error");
      }

      try {
          db.view("test/with_reduce", {group: true, reduce: false});
          T(0 == 1);
      } catch(e) {
          T(e.error == "query_parse_error");
      }

      var designDoc3 = {
        _id:"_design/infinite",
        language: "javascript",
        views: {
          "infinite_loop" :{map:"function(doc) {while(true){emit(doc,doc);}};"}
        }
      };
      T(db.save(designDoc3).ok);

      try {
          db.view("infinite/infinite_loop");
          T(0 == 1);
      } catch(e) {
          T(e.error == "os_process_error");
      }

      // Check error responses for invalid multi-get bodies.
      var path = "/test_suite_db/_design/test/_view/no_reduce";
      var xhr = CouchDB.request("POST", path, {body: "[]"});
      T(xhr.status == 400);
      result = JSON.parse(xhr.responseText);
      T(result.error == "bad_request");
      T(result.reason == "Request body must be a JSON object");
      var data = "{\"keys\": 1}";
      xhr = CouchDB.request("POST", path, {body:data});
      T(xhr.status == 400);
      result = JSON.parse(xhr.responseText);
      T(result.error == "bad_request");
      T(result.reason == "`keys` member must be a array.");

      // if the reduce grows to fast, throw an overflow error
      var path = "/test_suite_db/_design/testbig/_view/reduce_too_big";
      xhr = CouchDB.request("GET", path);
      T(xhr.status == 500);
      result = JSON.parse(xhr.responseText);
      T(result.error == "reduce_overflow_error");
    });
};
<|endoftext|>


<commit_before>var QueryModule = require('./scripts/QueryModule.js');
var User = require('./models/user.js');
var Page = require('./models/page.js');

module.exports = function (app, passport) {
    app.get('/', function(req, res) {
        res.render('index.ejs', {
            message: req.flash('privilegesMessage')
        });
    });

    app.get('/index2', function(req, res) {
        var navPages = Page.find({nav: 'true'}, function (err, pages) {
            if (err) {
                throw err;
            }

            console.log(pages);
            res.render('index2.ejs', {
                navPages: pages
            });
        })
    });

    app.post('/epic/createPage', function(req, res) {
        console.log(req.body);
        Page.collection.insert(req.body, function (err, docs) {
            if (err) {
                throw err;
            }

            console.log('Pages were inserted: ' + docs.length);
            res.send('{}');
        });
    });

    app.get('/pages/:pageURL', function(req, res) {
        var navPages = Page.findOne({href: req.params.pageURL}, function (err, page) {
            if (err) {
                throw err;
            }

            if (!page) {
                console.log('NO SUCH PAGE?');
                res.render('Could not find such page.');
            }

            res.send(page.href);
        });
    });

    //show login form
    app.get('/login', function(req, res) {
        res.render('login.ejs', {
            message: req.flash('loginMessage')
        });
    });

    app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    }));

    //show signup form
    app.get('/signup', function(req, res) {
        res.render('signup.ejs', {
            message: req.flash('signupMessage')
        });
    });

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/profile',
        failureRedirect: '/signup',
        failureFlash: true //allow flash messages
    }));

    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user: req.user // get the user out of session and pass it to template
        });
    });

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

    app.get('/admin',isLoggedIn, isAdmin, function (req, res) {
        res.render('admin/index.ejs');
    });

    app.get('/getAllUsers', function(req, res) {
        var users = User.find({}, function (err, users) {
            if (err) {
                throw err;
            }

            res.render('admin/users-partial.ejs', {
                users: users
            });
        })
    });

    app.post('/updateUserInfo', function(req, res) {
        User.update(req.body.query, req.body.options, function (err, numAffected) {
            if (err) {
                throw err;
            }

            console.log('Updated user: ' + req.params.id);
            //jquery data is set to json
            res.send('{}');
        });
    });

    //middleware to make sure user is logged in
    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        }
        req.flash('privilegesMessage', 'You don\'t have the required privileges to visit this page!');
        res.redirect('/');
    }

    function isAdmin(req, res, next) {
        /*TODO: probably should be changed to use external admins collection*/
        if (req.user.userType === 'admin') {
            return next();
        }
        req.flash('privilegesMessage', 'You don\'t have the required privileges to visit this page!');
        res.redirect('/');
    }
}
<commit_msg>queryModule is not used<commit_after>var User = require('./models/user.js');
var Page = require('./models/page.js');

module.exports = function (app, passport) {
    app.get('/', function(req, res) {
        res.render('index.ejs', {
            message: req.flash('privilegesMessage')
        });
    });

    app.get('/index2', function(req, res) {
        var navPages = Page.find({nav: 'true'}, function (err, pages) {
            if (err) {
                throw err;
            }

            console.log(pages);
            res.render('index2.ejs', {
                navPages: pages
            });
        })
    });

    app.post('/epic/createPage', function(req, res) {
        console.log(req.body);
        Page.collection.insert(req.body, function (err, docs) {
            if (err) {
                throw err;
            }

            console.log('Pages were inserted: ' + docs.length);
            res.send('{}');
        });
    });

    app.get('/pages/:pageURL', function(req, res) {
        var navPages = Page.findOne({href: req.params.pageURL}, function (err, page) {
            if (err) {
                throw err;
            }

            if (!page) {
                console.log('NO SUCH PAGE?');
                res.render('Could not find such page.');
            }

            res.send(page.href);
        });
    });

    //show login form
    app.get('/login', function(req, res) {
        res.render('login.ejs', {
            message: req.flash('loginMessage')
        });
    });

    app.post('/login', passport.authenticate('local-login', {
        successRedirect: '/profile',
        failureRedirect: '/login',
        failureFlash: true
    }));

    //show signup form
    app.get('/signup', function(req, res) {
        res.render('signup.ejs', {
            message: req.flash('signupMessage')
        });
    });

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/profile',
        failureRedirect: '/signup',
        failureFlash: true //allow flash messages
    }));

    app.get('/profile', isLoggedIn, function(req, res) {
        res.render('profile.ejs', {
            user: req.user // get the user out of session and pass it to template
        });
    });

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

    app.get('/admin',isLoggedIn, isAdmin, function (req, res) {
        res.render('admin/index.ejs');
    });

    app.get('/getAllUsers', function(req, res) {
        var users = User.find({}, function (err, users) {
            if (err) {
                throw err;
            }

            res.render('admin/users-partial.ejs', {
                users: users
            });
        })
    });

    app.post('/updateUserInfo', function(req, res) {
        User.update(req.body.query, req.body.options, function (err, numAffected) {
            if (err) {
                throw err;
            }

            console.log('Updated user: ' + req.params.id);
            //jquery data is set to json
            res.send('{}');
        });
    });

    //middleware to make sure user is logged in
    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        }
        req.flash('privilegesMessage', 'You don\'t have the required privileges to visit this page!');
        res.redirect('/');
    }

    function isAdmin(req, res, next) {
        /*TODO: probably should be changed to use external admins collection*/
        if (req.user.userType === 'admin') {
            return next();
        }
        req.flash('privilegesMessage', 'You don\'t have the required privileges to visit this page!');
        res.redirect('/');
    }
}
<|endoftext|>


<commit_before>var Todo = require('./models/todo');
var MetaList = require('./models/metalist');
var Numba = require('./models/number');
var currencyFormatter = require('currency-formatter');
var mongoose = require('mongoose');

function addMetaListTotal(res, price) {
    MetaList.find(function(err, metalist) {
        if (err) {
            res.send(err);
        }
        metalist[0].update({ total: +price + +metalist[0].total, number: ++metalist[0].number },
            function(err, message) {
                if (err) {
                    res.send("There was a problem updating the information to the database: " + err);
                }
                MetaList.find(function(err, metalist2) {
                    if (err) {
                        res.send(err);
                    }
                    var obj = metalist2[0].toObject();
                    obj.total = obj.total;
                    obj.cTotal = dollar(obj.total);
                    res.json(obj);
                });

            });
    });
};

function subtractMetaListTotal(res, id) {
    try {
        console.log("id:" + id);
        if (id.match(/^[0-9a-fA-F]{24}$/)) {
            Todo.findById(id, function(err, todo) {
                console.log("?=>" + todo);
                if (err) {
                    console.log("error in subtract");
                    console.log(err.message);
                    res.send(500, err.message);
                }
                MetaList.find(function(err, metalist) {
                    if (err) {
                        res.status(500).json({ error: err.message });
                    }
                    metalist[0].update({ total: +metalist[0].total - +todo.price, number: --metalist[0].number },
                        function(err, message) {
                            if (err) {
                                res.status(500).json({ error: err.message });
                            }
                            console.log("metalist update response message:" + message);
                            console.log("just updated metalist:" + JSON.stringify(metalist[0]));
                            MetaList.find(function(err, metalist2) {
                                var obj = metalist2[0].toObject()
                                if (err) {
                                    res.send(err);
                                }
                                obj.cTotal = dollar(obj.total);
                                console.log("subtract: 2nd pass on getting metalist:" + JSON.stringify(obj));
                                res.json(obj);
                            });
                        });
                });
            });
        } else {
            throw new Error("Not a valid id:" + id);
        }
    } catch (err) {
        console.log("ERR in subtract:" + err.message);
        res.status(500).json({ error: err.message });
    }
};

function getMetaList(res) {
    MetaList.find(function(err, metalist) {
        var obj = metalist[0].toObject()
            // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }
        obj.cTotal = dollar(obj.total);
        res.json(obj);
    });
};

function getTodos(res) {
    Todo.find(function(err, todos) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }

        res.json(todos); // return all todos in JSON format
    });
};

function getTodoById(id, res) {
    // get a user with ID of 1
    Todo.findById(id, function(err, todo) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }
        res.json(todo);
    });
};

function getTodoByProperty(key, value, res) {
    // get a user with ID of 1
    //Todo.find({ key: value }).exec(function(err, todo) {
    Todo.where(key, value).exec(function(err, todo) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }
        res.json(todo);
    });
};

function dollar(amount) {
    return currencyFormatter.format(amount, { code: 'USD' });
}

function getItemAtOrder(order, res) {
    console.log("getting ready to look for:" + order);
    Numba.where("order", order).exec(function(err, number) {
        if (err) {
            res.send(err);
        }
        console.log("found order:" + JSON.stringify(number))
        Todo.find(function(err, todos) {
            try {
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err) {
                    console.log(err.message)
                    res.send(err);
                }

                console.log("number:" + (number[0].value - 1));
                console.log("todos.length:" + todos.length);
                if (todos.length >= number[0].value && number[0].value > 0) {
                    res.json(todos[number[0].value - 1]);
                } else {
                    throw new Error("Order value not valid:" + JSON.stringify(number[0]));
                }
                // if (todos.length > number[0].value) {
                //     res.json(todos[number[0].value - 1]); // return all todos in JSON format
                // } else {
                //     res.send("no item found");
                // }
            } catch (err) {
                console.log("ERR in order request:" + err.message);
                res.status(500).json({ error: err.message });
            }
        });
    })
}

module.exports = function(app) {

    // api ---------------------------------------------------------------------
    app.route('/api/list/:item_id')
        .get(function(req, res) {
            console.log("order value:" + req.params.item_id);
            getItemAtOrder(req.params.item_id, res);
        });
    app.route('/api/list')
        .get(function(req, res) {
            getTodos(res);
        }).post(function(req, res) {
            console.log("adding new item:" + JSON.stringify(req.body));
            var newTodo = new Todo(req.body);
            newTodo.save((err, newTodo) => {
                if (err) {
                    res.status(500).json({error: err.message});
                } else {
                    getTodos(res);
                }
            });
        });
    app.route('/api/metalist/add')
        .post(function(req, res) {
            console.log("add total:" + JSON.stringify(req.body));
            addMetaListTotal(res, req.body.price);
        });
    app.route('/api/metalist/subtract')
        .post(function(req, res) {
            console.log("subtract total from id:" + JSON.stringify(req.body));
            console.log("subtract total from id:" + req.body.id);
            subtractMetaListTotal(res, req.body.id);
        });
    app.route('/api/metalist')
        .get(function(req, res) {
            getMetaList(res);
        });
    app.get('/api/item/:order', function(req, res) {
        console.log("order:" + req.params.order);
        getItemAtOrder(req.params.order, res);
    });

    //------------------------
    //
    //  No Tests
    //
    //------------------------
    app.get('/api/todos/:todo_key/:todo_value', function(req, res) {
        console.log("key:" + req.params.todo_key);
        console.log("value:" + req.params.todo_value);
        getTodoByProperty(req.params.todo_key, req.params.todo_value, res);
    });

    // 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.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });
};
<commit_msg>cleaning up old code<commit_after>var Todo = require('./models/todo');
var MetaList = require('./models/metalist');
var Numba = require('./models/number');
var currencyFormatter = require('currency-formatter');
var mongoose = require('mongoose');

function addMetaListTotal(res, price) {
    MetaList.find(function(err, metalist) {
        if (err) {
            res.send(err);
        }
        metalist[0].update({ total: +price + +metalist[0].total, number: ++metalist[0].number },
            function(err, message) {
                if (err) {
                    res.send("There was a problem updating the information to the database: " + err);
                }
                MetaList.find(function(err, metalist2) {
                    if (err) {
                        res.send(err);
                    }
                    var obj = metalist2[0].toObject();
                    obj.total = obj.total;
                    obj.cTotal = dollar(obj.total);
                    res.json(obj);
                });

            });
    });
};

function subtractMetaListTotal(res, id) {
    try {
        console.log("id:" + id);
        if (id.match(/^[0-9a-fA-F]{24}$/)) {
            Todo.findById(id, function(err, todo) {
                console.log("?=>" + todo);
                if (err) {
                    console.log("error in subtract");
                    console.log(err.message);
                    res.send(500, err.message);
                }
                MetaList.find(function(err, metalist) {
                    if (err) {
                        res.status(500).json({ error: err.message });
                    }
                    metalist[0].update({ total: +metalist[0].total - +todo.price, number: --metalist[0].number },
                        function(err, message) {
                            if (err) {
                                res.status(500).json({ error: err.message });
                            }
                            console.log("metalist update response message:" + message);
                            console.log("just updated metalist:" + JSON.stringify(metalist[0]));
                            MetaList.find(function(err, metalist2) {
                                var obj = metalist2[0].toObject()
                                if (err) {
                                    res.send(err);
                                }
                                obj.cTotal = dollar(obj.total);
                                console.log("subtract: 2nd pass on getting metalist:" + JSON.stringify(obj));
                                res.json(obj);
                            });
                        });
                });
            });
        } else {
            throw new Error("Not a valid id:" + id);
        }
    } catch (err) {
        console.log("ERR in subtract:" + err.message);
        res.status(500).json({ error: err.message });
    }
};

function getMetaList(res) {
    MetaList.find(function(err, metalist) {
        var obj = metalist[0].toObject()
            // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }
        obj.cTotal = dollar(obj.total);
        res.json(obj);
    });
};

function getTodos(res) {
    Todo.find(function(err, todos) {

        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }

        res.json(todos); // return all todos in JSON format
    });
};

function getTodoById(id, res) {
    // get a user with ID of 1
    Todo.findById(id, function(err, todo) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }
        res.json(todo);
    });
};

function getTodoByProperty(key, value, res) {
    // get a user with ID of 1
    //Todo.find({ key: value }).exec(function(err, todo) {
    Todo.where(key, value).exec(function(err, todo) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            res.send(err);
        }
        res.json(todo);
    });
};

function dollar(amount) {
    return currencyFormatter.format(amount, { code: 'USD' });
}

function getItemAtOrder(order, res) {
    console.log("getting ready to look for:" + order);
    Numba.where("order", order).exec(function(err, number) {
        if (err) {
            res.send(err);
        }
        console.log("found order:" + JSON.stringify(number))
        Todo.find(function(err, todos) {
            try {
                // if there is an error retrieving, send the error. nothing after res.send(err) will execute
                if (err) {
                    console.log(err.message)
                    res.send(err);
                }

                console.log("number:" + (number[0].value - 1));
                console.log("todos.length:" + todos.length);
                if (todos.length >= number[0].value && number[0].value > 0) {
                    res.json(todos[number[0].value - 1]);
                } else {
                    throw new Error("Order value not valid:" + JSON.stringify(number[0]));
                }
                // if (todos.length > number[0].value) {
                //     res.json(todos[number[0].value - 1]); // return all todos in JSON format
                // } else {
                //     res.send("no item found");
                // }
            } catch (err) {
                console.log("ERR in order request:" + err.message);
                res.status(500).json({ error: err.message });
            }
        });
    })
}
//Shouldn't use exception for this, but needed a quick solution
function isJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
module.exports = function(app) {

    // api ---------------------------------------------------------------------
    app.route('/api/list/:item_id')
        .get(function(req, res) {
            console.log("order value:" + req.params.item_id);
            getItemAtOrder(req.params.item_id, res);
        });
    app.route('/api/list')
        .get(function(req, res) {
            getTodos(res);
        }).post(function(req, res) {
            var jsonItem;
            if (!isJsonString(req.body)) {
                console.log("req.body is json");
                jsonItem = req.body;
            } else {
                console.log("req.body is not json");
                jsonItem = JSON.parse(req.body);
            }
            console.log("adding new item:" + JSON.stringify(jsonItem));
            var newTodo = new Todo(jsonItem);
            newTodo.save((err, newTodo) => {
                if (err) {
                    res.status(500).json({ error: err.message });
                } else {
                    getTodos(res);
                }
            });
        });
    app.route('/api/metalist/add')
        .post(function(req, res) {
            console.log("add total:" + JSON.stringify(req.body));
            addMetaListTotal(res, req.body.price);
        });
    app.route('/api/metalist/subtract')
        .post(function(req, res) {
            console.log("subtract total from id:" + JSON.stringify(req.body));
            console.log("subtract total from id:" + req.body.id);
            subtractMetaListTotal(res, req.body.id);
        });
    app.route('/api/metalist')
        .get(function(req, res) {
            getMetaList(res);
        });

    //------------------------
    //
    //  No Tests
    //
    //------------------------
    app.get('/api/todos/:todo_key/:todo_value', function(req, res) {
        console.log("key:" + req.params.todo_key);
        console.log("value:" + req.params.todo_value);
        getTodoByProperty(req.params.todo_key, req.params.todo_value, res);
    });

    // 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.sendFile(__dirname + '/public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });
};
<|endoftext|>