users.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. 'use strict';
  2. const async = require('async');
  3. const config = require('config');
  4. const request = require('request');
  5. const bcrypt = require('bcrypt');
  6. const db = require('../db');
  7. const cache = require('../cache');
  8. const utils = require('../utils');
  9. const hooks = require('./hooks');
  10. const sha256 = require('sha256');
  11. const logger = require('../logger');
  12. cache.sub('user.updateUsername', user => {
  13. utils.socketsFromUser(user._id, sockets => {
  14. sockets.forEach(socket => {
  15. socket.emit('event:user.username.changed', user.username);
  16. });
  17. });
  18. });
  19. module.exports = {
  20. /**
  21. * Logs user in
  22. *
  23. * @param {Object} session - the session object automatically added by socket.io
  24. * @param {String} identifier - the email of the user
  25. * @param {String} password - the plaintext of the user
  26. * @param {Function} cb - gets called with the result
  27. */
  28. login: (session, identifier, password, cb) => {
  29. identifier = identifier.toLowerCase();
  30. async.waterfall([
  31. // check if a user with the requested identifier exists
  32. (next) => db.models.user.findOne({
  33. $or: [{ 'email.address': identifier }]
  34. }, next),
  35. // if the user doesn't exist, respond with a failure
  36. // otherwise compare the requested password and the actual users password
  37. (user, next) => {
  38. if (!user) return next('User not found');
  39. if (!user.services.password || !user.services.password.password) return next('The account you are trying to access uses GitHub to log in.');
  40. bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  41. if (err) return next(err);
  42. if (!match) return next('Incorrect password');
  43. // if the passwords match
  44. // store the session in the cache
  45. let sessionId = utils.guid();
  46. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
  47. if (err) return next(err);
  48. next(null, sessionId);
  49. });
  50. });
  51. }
  52. ], (err, sessionId) => {
  53. if (err && err !== true) {
  54. let error = 'An error occurred.';
  55. if (typeof err === "string") error = err;
  56. else if (err.message) error = err.message;
  57. logger.error("USER_PASSWORD_LOGIN", "Login failed with password for user " + identifier + '. "' + error + '"');
  58. return cb({ status: 'failure', message: error });
  59. }
  60. logger.success("USER_PASSWORD_LOGIN", "Login successful with password for user " + identifier);
  61. cb({ status: 'success', message: 'Login successful', user: {}, SID: sessionId });
  62. });
  63. },
  64. /**
  65. * Registers a new user
  66. *
  67. * @param {Object} session - the session object automatically added by socket.io
  68. * @param {String} username - the username for the new user
  69. * @param {String} email - the email for the new user
  70. * @param {String} password - the plaintext password for the new user
  71. * @param {Object} recaptcha - the recaptcha data
  72. * @param {Function} cb - gets called with the result
  73. */
  74. register: function(session, username, email, password, recaptcha, cb) {
  75. email = email.toLowerCase();
  76. async.waterfall([
  77. // verify the request with google recaptcha
  78. (next) => {
  79. request({
  80. url: 'https://www.google.com/recaptcha/api/siteverify',
  81. method: 'POST',
  82. form: {
  83. 'secret': config.get("apis").recaptcha.secret,
  84. 'response': recaptcha
  85. }
  86. }, next);
  87. },
  88. // check if the response from Google recaptcha is successful
  89. // if it is, we check if a user with the requested username already exists
  90. (response, body, next) => {
  91. let json = JSON.parse(body);
  92. if (json.success !== true) return next('Response from recaptcha was not successful.');
  93. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  94. },
  95. // if the user already exists, respond with that
  96. // otherwise check if a user with the requested email already exists
  97. (user, next) => {
  98. if (user) return next('A user with that username already exists.');
  99. db.models.user.findOne({ 'email.address': email }, next);
  100. },
  101. // if the user already exists, respond with that
  102. // otherwise, generate a salt to use with hashing the new users password
  103. (user, next) => {
  104. if (user) return next('A user with that email already exists.');
  105. bcrypt.genSalt(10, next);
  106. },
  107. // hash the password
  108. (salt, next) => {
  109. bcrypt.hash(sha256(password), salt, next)
  110. },
  111. // save the new user to the database
  112. (hash, next) => {
  113. db.models.user.create({
  114. _id: utils.generateRandomString(12),//TODO Check if exists
  115. username,
  116. email: {
  117. address: email,
  118. verificationToken: utils.generateRandomString(64)
  119. },
  120. services: {
  121. password: {
  122. password: hash
  123. }
  124. }
  125. }, next);
  126. },
  127. // respond with the new user
  128. (newUser, next) => {
  129. //TODO Send verification email
  130. next();
  131. }
  132. ], (err) => {
  133. if (err && err !== true) {
  134. let error = 'An error occurred.';
  135. if (typeof err === "string") error = err;
  136. else if (err.message) error = err.message;
  137. logger.error("USER_PASSWORD_REGISTER", "Register failed with password for user. " + '"' + error + '"');
  138. cb({status: 'failure', message: error});
  139. } else {
  140. module.exports.login(session, email, password, (result) => {
  141. let obj = {status: 'success', message: 'Successfully registered.'};
  142. if (result.status === 'success') {
  143. obj.SID = result.SID;
  144. }
  145. logger.success("USER_PASSWORD_REGISTER", "Register successful with password for user '" + username + "'.");
  146. cb({status: 'success', message: 'Successfully registered.'});
  147. });
  148. }
  149. });
  150. },
  151. /**
  152. * Logs out a user
  153. *
  154. * @param {Object} session - the session object automatically added by socket.io
  155. * @param {Function} cb - gets called with the result
  156. */
  157. logout: (session, cb) => {
  158. cache.hget('sessions', session.sessionId, (err, session) => {
  159. if (err || !session) {
  160. //TODO Properly return err message
  161. logger.error("USER_LOGOUT", "Logout failed. Couldn't get session.");
  162. return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  163. }
  164. cache.hdel('sessions', session.sessionId, (err) => {
  165. if (err) {
  166. logger.error("USER_LOGOUT", "Logout failed. Failed deleting session from cache.");
  167. return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  168. }
  169. logger.success("USER_LOGOUT", "Logout successful.");
  170. return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
  171. });
  172. });
  173. },
  174. /**
  175. * Gets user object from username (only a few properties)
  176. *
  177. * @param {Object} session - the session object automatically added by socket.io
  178. * @param {String} username - the username of the user we are trying to find
  179. * @param {Function} cb - gets called with the result
  180. */
  181. findByUsername: (session, username, cb) => {
  182. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, (err, account) => {
  183. if (err) {
  184. logger.error("FIND_BY_USERNAME", "Find by username failed for username '" + username + "'. Mongo error.");
  185. return cb({ 'status': 'error', message: err.message });
  186. }
  187. else if (!account) {
  188. logger.error("FIND_BY_USERNAME", "User not found for username '" + username + "'.");
  189. return cb({
  190. status: 'error',
  191. message: 'User cannot be found'
  192. });
  193. } else {
  194. logger.success("FIND_BY_USERNAME", "User found for username '" + username + "'.");
  195. return cb({
  196. status: 'success',
  197. data: {
  198. _id: account._id,
  199. username: account.username,
  200. role: account.role,
  201. email: account.email.address,
  202. createdAt: account.createdAt,
  203. statistics: account.statistics,
  204. liked: account.liked,
  205. disliked: account.disliked
  206. }
  207. });
  208. }
  209. });
  210. },
  211. //TODO Fix security issues
  212. /**
  213. * Gets user info from session
  214. *
  215. * @param {Object} session - the session object automatically added by socket.io
  216. * @param {Function} cb - gets called with the result
  217. */
  218. findBySession: (session, cb) => {
  219. cache.hget('sessions', session.sessionId, (err, session) => {
  220. if (err) {
  221. logger.error("FIND_BY_SESSION", "Failed getting session. Redis error. '" + err + "'.");
  222. return cb({ 'status': 'error', message: err.message });
  223. }
  224. if (!session) {
  225. logger.error("FIND_BY_SESSION", "Session not found. Not logged in.");
  226. return cb({ 'status': 'error', message: 'You are not logged in' });
  227. }
  228. db.models.user.findOne({ _id: session.userId }, {username: 1, "email.address": 1}, (err, user) => {
  229. if (err) {
  230. logger.error("FIND_BY_SESSION", "User not found. Failed getting user. Mongo error.");
  231. throw err;
  232. } else if (user) {
  233. logger.success("FIND_BY_SESSION", "User found. '" + user.username + "'.");
  234. return cb({
  235. status: 'success',
  236. data: user
  237. });
  238. }
  239. });
  240. });
  241. },
  242. /**
  243. * Updates a user's username
  244. *
  245. * @param {Object} session - the session object automatically added by socket.io
  246. * @param {String} newUsername - the new username
  247. * @param {Function} cb - gets called with the result
  248. * @param {String} userId - the userId automatically added by hooks
  249. */
  250. updateUsername: hooks.loginRequired((session, newUsername, cb, userId) => {
  251. db.models.user.findOne({ _id: userId }, (err, user) => {
  252. if (err) {
  253. logger.error("UPDATE_USERNAME", `Failed getting user. Mongo error. '${err.message}'.`);
  254. return cb({ status: 'error', message: 'Something went wrong.' });
  255. } else if (!user) {
  256. logger.error("UPDATE_USERNAME", `User not found. '${userId}'`);
  257. return cb({ status: 'error', message: 'User not found' });
  258. } else if (user.username !== newUsername) {
  259. if (user.username.toLowerCase() !== newUsername.toLowerCase()) {
  260. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, (err, _user) => {
  261. if (err) {
  262. logger.error("UPDATE_USERNAME", `Failed to get other user with the same username. Mongo error. '${err.message}'`);
  263. return cb({ status: 'error', message: err.message });
  264. }
  265. if (_user) {
  266. logger.error("UPDATE_USERNAME", `Username already in use.`);
  267. return cb({ status: 'failure', message: 'That username is already in use' });
  268. }
  269. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  270. if (err) {
  271. logger.error("UPDATE_USERNAME", `Couldn't update user. Mongo error. '${err.message}'`);
  272. return cb({ status: 'error', message: err.message });
  273. }
  274. cache.pub('user.updateUsername', {
  275. username: newUsername,
  276. _id: userId
  277. });
  278. logger.success("UPDATE_USERNAME", `Updated username. '${userId}' '${newUsername}'`);
  279. cb({ status: 'success', message: 'Username updated successfully' });
  280. });
  281. });
  282. } else {
  283. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  284. if (err) {
  285. logger.error("UPDATE_USERNAME", `Couldn't update user. Mongo error. '${err.message}'`);
  286. return cb({ status: 'error', message: err.message });
  287. }
  288. cache.pub('user.updateUsername', {
  289. username: newUsername,
  290. _id: userId
  291. });
  292. logger.success("UPDATE_USERNAME", `Updated username. '${userId}' '${newUsername}'`);
  293. cb({ status: 'success', message: 'Username updated successfully' });
  294. });
  295. }
  296. } else {
  297. logger.error("UPDATE_USERNAME", `New username is the same as the old username. '${newUsername}'`);
  298. cb({ status: 'error', message: 'Your new username cannot be the same as your old username' });
  299. }
  300. });
  301. }),
  302. /**
  303. * Updates a user's email
  304. *
  305. * @param {Object} session - the session object automatically added by socket.io
  306. * @param {String} newEmail - the new email
  307. * @param {Function} cb - gets called with the result
  308. * @param {String} userId - the userId automatically added by hooks
  309. */
  310. updateEmail: hooks.loginRequired((session, newEmail, cb, userId) => {
  311. newEmail = newEmail.toLowerCase();
  312. db.models.user.findOne({ _id: userId }, (err, user) => {
  313. if (err) {
  314. logger.error("UPDATE_EMAIL", `Failed getting user. Mongo error. '${err.message}'.`);
  315. return cb({ status: 'error', message: 'Something went wrong.' });
  316. } else if (!user) {
  317. logger.error("UPDATE_EMAIL", `User not found. '${userId}'`);
  318. return cb({ status: 'error', message: 'User not found.' });
  319. } else if (user.email.address !== newEmail) {
  320. db.models.user.findOne({"email.address": newEmail}, (err, _user) => {
  321. if (err) {
  322. logger.error("UPDATE_EMAIL", `Couldn't get other user with new email. Mongo error. '${newEmail}'`);
  323. return cb({ status: 'error', message: err.message });
  324. } else if (_user) {
  325. logger.error("UPDATE_EMAIL", `Email already in use.`);
  326. return cb({ status: 'failure', message: 'That email is already in use.' });
  327. }
  328. db.models.user.update({_id: userId}, {$set: {"email.address": newEmail}}, (err) => {
  329. if (err) {
  330. logger.error("UPDATE_EMAIL", `Couldn't update user. Mongo error. ${err.message}`);
  331. return cb({ status: 'error', message: err.message });
  332. }
  333. logger.success("UPDATE_EMAIL", `Updated email. '${userId}' ${newEmail}'`);
  334. cb({ status: 'success', message: 'Email updated successfully.' });
  335. });
  336. });
  337. } else {
  338. logger.error("UPDATE_EMAIL", `New email is the same as the old email.`);
  339. cb({
  340. status: 'error',
  341. message: 'Email has not changed. Your new email cannot be the same as your old email.'
  342. });
  343. }
  344. });
  345. }),
  346. /**
  347. * Updates a user's role
  348. *
  349. * @param {Object} session - the session object automatically added by socket.io
  350. * @param {String} updatingUserId - the updating user's id
  351. * @param {String} newRole - the new role
  352. * @param {Function} cb - gets called with the result
  353. * @param {String} userId - the userId automatically added by hooks
  354. */
  355. updateRole: hooks.adminRequired((session, updatingUserId, newRole, cb, userId) => {
  356. newRole = newRole.toLowerCase();
  357. db.models.user.update({_id: updatingUserId}, {$set: {role: newRole}}, (err) => {
  358. if (err) {
  359. logger.error("UPDATE_ROLE", `Failed updating user. Mongo error. '${err.message}'.`);
  360. return cb({ status: 'error', message: 'Something went wrong.' });
  361. }
  362. logger.error("UPDATE_ROLE", `User '${userId}' updated the role of user '${updatingUserId}' to role '${newRole}'.`);
  363. cb({
  364. status: 'success',
  365. message: 'Role successfully updated.'
  366. });
  367. });
  368. })
  369. };