ensl_gathers/config/socketio.js

84 lines
2.2 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");
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-12-29 16:26:11 +00:00
var eventController = require("../lib/event/controller");
2015-08-18 11:40:48 +00:00
var usersHelper = require("../lib/user/helper");
var env = process.env.NODE_ENV || "development";
2015-08-18 11:09:33 +00:00
var parseCookies = EnslClient.parseCookies;
2015-08-18 09:56:35 +00:00
2015-08-18 11:40:48 +00:00
var assignRandomUser = (socket, next) => {
2015-08-28 20:37:55 +00:00
usersHelper.getRandomUser(function (error, user) {
2015-08-18 11:40:48 +00:00
if (error) {
winston.error(error);
return next(new Error("Authentication Failed"))
}
2015-08-28 20:37:55 +00:00
socket._user = user;
2015-08-18 11:40:48 +00:00
return next();
});
};
2020-07-21 18:30:01 +00:00
var assignFixedUser = (socket, next, userId) => {
usersHelper.getFixedUser(userId, function (error, user) {
if (error) {
winston.error(error);
return next(new Error("Authentication Failed"))
}
socket._user = user;
return next();
});
};
var handleFailedAuth = (socket, next) => {
if (process.env.RANDOM_USER) {
return assignRandomUser(socket, next);
2020-07-21 18:30:01 +00:00
} else if (process.env.FIXED_USER) {
return assignFixedUser(socket, next, process.env.FIXED_USER);
} else {
return next(new Error("Authentication Failed"));
}
};
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-19 13:59:28 +00:00
let cookies = parseCookies(socket);
if (!cookies) {
return handleFailedAuth(socket, next);
2015-08-19 13:59:28 +00:00
}
2015-08-18 09:56:35 +00:00
let session = cookies[config.session_store_name];
if (!session) {
return handleFailedAuth(socket, next);
2015-08-18 11:40:48 +00:00
}
2015-08-18 09:56:35 +00:00
EnslClient.decodeSession(session, function (error, userId) {
if (error) return handleFailedAuth(socket, next);
User.find(userId, (error, user) => {
if (error) {
winston.error(error);
return next(new Error("Authentication failed"));
}
socket._user = user;
if (socket._user.bans.gather) return next(new Error("Gather Banned"));
winston.info("Logged in:", user.username, user.id);
return next();
});
2015-08-18 09:56:35 +00:00
});
2015-07-21 00:24:14 +00:00
});
userController(rootNamespace);
chatController(rootNamespace);
gatherController(rootNamespace);
2015-12-29 16:26:11 +00:00
eventController(rootNamespace);
};