1 var Server = require("./server");
2 var util = require("./utilities");
3 var db = require("./database");
4 var Config = require("./config");
5 var ACP = require("./acp");
6 var Account = require("./account");
7 var Flags = require("./flags");
8 import { EventEmitter } from 'events';
9 import Logger from './logger';
10 import net from 'net';
12 const LOGGER = require('@calzoneman/jsli')('user');
14 function User(socket, ip, loginInfo) {
17 // Expanding IPv6 addresses shouldn't really be necessary
18 // At some point, the IPv6 related stuff should be revisited
19 this.realip = net.isIPv6(ip) ? util.expandIPv6(ip) : ip;
20 this.displayip = util.cloakIP(this.realip);
22 this.queueLimiter = util.newRateLimiter();
23 this.chatLimiter = util.newRateLimiter();
24 this.reqPlaylistLimiter = util.newRateLimiter();
25 this.awaytimer = false;
28 this.account = new Account.Account(this.realip, loginInfo, socket.context.aliases);
29 this.registrationTime = new Date(this.account.user.time);
30 this.setFlag(Flags.U_REGISTERED | Flags.U_LOGGED_IN | Flags.U_READY);
31 socket.emit("login", {
36 socket.emit("rank", this.account.effectiveRank);
37 if (this.account.globalRank >= 255) {
38 this.initAdminCallbacks();
40 this.emit("login", this.account);
41 LOGGER.info(ip + " logged in as " + this.getName());
43 this.account = new Account.Account(this.realip, null, socket.context.aliases);
44 socket.emit("rank", -1);
45 this.setFlag(Flags.U_READY);
46 this.once("login", account => {
47 if (account.globalRank >= 255) {
48 this.initAdminCallbacks();
53 socket.once("joinChannel", data => this.handleJoinChannel(data));
54 socket.once("initACP", () => this.handleInitACP());
55 socket.on("login", data => this.handleLogin(data));
58 User.prototype = Object.create(EventEmitter.prototype);
60 User.prototype.handleJoinChannel = function handleJoinChannel(data) {
61 if (typeof data !== "object" || typeof data.name !== "string") {
65 if (this.inChannel()) {
69 if (!util.isValidChannelName(data.name)) {
70 this.socket.emit("errorMsg", {
71 msg: "Invalid channel name. Channel names may consist of 1-30 " +
72 "characters in the set a-z, A-Z, 0-9, -, and _"
74 this.kick("Invalid channel name");
78 data.name = data.name.toLowerCase();
79 if (data.name in Config.get("channel-blacklist")) {
80 this.kick("This channel is blacklisted.");
84 this.waitFlag(Flags.U_READY, () => {
87 chan = Server.getServer().getChannel(data.name);
89 if (error.code === 'EWRONGPART') {
90 this.socket.emit("errorMsg", {
91 msg: "Channel '" + data.name + "' is hosted on another server. " +
92 "Try refreshing the page to update the connection URL."
95 LOGGER.error("Unexpected error from getChannel(): %s", error.stack);
96 this.socket.emit("errorMsg", {
97 msg: "Unable to join channel due to an internal error"
103 if (!chan.is(Flags.C_READY)) {
104 chan.once("loadFail", reason => {
105 this.socket.emit("errorMsg", {
109 this.kick(`Channel could not be loaded: ${reason}`);
112 chan.joinUser(this, data);
116 User.prototype.handleInitACP = function handleInitACP() {
117 this.waitFlag(Flags.U_LOGGED_IN, () => {
118 if (this.account.globalRank >= 255) {
121 this.kick("Attempted initACP from non privileged user. This incident " +
122 "will be reported.");
123 Logger.eventlog.log("[acp] Attempted initACP from socket client " +
124 this.getName() + "@" + this.realip);
129 User.prototype.handleLogin = function handleLogin(data) {
130 if (typeof data !== "object") {
131 this.socket.emit("errorMsg", {
132 msg: "Invalid login frame"
137 var name = data.name;
138 if (typeof name !== "string") {
142 var pw = data.pw || "";
143 if (typeof pw !== "string") {
147 if (this.is(Flags.U_LOGGING_IN) || this.is(Flags.U_LOGGED_IN)) {
152 this.guestLogin(name);
154 this.login(name, pw);
158 User.prototype.die = function () {
159 for (const key in this.socket._events) {
160 delete this.socket._events[key];
163 delete this.socket.typecheckedOn;
164 delete this.socket.typecheckedOnce;
166 for (const key in this.__evHandlers) {
167 delete this.__evHandlers[key];
170 if (this.awaytimer) {
171 clearTimeout(this.awaytimer);
177 User.prototype.is = function (flag) {
178 return Boolean(this.flags & flag);
181 User.prototype.setFlag = function (flag) {
183 this.emit("setFlag", flag);
186 User.prototype.clearFlag = function (flag) {
188 this.emit("clearFlag", flag);
191 User.prototype.waitFlag = function (flag, cb) {
196 var wait = function (f) {
198 self.removeListener("setFlag", wait);
202 self.on("setFlag", wait);
206 User.prototype.getName = function () {
207 return this.account.name;
210 User.prototype.getLowerName = function () {
211 return this.account.lowername;
214 User.prototype.inChannel = function () {
215 return this.channel != null && !this.channel.dead;
218 User.prototype.inRegisteredChannel = function () {
219 return this.inChannel() && this.channel.is(Flags.C_REGISTERED);
222 /* Called when a user's AFK status changes */
223 User.prototype.setAFK = function (afk) {
224 if (!this.inChannel()) {
228 /* No change in AFK status, don't need to change anything */
229 if (this.is(Flags.U_AFK) === afk) {
235 this.setFlag(Flags.U_AFK);
236 if (this.channel.modules.voteskip) {
237 this.channel.modules.voteskip.unvote(this.realip);
238 this.socket.emit("clearVoteskipVote");
241 this.clearFlag(Flags.U_AFK);
245 if (!this.inChannel()) {
247 * In unusual circumstances, the above emit("clearVoteskipVote")
248 * can cause the "disconnect" event to be fired synchronously,
249 * which results in this user no longer being in the channel.
254 /* Number of AFK users changed, voteskip state changes */
255 if (this.channel.modules.voteskip) {
256 this.channel.modules.voteskip.update();
259 this.emit('afk', afk);
262 /* Automatically tag a user as AFK after a period of inactivity */
263 User.prototype.autoAFK = function () {
265 if (self.awaytimer) {
266 clearTimeout(self.awaytimer);
269 if (!self.inChannel() || !self.channel.modules.options) {
273 /* Don't set a timer if the duration is invalid */
274 var timeout = parseFloat(self.channel.modules.options.get("afk_timeout"));
275 if (isNaN(timeout) || timeout <= 0) {
279 self.awaytimer = setTimeout(function () {
284 User.prototype.kick = function (reason) {
285 this.socket.emit("kick", { reason: reason });
286 this.socket.disconnect();
289 User.prototype.isAnonymous = function(){
291 return !self.is(Flags.U_LOGGED_IN);
294 User.prototype.initAdminCallbacks = function () {
296 self.socket.on("borrow-rank", function (rank) {
297 if (self.inChannel()) {
298 if (typeof rank !== "number") {
302 if (rank > self.account.globalRank) {
306 if (rank === 255 && self.account.globalRank > 255) {
307 rank = self.account.globalRank;
310 self.account.channelRank = rank;
311 self.account.effectiveRank = rank;
312 self.socket.emit("rank", rank);
313 self.channel.broadcastAll("setUserRank", {
314 name: self.getName(),
321 User.prototype.login = function (name, pw) {
323 self.setFlag(Flags.U_LOGGING_IN);
325 db.users.verifyLogin(name, pw, function (err, user) {
327 if (err === "Invalid username/password combination") {
328 Logger.eventlog.log("[loginfail] Login failed (bad password): " + name
329 + "@" + self.realip);
332 self.socket.emit("login", {
336 self.clearFlag(Flags.U_LOGGING_IN);
340 const oldRank = self.account.effectiveRank;
341 self.account.user = user;
342 self.account.update();
343 self.socket.emit("rank", self.account.effectiveRank);
344 self.emit("effectiveRankChange", self.account.effectiveRank, oldRank);
345 self.registrationTime = new Date(user.time);
346 self.setFlag(Flags.U_REGISTERED);
347 self.socket.emit("login", {
351 db.recordVisit(self.realip, self.getName());
352 LOGGER.info(self.realip + " logged in as " + user.name);
353 self.setFlag(Flags.U_LOGGED_IN);
354 self.clearFlag(Flags.U_LOGGING_IN);
355 self.emit("login", self.account);
359 var lastguestlogin = {};
360 User.prototype.guestLogin = function (name) {
363 if (!self.channel.modules.options.get("allow_anon_chat") && self.realip in lastguestlogin) {
364 var diff = (Date.now() - lastguestlogin[self.realip]) / 1000;
365 if (diff < Config.get("guest-login-delay")) {
366 self.socket.emit("login", {
368 error: "Guest logins are restricted to one per IP address per " +
369 Config.get("guest-login-delay") + " seconds."
375 if (!util.isValidUserName(name)) {
376 self.socket.emit("login", {
378 error: "Invalid username. Usernames must be 1-20 characters long and " +
379 "consist only of characters a-z, A-Z, 0-9, -, or _."
384 if (!self.channel.modules.options.get("allow_anon_chat") && name.match(Config.get("reserved-names.usernames"))) {
386 'Rejecting attempt by %s to use reserved username "%s"',
390 self.socket.emit("login", {
392 error: "That username is reserved."
397 // Prevent duplicate logins
398 self.setFlag(Flags.U_LOGGING_IN);
399 db.users.isUsernameTaken(name, function (err, taken) {
400 self.clearFlag(Flags.U_LOGGING_IN);
402 self.socket.emit("login", {
410 self.socket.emit("login", {
412 error: "That username is registered."
417 if (!self.channel.modules.options.get("allow_anon_chat") && self.inChannel()) {
418 var nameLower = name.toLowerCase();
419 for (var i = 0; i < self.channel.users.length; i++) {
420 if (self.channel.users[i].getLowerName() === nameLower) {
421 self.socket.emit("login", {
423 error: "That name is already in use on this channel."
430 lastguestlogin[self.realip] = Date.now();
432 const oldRank = self.account.effectiveRank;
433 self.account.guestName = name;
434 self.account.update();
435 self.socket.emit("rank", self.account.effectiveRank);
436 self.emit("effectiveRankChange", self.account.effectiveRank, oldRank);
437 self.socket.emit("login", {
442 db.recordVisit(self.realip, self.getName());
443 LOGGER.info(self.realip + " signed in as " + name);
444 self.setFlag(Flags.U_LOGGED_IN);
445 self.emit("login", self.account);
449 /* Clean out old login throttlers to save memory */
450 setInterval(function () {
451 var delay = Config.get("guest-login-delay");
452 for (var ip in lastguestlogin) {
453 var diff = (Date.now() - lastguestlogin[ip]) / 1000;
455 delete lastguestlogin[ip];
459 if (Config.get("aggressive-gc") && global && global.gc) {
464 User.prototype.getFirstSeenTime = function getFirstSeenTime() {
465 if (this.registrationTime && this.socket.context.ipSessionFirstSeen) {
467 this.registrationTime.getTime(),
468 this.socket.context.ipSessionFirstSeen.getTime()
470 } else if (this.registrationTime) {
471 return this.registrationTime.getTime();
472 } else if (this.socket.context.ipSessionFirstSeen) {
473 return this.socket.context.ipSessionFirstSeen.getTime();
475 LOGGER.error(`User "${this.getName()}" (IP: ${this.realip}) has neither ` +
476 "an IP session first seen time nor a registered account.");
481 User.prototype.setChannelRank = function setRank(rank) {
482 const oldRank = this.account.effectiveRank;
483 const changed = oldRank !== rank;
484 this.account.channelRank = rank;
485 this.account.update();
486 this.socket.emit("rank", this.account.effectiveRank);
488 this.emit("effectiveRankChange", this.account.effectiveRank, oldRank);
492 module.exports = User;