users.js 6.9 KB

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