summaryrefslogtreecommitdiffstats
path: root/_site/examples/cross-domain/server.js
blob: beea5d3be92ab0e7f5b609176627eed1874d1d8f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
var express = require('express');

var connect = require('connect');
// Custom csrf library
var csrf = require('./csrf');

var app = express.createServer();

var allowCrossDomain = function(req, res, next) {
  // Added other domains you want the server to give access to
  // WARNING - Be careful with what origins you give access to
  var allowedHost = [
    'http://backbonetutorials.com',
    'http://localhost'
  ];

  if(allowedHost.indexOf(req.headers.origin) !== -1) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
    next();
  } else {
    res.send({auth: false});
  }
}

app.configure(function() {
    app.use(express.cookieParser());
    app.use(express.session({ secret: 'thomasdavislovessalmon' }));
    app.use(express.bodyParser());
    app.use(allowCrossDomain);
    app.use(csrf.check);
});

app.get('/session', function(req, res){
  // This checks the current users auth
  // It runs before Backbones router is started
  // we should return a csrf token for Backbone to use
  if(typeof req.session.username !== 'undefined'){
    res.send({auth: true, id: req.session.id, username: req.session.username, _csrf: req.session._csrf});
  } else {
    res.send({auth: false, _csrf: req.session._csrf});
  }
});

app.post('/session', function(req, res){
  // Login
  // Here you would pull down your user credentials and match them up
  // to the request
  req.session.username = req.body.username;
  res.send({auth: true, id: req.session.id, username: req.session.username});
});

app.del('/session/:id', function(req, res, next){
  // Logout by clearing the session
  req.session.regenerate(function(err){
    // Generate a new csrf token so the user can login again
    // This is pretty hacky, connect.csrf isn't built for rest
    // I will probably release a restful csrf module
    csrf.generate(req, res, function () {
      res.send({auth: false, _csrf: req.session._csrf});
    });
  });
});

app.listen(8000);