|
| 1 | +var app = require('express')(); |
| 2 | +var http = require('http').Server(app); |
| 3 | +var io = require('socket.io')(http); |
| 4 | +var request = require('request'); |
| 5 | +var bodyParser = require('body-parser'); |
| 6 | + |
| 7 | +app.use(bodyParser()); |
| 8 | + |
| 9 | +app.get('/realtime/', function(req, res){ |
| 10 | + res.sendFile(__dirname + '/files/index.html'); |
| 11 | +}); |
| 12 | + |
| 13 | +app.post('/events/', function(req, res){ |
| 14 | + if(req.body){ |
| 15 | + io.emit("event", req.body); |
| 16 | + } |
| 17 | + res.status(201); |
| 18 | + res.send("{}"); |
| 19 | +}); |
| 20 | + |
| 21 | +io.on("connection", function(socket){ |
| 22 | + // Authentication Check |
| 23 | + var headers = socket.handshake.headers; |
| 24 | + request({ |
| 25 | + url:"http://localhost:8000/api/auth/", |
| 26 | + json:true, |
| 27 | + headers:{ |
| 28 | + "Cookie":headers.cookie, |
| 29 | + "Accept":"application/json" |
| 30 | + } |
| 31 | + },function (error, response, body){ |
| 32 | + if (!error && response.statusCode == 200 && body.is_staff) { |
| 33 | + allowed = true; |
| 34 | + }else{ |
| 35 | + socket.disconnect(); |
| 36 | + } |
| 37 | + }); |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +}); |
| 43 | + |
| 44 | + |
| 45 | +http.listen(8001, function(){ |
| 46 | + console.log('listening on *:8001'); |
| 47 | +}); |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +// Proxy Server for Development |
| 54 | +var http = require('http'); |
| 55 | +var httpProxy = require('http-proxy'); |
| 56 | +var url = require('url'); |
| 57 | +var proxy = httpProxy.createProxyServer({}); |
| 58 | + |
| 59 | +var server = http.createServer(function (req, res) { |
| 60 | + |
| 61 | + var hostname = req.headers.host.split(":")[0]; |
| 62 | + var pathname = url.parse(req.url).pathname; |
| 63 | + |
| 64 | + if(pathname.indexOf("/socket.io/") === 0 || pathname.indexOf("/realtime/") === 0 ){ |
| 65 | + proxy.web(req, res, { |
| 66 | + target: "http://localhost:8001" |
| 67 | + }); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + proxy.web(req, res, { |
| 72 | + target: "http://localhost:8000" |
| 73 | + }); |
| 74 | +}); |
| 75 | + |
| 76 | +server.on('upgrade', function (req, socket, head) { |
| 77 | + console.log("upgrade"); |
| 78 | + proxy.ws(req, socket, head, { |
| 79 | + target: { |
| 80 | + host: 'localhost', |
| 81 | + port: 8001 |
| 82 | + } |
| 83 | + }); |
| 84 | +}); |
| 85 | + |
| 86 | +server.listen(8080, function(){ |
| 87 | + console.log('listening on *:8080'); |
| 88 | +}); |
0 commit comments