users.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. login: (session, identifier, password, cb) => {
  21. identifier = identifier.toLowerCase();
  22. async.waterfall([
  23. // check if a user with the requested identifier exists
  24. (next) => db.models.user.findOne({
  25. $or: [{ 'email.address': identifier }]
  26. }, next),
  27. // if the user doesn't exist, respond with a failure
  28. // otherwise compare the requested password and the actual users password
  29. (user, next) => {
  30. if (!user) return next('User not found');
  31. if (!user.services.password || !user.services.password.password) return next('The account you are trying to access uses GitHub to log in.');
  32. bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  33. if (err) return next(err);
  34. // if the passwords match
  35. if (match) {
  36. // store the session in the cache
  37. let sessionId = utils.guid();
  38. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
  39. if (!err) {
  40. //TODO See if it is necessary to add new SID to socket.
  41. next(null, { status: 'success', message: 'Login successful', user, SID: sessionId });
  42. } else {
  43. next(null, { status: 'failure', message: 'Something went wrong' });
  44. }
  45. });
  46. }
  47. else {
  48. next(null, { status: 'failure', message: 'Incorrect password' });
  49. }
  50. });
  51. }
  52. ], (err, payload) => {
  53. // log this error somewhere
  54. if (err && err !== true) {
  55. let error = 'An error occurred.';
  56. if (typeof err === "string") error = err;
  57. else if (err.message) error = err.message;
  58. logger.log("USER_PASSWORD_LOGIN", "ERROR", "Login failed with password for user " + identifier + '. "' + error + '"');
  59. return cb({ status: 'failure', message: error });
  60. }
  61. logger.log("USER_PASSWORD_LOGIN", "SUCCESS", "Login successful with password for user " + identifier);
  62. cb(payload);
  63. });
  64. },
  65. register: function(session, username, email, password, recaptcha, cb) {
  66. email = email.toLowerCase();
  67. async.waterfall([
  68. // verify the request with google recaptcha
  69. (next) => {
  70. request({
  71. url: 'https://www.google.com/recaptcha/api/siteverify',
  72. method: 'POST',
  73. form: {
  74. 'secret': config.get("apis").recaptcha.secret,
  75. 'response': recaptcha
  76. }
  77. }, next);
  78. },
  79. // check if the response from Google recaptcha is successful
  80. // if it is, we check if a user with the requested username already exists
  81. (response, body, next) => {
  82. let json = JSON.parse(body);
  83. if (json.success !== true) return next('Response from recaptcha was not successful.');
  84. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  85. },
  86. // if the user already exists, respond with that
  87. // otherwise check if a user with the requested email already exists
  88. (user, next) => {
  89. if (user) return next('A user with that username already exists.');
  90. db.models.user.findOne({ 'email.address': email }, next);
  91. },
  92. // if the user already exists, respond with that
  93. // otherwise, generate a salt to use with hashing the new users password
  94. (user, next) => {
  95. if (user) return next('A user with that email already exists.');
  96. bcrypt.genSalt(10, next);
  97. },
  98. // hash the password
  99. (salt, next) => {
  100. bcrypt.hash(sha256(password), salt, next)
  101. },
  102. // save the new user to the database
  103. (hash, next) => {
  104. db.models.user.create({
  105. _id: utils.generateRandomString(12),//TODO Check if exists
  106. username,
  107. email: {
  108. address: email,
  109. verificationToken: utils.generateRandomString(64)
  110. },
  111. services: {
  112. password: {
  113. password: hash
  114. }
  115. }
  116. }, next);
  117. },
  118. // respond with the new user
  119. (newUser, next) => {
  120. //TODO Send verification email
  121. next(null, { status: 'success', user: newUser })
  122. }
  123. ], (err, payload) => {
  124. // log this error somewhere
  125. if (err && err !== true) {
  126. let error = 'An error occurred.';
  127. if (typeof err === "string") error = err;
  128. else if (err.message) error = err.message;
  129. logger.log("USER_PASSWORD_REGISTER", "ERROR", "Register failed with password for user. " + '"' + error + '"');
  130. } else {
  131. module.exports.login(session, email, password, (result) => {
  132. let obj = {status: 'success', message: 'Successfully registered.'};
  133. if (result.status === 'success') {
  134. obj.SID = result.SID;
  135. }
  136. logger.log("USER_PASSWORD_REGISTER", "SUCCESS", "Register successful with password for user '" + username + "'.");
  137. cb(obj);
  138. });
  139. }
  140. });
  141. },
  142. logout: (session, cb) => {
  143. cache.hget('sessions', session.sessionId, (err, session) => {
  144. if (err || !session) {
  145. //TODO Properly return err message
  146. logger.log("USER_LOGOUT", "ERROR", "Logout failed. Couldn't get session.");
  147. return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  148. }
  149. cache.hdel('sessions', session.sessionId, (err) => {
  150. if (err) {
  151. logger.log("USER_LOGOUT", "ERROR", "Logout failed. Failed deleting session from cache.");
  152. return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  153. }
  154. logger.log("USER_LOGOUT", "SUCCESS", "Logout successful.");
  155. return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
  156. });
  157. });
  158. },
  159. findByUsername: (session, username, cb) => {
  160. db.models.user.find({ username }, (err, account) => {
  161. if (err) {
  162. logger.log("FIND_BY_USERNAME", "ERROR", "Find by username failed for username '" + username + "'. Mongo error.");
  163. throw err;
  164. }
  165. else if (account.length == 0) {
  166. logger.log("FIND_BY_USERNAME", "ERROR", "User not found for username '" + username + "'.");
  167. return cb({
  168. status: 'error',
  169. message: 'Username cannot be found'
  170. });
  171. } else {
  172. account = account[0];
  173. logger.log("FIND_BY_USERNAME", "SUCCESS", "User found for username '" + username + "'.");
  174. return cb({
  175. status: 'success',
  176. data: {
  177. _id: account._id,
  178. username: account.username,
  179. role: account.role,
  180. email: account.email.address,
  181. password: '',
  182. createdAt: account.createdAt,
  183. statistics: account.statistics,
  184. liked: account.liked,
  185. disliked: account.disliked
  186. }
  187. });
  188. }
  189. });
  190. },
  191. //TODO Fix security issues
  192. findBySession: (session, cb) => {
  193. cache.hget('sessions', session.sessionId, (err, session) => {
  194. if (err) {
  195. logger.log("FIND_BY_SESSION", "ERROR", "Failed getting session. Redis error. '" + err + "'.");
  196. return cb({ 'status': 'error', message: err.message });
  197. }
  198. if (!session) {
  199. logger.log("FIND_BY_SESSION", "ERROR", "Session not found. Not logged in.");
  200. return cb({ 'status': 'error', message: 'You are not logged in' });
  201. }
  202. db.models.user.findOne({ _id: session.userId }, {username: 1, "email.address": 1}, (err, user) => {
  203. if (err) {
  204. logger.log("FIND_BY_SESSION", "ERROR", "User not found. Failed getting user. Mongo error.");
  205. throw err;
  206. } else if (user) {
  207. logger.log("FIND_BY_SESSION", "SUCCESS", "User found. '" + user.username + "'.");
  208. return cb({
  209. status: 'success',
  210. data: user
  211. });
  212. }
  213. });
  214. });
  215. },
  216. updateUsername: hooks.loginRequired((session, newUsername, cb, userId) => {
  217. db.models.user.findOne({ _id: userId }, (err, user) => {
  218. if (err) {
  219. logger.log("UPDATE_USERNAME", "ERROR", `Failed getting user. Mongo error. '${err.message}'.`);
  220. return cb({ status: 'error', message: 'Something went wrong.' });
  221. } else if (!user) {
  222. logger.log("UPDATE_USERNAME", "ERROR", `User not found. '${userId}'`);
  223. return cb({ status: 'error', message: 'User not found' });
  224. } else if (user.username !== newUsername) {
  225. if (user.username.toLowerCase() !== newUsername.toLowerCase()) {
  226. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, (err, _user) => {
  227. if (err) {
  228. logger.log("UPDATE_USERNAME", "ERROR", `Failed to get other user with the same username. Mongo error. '${err.message}'`);
  229. return cb({ status: 'error', message: err.message });
  230. }
  231. if (_user) {
  232. logger.log("UPDATE_USERNAME", "ERROR", `Username already in use.`);
  233. return cb({ status: 'failure', message: 'That username is already in use' });
  234. }
  235. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  236. if (err) {
  237. logger.log("UPDATE_USERNAME", "ERROR", `Couldn't update user. Mongo error. '${err.message}'`);
  238. return cb({ status: 'error', message: err.message });
  239. }
  240. cache.pub('user.updateUsername', {
  241. username: newUsername,
  242. _id: userId
  243. });
  244. logger.log("UPDATE_USERNAME", "SUCCESS", `Updated username. '${userId}' '${newUsername}'`);
  245. cb({ status: 'success', message: 'Username updated successfully' });
  246. });
  247. });
  248. } else {
  249. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  250. if (err) {
  251. logger.log("UPDATE_USERNAME", "ERROR", `Couldn't update user. Mongo error. '${err.message}'`);
  252. return cb({ status: 'error', message: err.message });
  253. }
  254. cache.pub('user.updateUsername', {
  255. username: newUsername,
  256. _id: userId
  257. });
  258. logger.log("UPDATE_USERNAME", "SUCCESS", `Updated username. '${userId}' '${newUsername}'`);
  259. cb({ status: 'success', message: 'Username updated successfully' });
  260. });
  261. }
  262. } else {
  263. logger.log("UPDATE_USERNAME", "ERROR", `New username is the same as the old username. '${newUsername}'`);
  264. cb({ status: 'error', message: 'Your new username cannot be the same as your old username' });
  265. }
  266. });
  267. }),
  268. updateEmail: hooks.loginRequired((session, newEmail, cb, userId) => {
  269. newEmail = newEmail.toLowerCase();
  270. db.models.user.findOne({ _id: userId }, (err, user) => {
  271. if (err) {
  272. logger.log("UPDATE_EMAIL", "ERROR", `Failed getting user. Mongo error. '${err.message}'.`);
  273. return cb({ status: 'error', message: 'Something went wrong.' });
  274. } else if (!user) {
  275. logger.log("UPDATE_EMAIL", "ERROR", `User not found. '${userId}'`);
  276. return cb({ status: 'error', message: 'User not found.' });
  277. } else if (user.email.address !== newEmail) {
  278. db.models.user.findOne({"email.address": newEmail}, (err, _user) => {
  279. if (err) {
  280. logger.log("UPDATE_EMAIL", "ERROR", `Couldn't get other user with new email. Mongo error. '${newEmail}'`);
  281. return cb({ status: 'error', message: err.message });
  282. } else if (_user) {
  283. logger.log("UPDATE_EMAIL", "ERROR", `Email already in use.`);
  284. return cb({ status: 'failure', message: 'That email is already in use.' });
  285. }
  286. db.models.user.update({_id: userId}, {$set: {"email.address": newEmail}}, (err) => {
  287. if (err) {
  288. logger.log("UPDATE_EMAIL", "ERROR", `Couldn't update user. Mongo error. ${err.message}`);
  289. return cb({ status: 'error', message: err.message });
  290. }
  291. logger.log("UPDATE_EMAIL", "SUCCESS", `Updated email. '${userId}' ${newEmail}'`);
  292. cb({ status: 'success', message: 'Email updated successfully.' });
  293. });
  294. });
  295. } else {
  296. logger.log("UPDATE_EMAIL", "ERROR", `New email is the same as the old email.`);
  297. cb({
  298. status: 'error',
  299. message: 'Email has not changed. Your new email cannot be the same as your old email.'
  300. });
  301. }
  302. });
  303. })
  304. };