users.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. cache.sub('user.updateUsername', user => {
  12. utils.socketsFromUser(user._id, sockets => {
  13. sockets.forEach(socket => {
  14. socket.emit('event:user.username.changed', user.username);
  15. });
  16. });
  17. });
  18. module.exports = {
  19. login: (session, identifier, password, cb) => {
  20. identifier = identifier.toLowerCase();
  21. async.waterfall([
  22. // check if a user with the requested identifier exists
  23. (next) => db.models.user.findOne({
  24. $or: [{ 'username': identifier }, { 'email.address': identifier }]
  25. }, next),
  26. // if the user doesn't exist, respond with a failure
  27. // otherwise compare the requested password and the actual users password
  28. (user, next) => {
  29. if (!user) return next(true, { status: 'failure', message: 'User not found' });
  30. bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  31. if (err) return next(err);
  32. // if the passwords match
  33. if (match) {
  34. // store the session in the cache
  35. let sessionId = utils.guid();
  36. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
  37. if (!err) {
  38. //TODO See if it is necessary to add new SID to socket.
  39. next(null, { status: 'success', message: 'Login successful', user, SID: sessionId });
  40. } else {
  41. next(null, { status: 'failure', message: 'Something went wrong' });
  42. }
  43. });
  44. }
  45. else {
  46. next(null, { status: 'failure', message: 'Incorrect password' });
  47. }
  48. });
  49. }
  50. ], (err, payload) => {
  51. // log this error somewhere
  52. if (err && err !== true) {
  53. console.error(err);
  54. return cb({ status: 'error', message: 'An error occurred while logging in' });
  55. }
  56. cb(payload);
  57. });
  58. },
  59. register: function(session, username, email, password, recaptcha, cb) {
  60. email = email.toLowerCase();
  61. async.waterfall([
  62. // verify the request with google recaptcha
  63. (next) => {
  64. request({
  65. url: 'https://www.google.com/recaptcha/api/siteverify',
  66. method: 'POST',
  67. form: {
  68. 'secret': config.get("apis").recaptcha.secret,
  69. 'response': recaptcha
  70. }
  71. }, next);
  72. },
  73. // check if the response from Google recaptcha is successful
  74. // if it is, we check if a user with the requested username already exists
  75. (response, body, next) => {
  76. let json = JSON.parse(body);
  77. if (json.success !== true) return next('Response from recaptcha was not successful');
  78. db.models.user.findOne({ username: new RegExp(`^${username}$`, 'i') }, next);
  79. },
  80. // if the user already exists, respond with that
  81. // otherwise check if a user with the requested email already exists
  82. (user, next) => {
  83. if (user) return next(true, { status: 'failure', message: 'A user with that username already exists' });
  84. db.models.user.findOne({ 'email.address': email }, next);
  85. },
  86. // if the user already exists, respond with that
  87. // otherwise, generate a salt to use with hashing the new users password
  88. (user, next) => {
  89. if (user) return next(true, { status: 'failure', message: 'A user with that email already exists' });
  90. bcrypt.genSalt(10, next);
  91. },
  92. // hash the password
  93. (salt, next) => {
  94. bcrypt.hash(sha256(password), salt, next)
  95. },
  96. // save the new user to the database
  97. (hash, next) => {
  98. db.models.user.create({
  99. _id: utils.generateRandomString(12),//TODO Check if exists
  100. username,
  101. email: {
  102. address: email,
  103. verificationToken: utils.generateRandomString(64)
  104. },
  105. services: {
  106. password: {
  107. password: hash
  108. }
  109. }
  110. }, next);
  111. },
  112. // respond with the new user
  113. (newUser, next) => {
  114. //TODO Send verification email
  115. next(null, { status: 'success', user: newUser })
  116. }
  117. ], (err, payload) => {
  118. // log this error somewhere
  119. if (err && err !== true) {
  120. console.error(err);
  121. return cb({ status: 'error', message: 'An error occurred while registering for an account' });
  122. } else {
  123. module.exports.login(session, email, password, (result) => {
  124. let obj = {status: 'success', message: 'Successfully registered.'};
  125. if (result.status === 'success') {
  126. obj.SID = result.SID;
  127. }
  128. cb(obj);
  129. });
  130. }
  131. });
  132. },
  133. logout: (session, cb) => {
  134. cache.hget('sessions', session.sessionId, (err, session) => {
  135. if (err || !session) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  136. cache.hdel('sessions', session.sessionId, (err) => {
  137. if (err) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  138. return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
  139. });
  140. });
  141. },
  142. findByUsername: (session, username, cb) => {
  143. db.models.user.find({ username }, (err, account) => {
  144. if (err) throw err;
  145. else if (account.length == 0) {
  146. return cb({
  147. status: 'error',
  148. message: 'Username cannot be found'
  149. });
  150. } else {
  151. account = account[0];
  152. return cb({
  153. status: 'success',
  154. data: {
  155. _id: account._id,
  156. username: account.username,
  157. role: account.role,
  158. email: account.email.address,
  159. password: '',
  160. createdAt: account.createdAt,
  161. statistics: account.statistics,
  162. liked: account.liked,
  163. disliked: account.disliked
  164. }
  165. });
  166. }
  167. });
  168. },
  169. //TODO Fix security issues
  170. findBySession: (session, cb) => {
  171. cache.hget('sessions', session.sessionId, (err, session) => {
  172. if (err) return cb({ 'status': 'error', message: err });
  173. if (!session) return cb({ 'status': 'error', message: 'You are not logged in' });
  174. db.models.user.findOne({ _id: session.userId }, {username: 1, "email.address": 1}, (err, user) => {
  175. if (err) { throw err; } else if (user) {
  176. return cb({
  177. status: 'success',
  178. data: user
  179. });
  180. }
  181. });
  182. });
  183. },
  184. updateUsername: hooks.loginRequired((session, newUsername, cb, userId) => {
  185. db.models.user.findOne({ _id: userId }, (err, user) => {
  186. if (err) console.error(err);
  187. if (!user) return cb({ status: 'error', message: 'User not found' });
  188. if (user.username !== newUsername) {
  189. if (user.username.toLowerCase() !== newUsername.toLowerCase()) {
  190. db.models.user.findOne({ username: new RegExp(`^${newUsername}$`, 'i') }, (err, _user) => {
  191. if (err) return cb({ status: 'error', message: err.message });
  192. if (_user) return cb({ status: 'failure', message: 'That username is already in use' });
  193. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  194. if (err) return cb({ status: 'error', message: err.message });
  195. cache.pub('user.updateUsername', {
  196. username: newUsername,
  197. _id: userId
  198. });
  199. cb({ status: 'success', message: 'Username updated successfully' });
  200. });
  201. });
  202. } else {
  203. db.models.user.update({ _id: userId }, { $set: { username: newUsername } }, (err) => {
  204. if (err) return cb({ status: 'error', message: err.message });
  205. cache.pub('user.updateUsername', {
  206. username: newUsername,
  207. _id: userId
  208. });
  209. cb({ status: 'success', message: 'Username updated successfully' });
  210. });
  211. }
  212. } else cb({ status: 'error', message: 'Your new username cannot be the same as your old username' });
  213. });
  214. }),
  215. updateEmail: hooks.loginRequired((session, newEmail, cb, userId) => {
  216. newEmail = newEmail.toLowerCase();
  217. db.models.user.findOne({ _id: userId }, (err, user) => {
  218. if (err) console.error(err);
  219. if (!user) return cb({ status: 'error', message: 'User not found.' });
  220. if (user.email.address !== newEmail) {
  221. db.models.user.findOne({"email.address": newEmail}, (err, _user) => {
  222. if (err) return cb({ status: 'error', message: err.message });
  223. if (_user) return cb({ status: 'failure', message: 'That email is already in use.' });
  224. db.models.user.update({_id: userId}, {$set: {"email.address": newEmail}}, (err) => {
  225. if (err) return cb({ status: 'error', message: err.message });
  226. cb({ status: 'success', message: 'Email updated successfully.' });
  227. });
  228. });
  229. } else cb({ status: 'error', message: 'Email has not changed. Your new email cannot be the same as your old email.' });
  230. });
  231. })
  232. };