2
0
Эх сурвалжийг харах

Redesigned session system, fixed some bugs.

KrisVos130 8 жил өмнө
parent
commit
7442a38844

+ 2 - 2
backend/logic/actions/apis.js

@@ -35,9 +35,9 @@ module.exports = {
 		});
 	},
 
-	joinRoom: (sessionId, page, cb) => {
+	joinRoom: (session, page, cb) => {
 		if (page === 'home') {
-			utils.socketJoinRoom(sessionId, page);
+			utils.socketJoinRoom(session.socketId, page);
 		}
 		cb({});
 	}

+ 8 - 11
backend/logic/actions/hooks/adminRequired.js

@@ -2,22 +2,19 @@ const cache = require('../../cache');
 const db = require('../../db');
 
 module.exports = function(next) {
-	return function(sessionId) {
+	return function(session) {
 		let args = [];
 		for (let prop in arguments) {
 			args.push(arguments[prop]);
 		}
 		let cb = args[args.length - 1];
-		cache.hget('sessions', sessionId, (err, session) => {
-			if (err || !session || !session.userSessionId) return cb({ status: 'failure', message: 'Login required.' });
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				if (err || !userSession || !userSession.userId) return cb({ status: 'failure', message: 'Login required.' });
-				db.models.user.findOne({_id: userSession.userId}, (err, user) => {
-					if (err || !user) return cb({ status: 'failure', message: 'Login required.' });
-					if (user.role !== 'admin') return cb({ status: 'failure', message: 'Admin required.' });
-					args.push(userSession.userId);
-					next.apply(null, args);
-				});
+		cache.hget('sessions', session.sessionId, (err, session) => {
+			if (err || !session || !session.userId) return cb({ status: 'failure', message: 'Login required.' });
+			db.models.user.findOne({_id: session.userId}, (err, user) => {
+				if (err || !user) return cb({ status: 'failure', message: 'Login required.' });
+				if (user.role !== 'admin') return cb({ status: 'failure', message: 'Admin required.' });
+				args.push(session.userId);
+				next.apply(null, args);
 			});
 		});
 	}

+ 5 - 8
backend/logic/actions/hooks/loginRequired.js

@@ -1,19 +1,16 @@
 const cache = require('../../cache');
 
 module.exports = function(next) {
-	return function(sessionId) {
+	return function(session) {
 		let args = [];
 		for (let prop in arguments) {
 			args.push(arguments[prop]);
 		}
 		let cb = args[args.length - 1];
-		cache.hget('sessions', sessionId, (err, session) => {
-			if (err || !session || !session.userSessionId) return cb({ status: 'failure', message: 'Login required.' });
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				if (err || !userSession || !userSession.userId) return cb({ status: 'failure', message: 'Login required.' });
-				args.push(userSession.userId);
-				next.apply(null, args);
-			});
+		cache.hget('sessions', session.sessionId, (err, session) => {
+			if (err || !session || !session.userId) return cb({ status: 'failure', message: 'Login required.' });
+			args.push(session.userId);
+			next.apply(null, args);
 		});
 	}
 };

+ 3 - 4
backend/logic/actions/queueSongs.js

@@ -50,14 +50,13 @@ module.exports = {
 
 	remove: hooks.adminRequired((session, _id, cb) => {
 		// TODO Require admin/login
-		db.models.queueSong.find({ _id }).remove().exec();
+		db.models.queueSong.remove({ _id });
 		return cb({ status: 'success', message: 'Song was removed successfully' });
 	}),
 
-	add: hooks.loginRequired((session, id, cb) => {
+	add: hooks.loginRequired((session, id, cb, userId) => {
 		//TODO Check if id is valid
 		//TODO Check if id is already in queue/rotation
-		// if (!session.logged_in) return cb({ status: 'failure', message: 'You must be logged in to add a song' });
 
 		let requestedAt = Date.now();
 
@@ -108,7 +107,7 @@ module.exports = {
 						skipDuration: 0,
 						thumbnail: '',
 						explicit: false,
-						requestedBy: 'temp',
+						requestedBy: userId,
 						requestedAt
 					};
 

+ 62 - 88
backend/logic/actions/songs.js

@@ -52,20 +52,18 @@ module.exports = {
 		});
 	},
 
-	update: hooks.adminRequired((session, id, song, cb) => {
-		db.models.song.findOneAndUpdate({ id }, song, { upsert: true }, (err, updatedSong) => {
+	update: hooks.adminRequired((session, songId, song, cb) => {
+		db.models.song.findOneAndUpdate({ _id: songId }, song, { upsert: true }, (err, updatedSong) => {
 			if (err) throw err;
 			return cb({ status: 'success', message: 'Song has been successfully updated', data: updatedSong });
 		});
 	}),
 
-	remove: hooks.adminRequired((session, _id, cb) => {
-		//TODO Require admin/login
-		db.models.song.find({ _id }).remove().exec();
+	remove: hooks.adminRequired((session, songId, cb) => {
+		db.models.song.remove({ _id: songId });
 	}),
 
 	add: hooks.adminRequired((session, song, cb) => {
-		//TODO Require admin/login
 		const newSong = new db.models.song(song);
 		db.models.song.findOne({ _id: song._id }, (err, existingSong) => {
 			if (err) throw err;
@@ -77,117 +75,93 @@ module.exports = {
 		//TODO Check if video is in queue and Add the song to the appropriate stations
 	}),
 
-	like: hooks.loginRequired((sessionId, songId, cb) => {
-		cache.hget('sessions', sessionId, (err, session) => {
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				db.models.user.findOne({ _id: userSession.userId }, (err, user) => {
-					if (user.liked.indexOf(songId) !== -1) return cb({ status: 'failure', message: 'You have already liked this song.' });
-					let dislikes = 0;
-					if (user.disliked.indexOf(songId) !== -1) dislikes = -1;
-					db.models.song.update({ _id: songId }, { $inc: { likes: 1, dislikes: dislikes } }, err => {
+	like: hooks.loginRequired((session, songId, cb) => {
+		db.models.user.findOne({ _id: userId }, (err, user) => {
+			if (user.liked.indexOf(songId) !== -1) return cb({ status: 'failure', message: 'You have already liked this song.' });
+			let dislikes = 0;
+			if (user.disliked.indexOf(songId) !== -1) dislikes = -1;
+			db.models.song.update({ _id: songId }, { $inc: { likes: 1, dislikes: dislikes } }, err => {
+				if (!err) {
+					db.models.user.update({_id: userId}, {$push: {liked: songId}, $pull: {disliked: songId}}, err => {
 						if (!err) {
-							db.models.user.update({_id: userSession.userId}, {$push: {liked: songId}, $pull: {disliked: songId}}, err => {
-								if (!err) {
-									console.log(JSON.stringify({ songId, userId: userSession.userId }));
-									songs.updateSong(songId, (err, song) => {});
-									cache.pub('song.like', JSON.stringify({ songId, userId: userSession.userId, undisliked: (dislikes === -1) }));
-								} else db.models.song.update({ _id: songId }, { $inc: { likes: -1, dislikes: -dislikes } }, err => {
-									return cb({ status: 'failure', message: 'Something went wrong while liking this song.' });
-								});
-							});
-						} else {
+							console.log(JSON.stringify({ songId, userId: userId }));
+							songs.updateSong(songId, (err, song) => {});
+							cache.pub('song.like', JSON.stringify({ songId, userId: session.userId, undisliked: (dislikes === -1) }));
+						} else db.models.song.update({ _id: songId }, { $inc: { likes: -1, dislikes: -dislikes } }, err => {
 							return cb({ status: 'failure', message: 'Something went wrong while liking this song.' });
-						}
+						});
 					});
-				});
+				} else {
+					return cb({ status: 'failure', message: 'Something went wrong while liking this song.' });
+				}
 			});
 		});
 	}),
 
-	dislike: hooks.loginRequired((sessionId, songId, cb) => {
-		cache.hget('sessions', sessionId, (err, session) => {
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				db.models.user.findOne({_id: userSession.userId}, (err, user) => {
-					if (user.disliked.indexOf(songId) !== -1) return cb({ status: 'failure', message: 'You have already disliked this song.' });
-					let likes = 0;
-					if (user.liked.indexOf(songId) !== -1) likes = -1;
-					db.models.song.update({_id: songId}, {$inc: {likes: likes, dislikes: 1}}, (err) => {
+	dislike: hooks.loginRequired((session, songId, cb, userId) => {
+		db.models.user.findOne({_id: userId}, (err, user) => {
+			if (user.disliked.indexOf(songId) !== -1) return cb({ status: 'failure', message: 'You have already disliked this song.' });
+			let likes = 0;
+			if (user.liked.indexOf(songId) !== -1) likes = -1;
+			db.models.song.update({_id: songId}, {$inc: {likes: likes, dislikes: 1}}, (err) => {
+				if (!err) {
+					db.models.user.update({_id: userId}, {$push: {disliked: songId}, $pull: {liked: songId}}, (err) => {
 						if (!err) {
-							db.models.user.update({_id: userSession.userId}, {$push: {disliked: songId}, $pull: {liked: songId}}, (err) => {
-								if (!err) {
-									songs.updateSong(songId, (err, song) => {});
-									cache.pub('song.dislike', JSON.stringify({songId, userId: userSession.userId, unliked: (likes === -1)}));
-								} else db.models.song.update({_id: songId}, {$inc: {likes: -likes, dislikes: -1}}, (err) => {
-									return cb({ status: 'failure', message: 'Something went wrong while disliking this song.' });
-								});
-							});
-						} else {
+							songs.updateSong(songId, (err, song) => {});
+							cache.pub('song.dislike', JSON.stringify({songId, userId: userId, unliked: (likes === -1)}));
+						} else db.models.song.update({_id: songId}, {$inc: {likes: -likes, dislikes: -1}}, (err) => {
 							return cb({ status: 'failure', message: 'Something went wrong while disliking this song.' });
-						}
+						});
 					});
-				});
+				} else {
+					return cb({ status: 'failure', message: 'Something went wrong while disliking this song.' });
+				}
 			});
 		});
 	}),
 
-	undislike: hooks.loginRequired((sessionId, songId, cb) => {
-		cache.hget('sessions', sessionId, (err, session) => {
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				db.models.user.findOne({_id: userSession.userId}, (err, user) => {
-					if (user.disliked.indexOf(songId) === -1) return cb({ status: 'failure', message: 'You have not disliked this song.' });
-					db.models.song.update({_id: songId}, {$inc: {dislikes: -1}}, (err) => {
+	undislike: hooks.loginRequired((session, songId, cb, userId) => {
+		db.models.user.findOne({_id: userId}, (err, user) => {
+			if (user.disliked.indexOf(songId) === -1) return cb({ status: 'failure', message: 'You have not disliked this song.' });
+			db.models.song.update({_id: songId}, {$inc: {dislikes: -1}}, (err) => {
+				if (!err) {
+					db.models.user.update({_id: userId}, {$pull: {disliked: songId}}, (err) => {
 						if (!err) {
-							db.models.user.update({_id: userSession.userId}, {$pull: {disliked: songId}}, (err) => {
-								if (!err) {
-									songs.updateSong(songId, (err, song) => {});
-									cache.pub('song.undislike', JSON.stringify({songId, userId: userSession.userId}));
-								} else db.models.song.update({_id: songId}, {$inc: {dislikes: 1}}, (err) => {
-									return cb({ status: 'failure', message: 'Something went wrong while undisliking this song.' });
-								});
-							});
-						} else {
+							songs.updateSong(songId, (err, song) => {});
+							cache.pub('song.undislike', JSON.stringify({songId, userId: userId}));
+						} else db.models.song.update({_id: songId}, {$inc: {dislikes: 1}}, (err) => {
 							return cb({ status: 'failure', message: 'Something went wrong while undisliking this song.' });
-						}
+						});
 					});
-				});
+				} else {
+					return cb({ status: 'failure', message: 'Something went wrong while undisliking this song.' });
+				}
 			});
 		});
 	}),
 
-	unlike: hooks.loginRequired((sessionId, songId, cb) => {
-		cache.hget('sessions', sessionId, (err, session) => {
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				db.models.user.findOne({_id: userSession.userId}, (err, user) => {
-					if (user.liked.indexOf(songId) === -1) return cb({ status: 'failure', message: 'You have not liked this song.' });
-					db.models.song.update({_id: songId}, {$inc: {likes: -1}}, (err) => {
+	unlike: hooks.loginRequired((session, songId, cb, userId) => {
+		db.models.user.findOne({_id: userId}, (err, user) => {
+			if (user.liked.indexOf(songId) === -1) return cb({ status: 'failure', message: 'You have not liked this song.' });
+			db.models.song.update({_id: songId}, {$inc: {likes: -1}}, (err) => {
+				if (!err) {
+					db.models.user.update({_id: userId}, {$pull: {liked: songId}}, (err) => {
 						if (!err) {
-							db.models.user.update({_id: userSession.userId}, {$pull: {liked: songId}}, (err) => {
-								if (!err) {
-									songs.updateSong(songId, (err, song) => {});
-									cache.pub('song.unlike', JSON.stringify({songId, userId: userSession.userId}));
-								} else db.models.song.update({_id: songId}, {$inc: {likes: 1}}, (err) => {
-									return cb({ status: 'failure', message: 'Something went wrong while unliking this song.' });
-								});
-							});
-						} else {
+							songs.updateSong(songId, (err, song) => {});
+							cache.pub('song.unlike', JSON.stringify({songId, userId: userId}));
+						} else db.models.song.update({_id: songId}, {$inc: {likes: 1}}, (err) => {
 							return cb({ status: 'failure', message: 'Something went wrong while unliking this song.' });
-						}
+						});
 					});
-				});
+				} else {
+					return cb({ status: 'failure', message: 'Something went wrong while unliking this song.' });
+				}
 			});
 		});
 	}),
 
-	getOwnSongRatings: hooks.loginRequired(function(sessionId, songId, cb, userId) {
+	getOwnSongRatings: hooks.loginRequired(function(session, songId, cb, userId) {
 		db.models.user.findOne({_id: userId}, (err, user) => {
-			console.log({
-				status: 'success',
-				songId: songId,
-				liked: (user.liked.indexOf(songId) !== -1),
-				disliked: (user.disliked.indexOf(songId) !== -1)
-			})
-			console.log(user.liked)
-			console.log(user.disliked)
 			return cb({
 				status: 'success',
 				songId: songId,

+ 29 - 35
backend/logic/actions/stations.js

@@ -73,12 +73,12 @@ module.exports = {
 	/**
 	 * Joins the station by its id
 	 *
-	 * @param sessionId
+	 * @param session
 	 * @param stationId - the station id
 	 * @param cb
 	 * @return {{ status: String, userCount: Integer }}
 	 */
-	join: (sessionId, stationId, cb) => {
+	join: (session, stationId, cb) => {
 
 		stations.initializeAndReturnStation(stationId, (err, station) => {
 
@@ -90,22 +90,22 @@ module.exports = {
 
 				//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(sessionId, `station.${stationId}`);
-					utils.socketJoinSongRoom(sessionId, `song.${station.currentSong._id}`);
-					//TODO Emit to cache, listen on cache
-					songs.getSong(station.currentSong._id, (err, song) => {
-						if (!err) {
-							station.currentSong.likes = song.likes;
-							station.currentSong.dislikes = song.dislikes;
-						} else {
-							station.currentSong.likes = -1;
-							station.currentSong.dislikes = -1;
-						}
-						cb({ status: 'success', currentSong: station.currentSong, startedAt: station.startedAt, paused: station.paused, timePaused: station.timePaused });
-					});
+				/*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.socketId, `station.${stationId}`);
+				utils.socketJoinSongRoom(session.socketId, `song.${station.currentSong._id}`);
+				//TODO Emit to cache, listen on cache
+				songs.getSong(station.currentSong._id, (err, song) => {
+					if (!err && song) {
+						station.currentSong.likes = song.likes;
+						station.currentSong.dislikes = song.dislikes;
+					} else {
+						station.currentSong.likes = -1;
+						station.currentSong.dislikes = -1;
+					}
+					cb({ status: 'success', currentSong: station.currentSong, startedAt: station.startedAt, paused: station.paused, timePaused: station.timePaused });
 				});
+				//});
 			}
 			else {
 				cb({ status: 'failure', message: `That station doesn't exist` });
@@ -150,8 +150,6 @@ module.exports = {
 	},*/
 
 	forceSkip: hooks.adminRequired((session, stationId, cb) => {
-		//TODO Require admin
-
 		stations.initializeAndReturnStation(stationId, (err, station) => {
 
 			if (err && err !== true) {
@@ -172,11 +170,11 @@ module.exports = {
 	 * Leaves the users current station
 	 *
 	 * @param session
+	 * @param stationId
 	 * @param cb
 	 * @return {{ status: String, userCount: Integer }}
 	 */
-	leave: (session, cb) => {
-		let stationId = "edm";
+	leave: (session, stationId, cb) => {
 		stations.initializeAndReturnStation(stationId, (err, station) => {
 
 			if (err && err !== true) {
@@ -196,7 +194,7 @@ module.exports = {
 		});
 	},
 
-	lock: hooks.adminRequired((sessionId, stationId, cb) => {
+	lock: hooks.adminRequired((session, stationId, cb) => {
 		stations.initializeAndReturnStation(stationId, (err, station) => {
 			if (err && err !== true) {
 				return cb({ status: 'error', message: 'An error occurred while locking the station' });
@@ -209,7 +207,7 @@ module.exports = {
 		});
 	}),
 
-	unlock: hooks.adminRequired((sessionId, stationId, cb) => {
+	unlock: hooks.adminRequired((session, stationId, cb) => {
 		stations.initializeAndReturnStation(stationId, (err, station) => {
 			if (err && err !== true) {
 				return cb({ status: 'error', message: 'An error occurred while unlocking the station' });
@@ -222,8 +220,7 @@ module.exports = {
 		});
 	}),
 
-	pause: hooks.adminRequired((sessionId, stationId, cb) => {
-		//TODO Require admin
+	pause: hooks.adminRequired((session, stationId, cb) => {
 		stations.initializeAndReturnStation(stationId, (err, station) => {
 			if (err && err !== true) {
 				return cb({ status: 'error', message: 'An error occurred while pausing the station' });
@@ -252,8 +249,7 @@ module.exports = {
 		});
 	}),
 
-	resume: hooks.adminRequired((sessionId, stationId, cb) => {
-		//TODO Require admin
+	resume: hooks.adminRequired((session, stationId, cb) => {
 		stations.initializeAndReturnStation(stationId, (err, station) => {
 			if (err && err !== true) {
 				return cb({ status: 'error', message: 'An error occurred while resuming the station' });
@@ -281,14 +277,14 @@ module.exports = {
 		});
 	}),
 
-	remove: hooks.adminRequired((sessionId, _id, cb) => {
-		db.models.station.find({ _id }).remove().exec();
-		cache.hdel('stations', _id, () => {
+	remove: hooks.adminRequired((session, stationId, cb) => {
+		db.models.station.remove({ _id: stationId });
+		cache.hdel('stations', stationId, () => {
 			return cb({ status: 'success', message: 'Station successfully removed' });
 		});
 	}),
 
-	create: hooks.adminRequired((sessionId, data, cb) => {
+	create: hooks.adminRequired((session, data, cb) => {
 		async.waterfall([
 
 			(next) => {
@@ -320,10 +316,8 @@ module.exports = {
 
 		], (err, station) => {
 			if (err) throw err;
-			stations.calculateSongForStation(station, () => {
-				cache.pub('station.create', data._id);
-				return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
-			});
+			cache.pub('station.create', data._id);
+			return cb(null, { 'status': 'success', 'message': 'Successfully created station.' });
 		});
 	}),
 

+ 27 - 38
backend/logic/actions/users.js

@@ -12,12 +12,13 @@ const hooks = require('./hooks');
 
 module.exports = {
 
-	login: (sessionId, identifier, password, cb) => {
+	login: (session, identifier, password, cb) => {
 
 		async.waterfall([
 
 			// check if a user with the requested identifier exists
 			(next) => db.models.user.findOne({
+				//TODO Handle lowercase
 				$or: [{ 'username': identifier }, { 'email.address': identifier }]
 			}, next),
 
@@ -33,15 +34,13 @@ module.exports = {
 					if (match) {
 
 						// store the session in the cache
-						let userSessionId = utils.guid();
-						cache.hset('userSessions', userSessionId, cache.schemas.userSession(user._id), (err) => {
+						let sessionId = utils.guid();
+						cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
 							if (!err) {
-								cache.hget('sessions', sessionId, (err, session) => {
-									session.userSessionId = userSessionId;
-									cache.hset('sessions', sessionId, session, (err) => {
-										next(null, { status: 'success', message: 'Login successful', user, SID: userSessionId });
-									})
-								})
+								//TODO See if it is necessary to add new SID to socket.
+								next(null, { status: 'success', message: 'Login successful', user, SID: sessionId });
+							} else {
+								next(null, { status: 'failure', message: 'Something went wrong' });
 							}
 						});
 					}
@@ -147,26 +146,20 @@ module.exports = {
 
 	},
 
-	logout: (sessionId, cb) => {
+	logout: (session, cb) => {
 
-		cache.hget('sessions', sessionId, (err, session) => {
+		cache.hget('sessions', session.sessionId, (err, session) => {
 			if (err || !session) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
-			if (!session.userSessionId) return cb({ 'status': 'failure', message: 'You are not logged in.' });
 
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				if (err || !userSession) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
-				if (!userSession) return cb({ 'status': 'failure', message: 'You are not logged in.' });
-
-				cache.hdel('userSessions', session.userSessionId, (err) => {
-					if (err || !userSession) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
-					return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
-				});
+			cache.hdel('sessions', session.sessionId, (err) => {
+				if (err) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
+				return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
 			});
 		});
 
 	},
 
-	findByUsername: (sessionId, username, cb) => {
+	findByUsername: (session, username, cb) => {
 		db.models.user.find({ username }, (err, account) => {
 			if (err) throw err;
 			else if (account.length == 0) {
@@ -192,28 +185,24 @@ module.exports = {
 		});
 	},
 
-	findBySession: (sessionId, cb) => {
-		cache.hget('sessions', sessionId, (err, session) => {
-			if (err || !session) return cb({ 'status': 'error', message: err });
-			if (!session.userSessionId) return cb({ 'status': 'error', message: 'You are not logged in' });
-			cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-				if (err || !userSession) return cb({ 'status': 'error', message: err });
-				if (!userSession) return cb({ 'status': 'error', message: 'You are not logged in' });
-				db.models.user.findOne({ _id: userSession.userId }, (err, user) => {
-					if (err) { throw err; } else if (user) {
-						return cb({
-							status: 'success',
-							data: user
-						});
-					}
-				});
+	findBySession: (session, cb) => {
+		cache.hget('sessions', session.sessionId, (err, session) => {
+			if (err) return cb({ 'status': 'error', message: err });
+			if (!session) return cb({ 'status': 'error', message: 'You are not logged in' });
+			db.models.user.findOne({ _id: session.userId }, (err, user) => {
+				if (err) { throw err; } else if (user) {
+					return cb({
+						status: 'success',
+						data: user
+					});
+				}
 			});
 		});
 
 	},
 
-	update: hooks.loginRequired((sessionId, user_id, property, value, cb, userId) => {
-        db.models.user.findOne({ _id: userId }, (err, user) => {
+	update: hooks.loginRequired((session, user_id, property, value, cb) => {
+        db.models.user.findOne({ _id: session.userId }, (err, user) => {
             if (err) throw err;
             else if (!user) cb({ status: 'error', message: 'Invalid User ID' });
             else if (user[property] !== undefined && user[property] !== value) {

+ 6 - 6
backend/logic/app.js

@@ -74,10 +74,10 @@ const lib = {
 								user.services.github.access_token = access_token;
 								user.save(err => {
 									if (err) return redirectOnErr('err');
-									let userSessionId = utils.guid();
-									cache.hset('userSessions', utils.guid(), cache.schemas.userSession(user._id), err => {
+									let sessionId = utils.guid();
+									cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), err => {
 										if (err) return redirectOnErr('err');
-										res.cookie('SID', utils.guid());
+										res.cookie('SID', sessionId);
 										res.redirect(`http://${config.get('domain')}/`);
 									});
 								});
@@ -110,10 +110,10 @@ const lib = {
 											}, (err, user) => {
 												if (err) return redirectOnErr('err');
 												//TODO Send verification email
-												let userSessionId = utils.guid();
-												cache.hset('userSessions', userSessionId, cache.schemas.userSession(user._id), err => {
+												let sessionId = utils.guid();
+												cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), err => {
 													if (err) return redirectOnErr('err');
-													res.cookie('SID', userSessionId);
+													res.cookie('SID', sessionId);
 													res.redirect(`http://${config.get('domain')}/`);
 												});
 											});

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

@@ -12,7 +12,6 @@ const lib = {
 	url: '',
 	schemas: {
 		session: require('./schemas/session'),
-		userSession: require('./schemas/userSession'),
 		station: require('./schemas/station'),
 		song: require('./schemas/song')
 	},

+ 3 - 9
backend/logic/cache/schemas/session.js

@@ -1,15 +1,9 @@
 'use strict';
 
-/**
- * Schema for a session stored in redis,
- * gets created when a user logs in
- *
- * @returns {{stationId: null, created: number}}
- */
-module.exports = (userSessionId) => {
+module.exports = (sessionId, userId) => {
 	return {
-		stationId: null,
-		userSessionId: userSessionId,
+		sessionId: sessionId,
+		userId: userId,
 		created: Date.now()
 	};
 };

+ 0 - 8
backend/logic/cache/schemas/userSession.js

@@ -1,8 +0,0 @@
-'use strict';
-
-module.exports = (userId) => {
-	return {
-		userId: userId,
-		created: Date.now()
-	};
-};

+ 23 - 31
backend/logic/io.js

@@ -21,13 +21,11 @@ module.exports = {
 			let SID = utils.cookies.parseCookies(cookies).SID;
 
 			if (!SID) SID = "NONE";
-			cache.hget('userSessions', SID, (err, userSession) => {
+			cache.hget('sessions', SID, (err, session) => {
 				if (err) SID = null;
-				let sessionId = utils.guid();
-				cache.hset('sessions', sessionId, cache.schemas.session(SID), (err) => {
-					socket.sessionId = sessionId;
-					return next();
-				});
+				socket.session = (session) ? session : {};
+				socket.session.socketId = socket.id;
+				return next();
 			});
 		});
 
@@ -38,10 +36,10 @@ module.exports = {
 			socket.on('disconnect', () => {
 
 				// remove the user from their current station (if any)
-				if (socket.sessionId) {
+				if (socket.session) {
 					//actions.stations.leave(socket.sessionId, result => {});
 					// Remove session from Redis
-					cache.hdel('sessions', socket.sessionId);
+					//cache.hdel('sessions', socket.session.sessionId);
 				}
 
 				console.info('User has disconnected');
@@ -64,7 +62,7 @@ module.exports = {
 						let cb = arguments[arguments.length - 1];
 
 						// load the session from the cache
-						cache.hget('sessions', socket.sessionId, (err, session) => {
+						cache.hget('sessions', socket.session.sessionId, (err, session) => {
 							if (err && err !== true) {
 								if (typeof cb === 'function') return cb({
 									status: 'error',
@@ -73,10 +71,10 @@ module.exports = {
 							}
 
 							// make sure the sockets sessionId isn't set if there is no session
-							if (socket.sessionId && session === null) delete socket.sessionId;
+							if (socket.session.sessionId && session === null) delete socket.session.sessionId;
 
 							// call the action, passing it the session, and the arguments socket.io passed us
-							actions[namespace][action].apply(null, [socket.sessionId].concat(args).concat([
+							actions[namespace][action].apply(null, [socket.session].concat(args).concat([
 								(result) => {
 									// respond to the socket with our message
 									if (typeof cb === 'function') return cb(result);
@@ -87,28 +85,22 @@ module.exports = {
 				})
 			});
 
-			//TODO check if session is valid before returning true/false
-			if (socket.sessionId !== undefined) cache.hget('sessions', socket.sessionId, (err, session) => {
-				if (err && err !== true) socket.emit('ready', false);
-				else if (session) {
-					if (!!session.userSessionId) {
-						cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-							if (err && err !== true) socket.emit('ready', false);
-							else if (userSession) {
-								db.models.user.findOne({ _id: userSession.userId }, (err, user) => {
-									let role = '';
-									let username = '';
-									if (user) {
-										role = user.role;
-										username = user.username;
-									}
-									socket.emit('ready', true, role, username);
-								});
-							} else socket.emit('ready', false);
+			if (socket.session.sessionId) {
+				cache.hget('sessions', socket.session.sessionId, (err, session) => {
+					if (err && err !== true) socket.emit('ready', false);
+					else if (session && session.userId) {
+						db.models.user.findOne({ _id: session.userId }, (err, user) => {
+							let role = '';
+							let username = '';
+							if (user) {
+								role = user.role;
+								username = user.username;
+							}
+							socket.emit('ready', true, role, username);
 						});
 					} else socket.emit('ready', false);
-				} else socket.emit('ready', false);
-			});
+				})
+			} else socket.emit('ready', false);
 		});
 
 		cb();

+ 15 - 27
backend/logic/utils.js

@@ -129,14 +129,10 @@ module.exports = {
 			return this.toString(cookies);
 		}
 	},
-	socketFromSession: function(sessionId) {
+	socketFromSession: function(socketId) {
 		let ns = io.io.of("/");
 		if (ns) {
-			for (let id in ns.connected) {
-				if (ns.connected[id].sessionId === sessionId) {
-					return ns.connected[id];
-				}
-			}
+			return ns.connected[socketId];
 		}
 	},
 	socketsFromUser: function(userId, cb) {
@@ -146,19 +142,13 @@ module.exports = {
 			let total = Object.keys(ns.connected).length;
 			let done = 0;
 			for (let id in ns.connected) {
-				let sessionId = ns.connected[id].sessionId;
-				if (sessionId) {
-					cache.hget('sessions', sessionId, (err, session) => {
-						if (!err && session && session.userSessionId) {
-							cache.hget('userSessions', session.userSessionId, (err, userSession) => {
-								if (!err && userSession && userSession.userId === userId) {
-									sockets.push(ns.connected[id]);
-								}
-								checkComplete();
-							})
-						} else checkComplete();
-					});
-				} else checkComplete();
+				let session = ns.connected[id].session;
+				cache.hget('sessions', session.sessionId, (err, session) => {
+					if (!err && session && session.userId === userId) {
+						sockets.push(ns.connected[id]);
+					}
+					checkComplete();
+				});
 			}
 			function checkComplete() {
 				done++;
@@ -168,25 +158,23 @@ module.exports = {
 			}
 		}
 	},
-	socketLeaveRooms: function(sessionId) {
-		let socket = this.socketFromSession(sessionId);
+	socketLeaveRooms: function(socketid) {
+		let socket = this.socketFromSession(socketid);
 		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(io.io.sockets[socket.id]);
+	socketJoinRoom: function(socketId, room) {
+		let socket = this.socketFromSession(socketId);
 		let rooms = socket.rooms;
 		for (let j = 0; j < rooms.length; j++) {
 			socket.leave(rooms[j]);
 		}
 		socket.join(room);
 	},
-	socketJoinSongRoom: function(sessionId, room) {
-		let socket = this.socketFromSession(sessionId);
-		//console.log(io.io.sockets[socket.id]);
+	socketJoinSongRoom: function(socketId, room) {
+		let socket = this.socketFromSession(socketId);
 		let rooms = socket.rooms;
 		for (let j = 0; j < rooms.length; j++) {
 			if (socket.indexOf('song.') !== -1) {