// app.js

var http = require('http');
var express = require('express');
var logger = require('morgan');
var bodyParser = require('body-parser');
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var _ = require('lodash');

var errCode = require('./errcode');
var datactx = require('./data/datacontext');
var chats = require('./routes/chats');
var users = require('./routes/users');

// express app begin
var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());

// authentication initialize
app.use(passport.initialize());

passport.use(new BasicStrategy(
    function (username, password, done) {
        try {
            var user = datactx.users.find({ name: username });

            if (!user || !checkPassword(password, user)) {
                return done(null, false); //errCode.INVALID_USER_PASSWORD
            }

            return done(null, user);
        }
        catch (err) {
            return done(err);
        }
    }
));

function checkPassword(password, user) {
    return user.password === password;
}

// app routes
app.use('/api/chats', chats);
app.use('/api/users', users);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error(http.STATUS_CODES[404]);
    err.status = 404;
    next(err);
});

// error handlers

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

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


module.exports = app;

@@ -430,25 +430,27 @@
 %0A// 
-express app begin
+begin app bootstrap
 %0Avar
@@ -1099,16 +1099,22 @@
 p routes
+ setup
 %0Aapp.use
@@ -1354,17 +1354,56 @@
 andlers%0A
-%0A
+if (app.get('env') === 'development') %7B 
 // devel
@@ -1422,19 +1422,16 @@
  handler
-%0A//
  will pr
@@ -1449,48 +1449,8 @@
 ace%0A
-if (app.get('env') === 'development') %7B%0A
     
@@ -1699,19 +1699,16 @@
  handler
-%0A//
  no stac
@@ -1939,16 +1939,16 @@
 ;%0A%7D);%0A%0A%0A
+
 module.e
@@ -1960,9 +1960,8 @@
 s = app;
-%0A

edit code comment