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

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

Fixed authentication.

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    app.use(express.cookieParser());
46    app.use(express.bodyParser());
47    app.use(express.session({ secret: "quasi experimental design" }));
48
49    // initialize passport
50    app.use(passport.initialize());
51    app.use(passport.session());
52
53    // static resources
54    app.get('/', function(request, response){
55        response.sendfile(clientPath('index.html'));
56    });
57    app.get('/*.html', function(request, response) {
58        response.sendfile(clientPath(request.path));
59    });
60    _.each(['/dojo', '/dijit', '/dojox', '/qed', '/qed-client'], function(dir){
61        app.use(dir, express.static(clientPath(dir)));
62    });
63
64   
65    // url to login (might work on others as well?)
66    // you should then have a session to work with
67    // should return a user info object
68    function returnUser(req,res) {
69        res.send(200, req.user);
70    }
71    app.post(
72        '/api/login',
73        passport.authenticate('local'),
74        returnUser);
75
76    // ensure we're authenticated on API calls
77    function ensureAuthenticated(req,res,next){
78        if (!req.user) {
79            return res.send(401,{error:"Login before accessing API."});
80        } else {
81            return next();
82        }
83    }
84   
85    app.get(
86        '/api/login',
87        ensureAuthenticated,
88        returnUser);
89
90    app.post(
91        '/api/logout',
92        ensureAuthenticated,
93        function(req,res){
94            req.logout();
95            res.send(200,{});
96        });
97
98    app.get(
99        '/api/surveyRuns/:id/responses.csv',
100        ensureAuthenticated,
101        function(req, res) {
102            var id = req.params.id;
103            // query CouchDB and build the CSV file
104            res.set({
105                'Content-Type': 'text/csv',
106                'Content-Disposition': 'attachment; filename=surveyRun-'+id+'-responses.csv'
107            });
108            res.send(200, "Response for surveyRun "+id);
109        });
110   
111    // forward to couch
112    app.use('/api/data', ensureAuthenticated);
113    app.use('/api/data', proxy(settings.couchDbURL));
114
115    return app;
116
117};
Note: See TracBrowser for help on using the repository browser.