Jelajahi Sumber

Made sessions functional, logging in works again.

KrisVos130 8 tahun lalu
induk
melakukan
b5f529ae8b

+ 30 - 45
backend/logic/actions/stations.js

@@ -10,8 +10,6 @@ const cache = require('../cache');
 const notifications = require('../notifications');
 const utils = require('../utils');
 
-let stationsLoaded = {};
-
 notifications.subscribe('station.locked', function(stationName) {
 	io.to(`station.${stationName}`).emit("event:station.locked");
 });
@@ -57,36 +55,33 @@ function initializeAndReturnStation (stationId, cb) {
 		if (err && err !== true) return cb(err);
 
 		// get notified when the next song for this station should play, so that we can notify our sockets
-		if (stationsLoaded[stationId] === undefined) {
-			stationsLoaded[stationId] = 1;
-			let notification = notifications.subscribe(`stations.nextSong?id=${station.id}`, () => {
-				// get the station from the cache
-				cache.hget('stations', station.name, (err, station) => {
-					if (station) {
-						console.log(777);
-						// notify all the sockets on this station to go to the next song
-						io.to(`station.${stationId}`).emit("event:songs.next", {
-							currentSong: station.currentSong,
-							startedAt: station.startedAt,
-							paused: station.paused,
-							timePaused: 0
-						});
-						// schedule a notification to be dispatched when the next song ends
-						notifications.schedule(`stations.nextSong?id=${station.id}`, station.currentSong.duration * 1000);
-					}
-					// the station doesn't exist anymore, unsubscribe from it
-					else {
-						console.log(888);
-						notifications.remove(notification);
-						delete stationsLoaded[stationId];
-					}
-				});
-			}, true);
-
-			if (!station.paused) {
-				console.log(station);
-				notifications.schedule(`stations.nextSong?id=${station.id}`, station.currentSong.duration * 1000);
-			}
+		let notification = notifications.subscribe(`stations.nextSong?id=${station.id}`, () => {
+			// get the station from the cache
+			console.log('NOTIFICATION');
+			cache.hget('stations', station.name, (err, station) => {
+				if (station) {
+					console.log(777);
+					// notify all the sockets on this station to go to the next song
+					io.to(`station.${stationId}`).emit("event:songs.next", {
+						currentSong: station.currentSong,
+						startedAt: station.startedAt,
+						paused: station.paused,
+						timePaused: 0
+					});
+					// schedule a notification to be dispatched when the next song ends
+					notifications.schedule(`stations.nextSong?id=${station.id}`, station.currentSong.duration * 1000);
+				}
+				// the station doesn't exist anymore, unsubscribe from it
+				else {
+					console.log(888);
+					notifications.remove(notification);
+				}
+			});
+		}, true);
+
+		if (!station.paused) {
+			console.log(station);
+			notifications.schedule(`stations.nextSong?id=${station.id}`, station.currentSong.duration * 1000);
 		}
 
 		return cb(null, station);
@@ -143,20 +138,12 @@ module.exports = {
 	/**
 	 * Joins the station by its id
 	 *
-	 * @param session
+	 * @param sessionId
 	 * @param stationId - the station id
 	 * @param cb
 	 * @return {{ status: String, userCount: Integer }}
 	 */
-	join: (session, stationId, cb) => {
-		let ns = io.io.of("/");
-		if (ns) {
-			for (let id in ns.connected) {
-				console.log(ns.connected[id]);
-				console.log(ns.connected[id].testProp);
-			}
-		}
-
+	join: (sessionId, stationId, cb) => {
 
 		initializeAndReturnStation(stationId, (err, station) => {
 
@@ -166,13 +153,11 @@ module.exports = {
 
 			if (station) {
 
-				if (session) session.stationId = stationId;
-
 				//TODO Loop through all sockets, see if socket with same session exists, and if so leave all other station rooms and join this stationRoom
 
 				cache.client.hincrby('station.userCounts', stationId, 1, (err, userCount) => {
 					if (err) return cb({ status: 'error', message: 'An error occurred while joining the station' });
-					utils.socketJoinRoom(session);
+					utils.socketJoinRoom(sessionId);
 					//TODO Emit to cache, listen on cache
 					cb({ status: 'success', currentSong: station.currentSong, startedAt: station.startedAt, paused: station.paused, timePaused: station.timePaused });
 				});

+ 7 - 5
backend/logic/actions/users.js

@@ -35,7 +35,9 @@ module.exports = {
 						let userSessionId = utils.guid();
 						cache.hset('userSessions', userSessionId, cache.schemas.userSession(user._id), (err) => {
 							if (!err) {
+								console.log(sessionId, 222);
 								cache.hget('sessions', sessionId, (err, session) => {
+									console.log(err, session, 333);
 									session.userSessionId = userSessionId;
 									cache.hset('sessions', sessionId, session, (err) => {
 										next(null, { status: 'success', message: 'Login successful', user, SID: userSessionId });
@@ -68,7 +70,7 @@ module.exports = {
 		async.waterfall([
 
 			// verify the request with google recaptcha
-			(next) => {
+			/*(next) => {
 				request({
 					url: 'https://www.google.com/recaptcha/api/siteverify',
 					method: 'POST',
@@ -77,13 +79,13 @@ module.exports = {
 						'response': recaptcha
 					}
 				}, next);
-			},
+			},*/
 
 			// check if the response from Google recaptcha is successful
 			// if it is, we check if a user with the requested username already exists
-			(response, body, next) => {
-				let json = JSON.parse(body);
-				console.log(json);
+			(/*response, body, */next) => {
+				/*let json = JSON.parse(body);
+				console.log(json);*/
 				//if (json.success !== true) return next('Response from recaptcha was not successful');
 				db.models.user.findOne({ username }, next);
 			},

+ 14 - 0
backend/logic/cache/index.js

@@ -79,6 +79,20 @@ const lib = {
 		});
 	},
 
+	/**
+	 * Deletes a single value from a table
+	 *
+	 * @param {String} table - name of the table to delete the value from (table === redis hash)
+	 * @param {String} key - name of the key to delete
+	 * @param {Function} cb - gets called when the value has been deleted from Redis or when it returned an error
+	 */
+	hdel: (table, key, cb) => {
+		lib.client.hdel(table, key, (err) => {
+			if (err) return typeof cb === 'function' ? cb(err) : null;
+			if (typeof cb === 'function') cb(null);
+		});
+	},
+
 	/**
 	 * Returns all the keys for a table
 	 *

+ 1 - 1
backend/logic/cache/schemas/session.js

@@ -9,7 +9,7 @@
 module.exports = (userSessionId) => {
 	return {
 		stationId: null,
-		userSessionId,
+		userSessionId: userSessionId,
 		created: Date.now()
 	};
 };

+ 7 - 5
backend/logic/io.js

@@ -22,9 +22,11 @@ module.exports = {
 
 			cache.hget('userSessions', SID, (err, userSession) => {
 				console.log(err, userSession);
+				if (err) {
+					SID = null;
+				}
 				let sessionId = utils.guid();
-				cache.hset('sessions', sessionId, cache.schemas.session(), (err, session) => {
-					console.log(err, session);
+				cache.hset('sessions', sessionId, cache.schemas.session(SID), (err) => {
 					socket.sessionId = sessionId;
 					return next();
 				});
@@ -41,8 +43,8 @@ module.exports = {
 				// remove the user from their current station (if any)
 				if (socket.sessionId) {
 					//actions.stations.leave(socket.sessionId, result => {});
-					//TODO Delete session
-					delete socket.sessionId;
+					// Remove session from Redis
+					cache.hdel('sessions', socket.sessionId);
 				}
 
 				console.log('io: User has disconnected');
@@ -77,7 +79,7 @@ module.exports = {
 							if (socket.sessionId && session === null) delete socket.sessionId;
 
 							// call the action, passing it the session, and the arguments socket.io passed us
-							actions[namespace][action].apply(null, [session].concat(args).concat([
+							actions[namespace][action].apply(null, [socket.sessionId].concat(args).concat([
 								(result) => {
 									// store the session id
 									//if (name == 'users.login' && result.user) socket.sessionId = result.user.sessionId;

+ 8 - 8
backend/logic/utils.js

@@ -129,26 +129,26 @@ module.exports = {
 		}
 	},
 	socketFromSession: function(sessionId) {
-		let sockets = io.io.sockets;
-		for (let i = 0; i < sockets.length; i++) {
-			let socket = sockets[i];
-			if (socket.sessionId === sessionId) {
-				return socket;
+		let ns = io.io.of("/");
+		if (ns) {
+			for (let id in ns.connected) {
+				if (ns.connected[id].sessionId === sessionId) {
+					return ns.connected[id];
+				}
 			}
 		}
 	},
 	socketLeaveRooms: function(sessionId, room) {
 		let socket = this.socketFromSession(sessionId);
-		let rooms = io.sockets.manager.roomClients[socket.id];
+		let rooms = socket.rooms;
 		for (let j = 0; j < rooms.length; j++) {
 			socket.leave(rooms[j]);
 		}
 	},
 	socketJoinRoom: function(sessionId, room) {
 		let socket = this.socketFromSession(sessionId);
-		console.log(socket);
 		//console.log(io.io.sockets[socket.id]);
-		let rooms = io.io.sockets.manager.roomClients[socket.id];
+		let rooms = socket.rooms;
 		for (let j = 0; j < rooms.length; j++) {
 			socket.leave(rooms[j]);
 		}

+ 1 - 1
frontend/App.vue

@@ -51,7 +51,7 @@
 		events: {
 			'register': function () {
 				let { register: { email, username, password } } = this;
-				this.socket.emit('users.register', username, email, password, grecaptcha.getResponse(), result => {
+				this.socket.emit('users.register', username, email, password, /*grecaptcha.getResponse()*/null, result => {
 					Toast.methods.addToast(`User ${username} has been registered`, 2000);
 					setTimeout(location.reload(), 2500);
 				});