users.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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.find({ username }, (err, account) => {
  183. if (err) {
  184. logger.error("FIND_BY_USERNAME", "Find by username failed for username '" + username + "'. Mongo error.");
  185. throw err;
  186. }
  187. else if (account.length == 0) {
  188. logger.error("FIND_BY_USERNAME", "User not found for username '" + username + "'.");
  189. return cb({
  190. status: 'error',
  191. message: 'Username cannot be found'
  192. });
  193. } else {
  194. account = account[0];
  195. logger.success("FIND_BY_USERNAME", "User found for username '" + username + "'.");
  196. return cb({
  197. status: 'success',
  198. data: {
  199. _id: account._id,
  200. username: account.username,
  201. role: account.role,
  202. email: account.email.address,
  203. password: '',
  204. createdAt: account.createdAt,
  205. statistics: account.statistics,
  206. liked: account.liked,
  207. disliked: account.disliked
  208. }
  209. });
  210. }
  211. });
  212. },
  213. //TODO Fix security issues
  214. /**
  215. * Gets user info from session
  216. *
  217. * @param {Object} session - the session object automatically added by socket.io
  218. * @param {Function} cb - gets called with the result
  219. */
  220. findBySession: (session, cb) => {
  221. cache.hget('sessions', session.sessionId, (err, session) => {
  222. if (err) {
  223. logger.error("FIND_BY_SESSION", "Failed getting session. Redis error. '" + err + "'.");
  224. return cb({ 'status': 'error', message: err.message });
  225. }
  226. if (!session) {
  227. logger.error("FIND_BY_SESSION", "Session not found. Not logged in.");
  228. return cb({ 'status': 'error', message: 'You are not logged in' });
  229. }
  230. db.models.user.findOne({ _id: session.userId }, {username: 1, "email.address": 1}, (err, user) => {
  231. if (err) {
  232. logger.error("FIND_BY_SESSION", "User not found. Failed getting user. Mongo error.");
  233. throw err;
  234. } else if (user) {
  235. logger.success("FIND_BY_SESSION", "User found. '" + user.username + "'.");
  236. return cb({
  237. status: 'success',
  238. data: user
  239. });
  240. }
  241. });
  242. });
  243. },
  244. /**
  245. * Updates a user's username
  246. *
  247. * @param {Object} session - the session object automatically added by socket.io
  248. * @param {String} newUsername - the new username
  249. * @param {Function} cb - gets called with the result
  250. * @param {String} userId - the userId automatically added by hooks
  251. */
  252. updateUsername: hooks.loginRequired((session, newUsername, cb, userId) => {
  253. db.models.user.findOne({ _id: userId }, (err, user) => {
  254. if (err) {
  255. logger.error("UPDATE_USERNAME", `Failed getting user. Mongo error. '${err.message}'.`);
  256. return cb({ status: 'error', message: 'Something went wrong.' });
  257. } else if (!user) {
  258. logger.error("UPDATE_USERNAME", `User not found. '${userId}'`);
  259. return cb({ status: 'error', message: 'User not found' });
  260. } else if (user.username !== newUsername) {
  261. if (user.username.toLowerCase() !== newUsername.toLowerCase()) {
  262. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, (err, _user) => {
  263. if (err) {
  264. logger.error("UPDATE_USERNAME", `Failed to get other user with the same username. Mongo error. '${err.message}'`);
  265. return cb({ status: 'error', message: err.message });
  266. }
  267. if (_user) {
  268. logger.error("UPDATE_USERNAME", `Username already in use.`);
  269. return cb({ status: 'failure', message: 'That username is already in use' });
  270. }
  271. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  272. if (err) {
  273. logger.error("UPDATE_USERNAME", `Couldn't update user. Mongo error. '${err.message}'`);
  274. return cb({ status: 'error', message: err.message });
  275. }
  276. cache.pub('user.updateUsername', {
  277. username: newUsername,
  278. _id: userId
  279. });
  280. logger.success("UPDATE_USERNAME", `Updated username. '${userId}' '${newUsername}'`);
  281. cb({ status: 'success', message: 'Username updated successfully' });
  282. });
  283. });
  284. } else {
  285. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  286. if (err) {
  287. logger.error("UPDATE_USERNAME", `Couldn't update user. Mongo error. '${err.message}'`);
  288. return cb({ status: 'error', message: err.message });
  289. }
  290. cache.pub('user.updateUsername', {
  291. username: newUsername,
  292. _id: userId
  293. });
  294. logger.success("UPDATE_USERNAME", `Updated username. '${userId}' '${newUsername}'`);
  295. cb({ status: 'success', message: 'Username updated successfully' });
  296. });
  297. }
  298. } else {
  299. logger.error("UPDATE_USERNAME", `New username is the same as the old username. '${newUsername}'`);
  300. cb({ status: 'error', message: 'Your new username cannot be the same as your old username' });
  301. }
  302. });
  303. }),
  304. /**
  305. * Updates a user's email
  306. *
  307. * @param {Object} session - the session object automatically added by socket.io
  308. * @param {String} newEmail - the new email
  309. * @param {Function} cb - gets called with the result
  310. * @param {String} userId - the userId automatically added by hooks
  311. */
  312. updateEmail: hooks.loginRequired((session, newEmail, cb, userId) => {
  313. newEmail = newEmail.toLowerCase();
  314. db.models.user.findOne({ _id: userId }, (err, user) => {
  315. if (err) {
  316. logger.error("UPDATE_EMAIL", `Failed getting user. Mongo error. '${err.message}'.`);
  317. return cb({ status: 'error', message: 'Something went wrong.' });
  318. } else if (!user) {
  319. logger.error("UPDATE_EMAIL", `User not found. '${userId}'`);
  320. return cb({ status: 'error', message: 'User not found.' });
  321. } else if (user.email.address !== newEmail) {
  322. db.models.user.findOne({"email.address": newEmail}, (err, _user) => {
  323. if (err) {
  324. logger.error("UPDATE_EMAIL", `Couldn't get other user with new email. Mongo error. '${newEmail}'`);
  325. return cb({ status: 'error', message: err.message });
  326. } else if (_user) {
  327. logger.error("UPDATE_EMAIL", `Email already in use.`);
  328. return cb({ status: 'failure', message: 'That email is already in use.' });
  329. }
  330. db.models.user.update({_id: userId}, {$set: {"email.address": newEmail}}, (err) => {
  331. if (err) {
  332. logger.error("UPDATE_EMAIL", `Couldn't update user. Mongo error. ${err.message}`);
  333. return cb({ status: 'error', message: err.message });
  334. }
  335. logger.success("UPDATE_EMAIL", `Updated email. '${userId}' ${newEmail}'`);
  336. cb({ status: 'success', message: 'Email updated successfully.' });
  337. });
  338. });
  339. } else {
  340. logger.error("UPDATE_EMAIL", `New email is the same as the old email.`);
  341. cb({
  342. status: 'error',
  343. message: 'Email has not changed. Your new email cannot be the same as your old email.'
  344. });
  345. }
  346. });
  347. })
  348. };