ensl_gathers/lib/user/controller.js

99 lines
2.2 KiB
JavaScript
Raw Normal View History

"use strict";
/*
* User Controller
*
* Server API
2015-07-29 10:46:30 +00:00
* users:update - Update list of users
*
* Client API
2015-07-29 10:46:30 +00:00
* users:online - User is on the page
* users:away - User is away from page
2015-08-18 09:56:35 +00:00
* users:authorize - Sign on with arbitary user ID (to be enabled for admin only)
2015-07-29 10:46:30 +00:00
* users:refresh - Request new user list
*
*/
var userCache = {};
2015-07-22 23:30:14 +00:00
var User = require("./user");
var winston = require("winston");
2015-08-18 09:56:35 +00:00
var mongoose = require("mongoose");
var Session = mongoose.model("Session");
2015-07-22 23:30:14 +00:00
var enslClient = require("../ensl/client")();
2015-07-29 13:50:39 +00:00
var _ = require("lodash");
2015-08-18 09:56:35 +00:00
module.exports = namespace => {
var refreshUsers = socket => {
var receivers = (socket !== undefined) ? [socket] : namespace.sockets;
var newCache = {};
for(let socketid in namespace.sockets) {
let socket = namespace.sockets[socketid];
var user = socket._user;
newCache[user.id] = user;
}
userCache = newCache;
var users = [];
for (var id in userCache) {
if (userCache.hasOwnProperty(id)) {
users.push(userCache[id]);
}
}
for(let socketid in receivers) {
let socket = receivers[socketid];
socket.emit('users:update', {
2015-07-27 11:55:36 +00:00
count: users.length,
users: users,
currentUser: socket._user
});
}
};
2015-08-18 09:56:35 +00:00
namespace.on('connection', socket => {
refreshUsers();
2015-07-27 11:55:36 +00:00
socket.on('users:refresh', refreshUsers.bind(null, socket));
2015-08-28 20:28:50 +00:00
socket.on('users:update:profile', data => {
if (socket._user.id !== data.id) return;
socket._user.updateProfile(data.profile, function (error) {
if (error) {
winston.error(error);
return;
}
refreshUsers();
});
});
2015-11-15 16:26:32 +00:00
socket.on('users:disconnect', data => {
const id = data.id;
if (typeof id !== 'number') return;
Object.values(namespace.sockets)
2015-11-15 16:26:32 +00:00
.filter(socket => socket._user.id === id)
.forEach(socket => socket.disconnect());
});
2015-08-18 09:56:35 +00:00
socket.on("users:authorize", data => {
2015-10-20 22:40:40 +00:00
if (!socket._user.isUserAdmin()) return;
var id = parseInt(data.id, 10);
if (isNaN(id)) return;
User.find(id, (error, user) => {
if (error) {
winston.error(error);
2015-10-18 15:29:47 +00:00
return null;
}
socket._user = user;
winston.info("Logged in:", user.username, user.id);
refreshUsers();
});
});
2015-08-18 09:56:35 +00:00
socket.on('disconnect', socket => { refreshUsers(); });
});
};