source: Dev/trunk/src/server/app.js @ 470

Last change on this file since 470 was 470, checked in by hendrikvanantwerpen, 12 years ago

Reorganized app and fixed some style issues.

Was looking for a bug where the proxy would not forward requests to the
database. This is somehow magically resolved now.

File size: 3.4 KB
Line 
1var express = require("express");
2var passport = require("passport"),
3    passportLocal = require("passport-local");
4var fs = require("fs");
5var path = require("path");
6var proxy = require("./util/simple-http-proxy");
7var _ = require("underscore");
8
9function assertSetting(name, settings, validate) {
10    if ( typeof settings[name] === 'undefined' ) {
11        throw new Error("Required setting '"+name+"' undefined.");
12    }
13    if ( _.isFunction(validate) && !validate(settings[name]) ) {
14        throw new Error("Setting '"+name+"' with value '"+settings[name]+"' is invalid.");
15    }
16}
17
18exports.App = function(settings) {
19
20    assertSetting("couchDbURL", settings, _.isString);
21   
22    function clientPath(relativePath) {
23        return path.resolve(__dirname+'/../client/'+relativePath);
24    }
25
26    passport.use(new passportLocal.Strategy(function(username, password, done){
27        if ( username === "igor" && password === "mayer" ) {
28            done(null,{ username: "igor" });
29        } else {
30            done(null,false,{ message: 'Invalid credentials.' });
31        }
32    }));
33    passport.serializeUser(function(user, done) {
34        done(null, user.username);
35    });
36    passport.deserializeUser(function(id, done) {
37        done(null, {username: id});
38    });
39
40    var app = express();
41    app.use(express.logger());
42    app.use(express.compress());
43    app.use(express.favicon());
44
45    // cookies and session
46    app.use('/api/login',express.bodyParser());
47    app.use(express.cookieParser());
48    app.use(express.session({ secret: "quasi experimental design" }));
49
50    // passport
51    app.use(passport.initialize());
52    app.use(passport.session());
53    function ensureAuthenticated(req,res,next){
54        if (!req.user) {
55            return res.send(401,{error:"Login before accessing API."});
56        } else {
57            return next();
58        }
59    }
60    function returnUser(req,res) {
61        res.send(200, req.user);
62    }
63
64    // static resources
65    app.get('/', function(request, response){
66        response.sendfile(clientPath('index.html'));
67    });
68    app.get('/*.html', function(request, response) {
69        response.sendfile(clientPath(request.path));
70    });
71    _.each(['/dojo', '/dijit', '/dojox', '/qed', '/qed-client'], function(dir){
72        app.use(dir, express.static(clientPath(dir)));
73    });
74
75
76    // post to this url to login
77    app.post(
78        '/api/login',
79        passport.authenticate('local'),
80        returnUser);
81
82    // return the info for the current logged in user
83    app.get(
84        '/api/login',
85        ensureAuthenticated,
86        returnUser);
87
88    // explicitly logout this user
89    app.post(
90        '/api/logout',
91        ensureAuthenticated,
92        function(req,res){
93            req.logout();
94            res.send(200,{});
95        });
96
97    // data is proxied to couch
98    app.use('/api/data', ensureAuthenticated);
99    app.use('/api/data', proxy(settings.couchDbURL));
100
101    // generate CSV download of responses
102    app.get(
103        '/api/surveyRuns/:id/responses.csv',
104        ensureAuthenticated,
105        function(req, res) {
106            var id = req.params.id;
107            // query CouchDB and build the CSV file
108            res.set({
109                'Content-Type': 'text/csv',
110                'Content-Disposition': 'attachment; filename=surveyRun-'+id+'-responses.csv'
111            });
112            res.send(200, "Response for surveyRun "+id);
113        });
114   
115    return app;
116
117};
Note: See TracBrowser for help on using the repository browser.