ensl_gathers/config/socketio.js

63 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-07-20 09:41:58 +00:00
"use strict";
2015-07-22 15:35:40 +00:00
var winston = require("winston");
2015-07-22 23:30:14 +00:00
var User = require("../lib/user/user");
2015-08-18 09:56:35 +00:00
var config = require("./config");
var EnslClient = require("../lib/ensl/client");
var client = EnslClient();
2015-07-22 23:30:14 +00:00
var chatController = require("../lib/chat/controller");
var gatherController = require("../lib/gather/controller");
var userController = require("../lib/user/controller");
2015-07-21 14:10:24 +00:00
2015-08-10 23:56:53 +00:00
var getRandomUser = callback => {
2015-08-18 09:56:35 +00:00
let id = Math.floor(Math.random() * 5000) + 1;
2015-07-27 11:55:36 +00:00
client.getUserById({
id: id
2015-08-10 23:56:53 +00:00
}, (error, response, body) => {
2015-07-27 11:55:36 +00:00
if (response.statusCode !== 200) return getRandomUser(callback);
return callback(error, response, body);
});
};
2015-07-26 11:54:35 +00:00
2015-08-18 09:56:35 +00:00
var parseCookies = (socket) => {
let cookieString = socket.request.headers.cookie;
if (typeof cookieString !== 'string') return null;
let cookies = socket.request.headers.cookie.split(";")
.map(cookie => cookie.trim())
.reduce((acc, cookie) => {
let values = cookie.split("=");
let attr = values[0];
let val = values[1];
if (attr && val) acc[attr] = val;
return acc;
}, {})
return cookies;
};
2015-08-10 23:56:53 +00:00
module.exports = io => {
var rootNamespace = io.of('/')
2015-08-18 09:56:35 +00:00
// Authentication
2015-08-10 23:56:53 +00:00
io.use((socket, next) => {
2015-08-18 09:56:35 +00:00
let session = EnslClient.decodeSession(parseCookies(socket)[config.session_store_name]);
if (!session || typeof session.user !== 'number') return next(new Error("Authentication Failed"));
client.getUserById({
id: session.user
}, (error, response, body) => {
2015-08-18 10:40:15 +00:00
if (error || response.statusCode !== 200) {
2015-07-22 15:35:40 +00:00
winston.error(error);
return next(new Error("Authentication Failed"))
2015-07-22 15:35:40 +00:00
};
2015-07-22 23:30:14 +00:00
socket._user = new User(body);
2015-08-18 09:56:35 +00:00
winston.info("Logged in:", body.username, body.id);
return next();
});
2015-07-21 00:24:14 +00:00
});
userController(rootNamespace);
chatController(rootNamespace);
gatherController(rootNamespace);
};