users.js 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. module.exports = {
  10. login: (sessionId, identifier, password, cb) => {
  11. async.waterfall([
  12. // check if a user with the requested identifier exists
  13. (next) => db.models.user.findOne({
  14. $or: [{ 'username': identifier }, { 'email.address': identifier }]
  15. }, next),
  16. // if the user doesn't exist, respond with a failure
  17. // otherwise compare the requested password and the actual users password
  18. (user, next) => {
  19. if (!user) return next(true, { status: 'failure', message: 'User not found' });
  20. bcrypt.compare(password, user.services.password.password, (err, match) => {
  21. if (err) return next(err);
  22. // if the passwords match
  23. if (match) {
  24. // store the session in the cache
  25. let userSessionId = utils.guid();
  26. cache.hset('userSessions', userSessionId, cache.schemas.userSession(user._id), (err) => {
  27. if (!err) {
  28. cache.hget('sessions', sessionId, (err, session) => {
  29. session.userSessionId = userSessionId;
  30. cache.hset('sessions', sessionId, session, (err) => {
  31. next(null, { status: 'success', message: 'Login successful', user, SID: userSessionId });
  32. })
  33. })
  34. }
  35. });
  36. }
  37. else {
  38. next(null, { status: 'failure', message: 'User not found' });
  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: (session, username, email, password, recaptcha, cb) => {
  52. async.waterfall([
  53. // verify the request with google recaptcha
  54. (next) => {
  55. request({
  56. url: 'https://www.google.com/recaptcha/api/siteverify',
  57. method: 'POST',
  58. form: {
  59. //'secret': config.get("apis.recaptcha.secret"),
  60. 'response': recaptcha
  61. }
  62. }, next);
  63. },
  64. // check if the response from Google recaptcha is successful
  65. // if it is, we check if a user with the requested username already exists
  66. (response, body, next) => {
  67. let json = JSON.parse(body);
  68. console.log(json);
  69. //if (json.success !== true) return next('Response from recaptcha was not successful');
  70. db.models.user.findOne({ username }, 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. next(null, { status: 'success', user: newUser })
  106. }
  107. ], (err, payload) => {
  108. // log this error somewhere
  109. if (err && err !== true) {
  110. console.error(err);
  111. return cb({ status: 'error', message: 'An error occurred while registering for an account' });
  112. }
  113. // respond with the payload that was passed to us earlier
  114. cb(payload);
  115. });
  116. },
  117. logout: (session, cb) => {
  118. if (!session) return cb({ status: 'failure', message: `You're not currently logged in` });
  119. //TODO Remove session
  120. session = null;
  121. return cb({ status: 'success', message: `You've been successfully logged out` });
  122. },
  123. findByUsername: (session, username, cb) => {
  124. db.models.user.find({ username }, (err, account) => {
  125. if (err) throw err;
  126. else if (account.length == 0) {
  127. return cb({
  128. status: 'error',
  129. message: 'Username cannot be found'
  130. });
  131. } else {
  132. account = account[0];
  133. return cb({
  134. status: 'success',
  135. data: {
  136. username: account.username,
  137. email: account.email.address,
  138. password: '',
  139. createdAt: account.createdAt,
  140. statistics: account.statistics
  141. }
  142. });
  143. }
  144. });
  145. },
  146. findBySession: (session, cb) => {
  147. return cb({
  148. status: 'success',
  149. data: session
  150. });
  151. },
  152. update: (session, user_id, property, value, cb) => {
  153. db.models.user.findOne({ _id: user_id }, (err, user) => {
  154. if (err) throw err;
  155. else if (!user) cb({ status: 'error', message: 'Invalid User ID' });
  156. else if (user[property] && user[property] !== value) {
  157. if (property == 'services.password.password') {
  158. bcrypt.compare(user[property], value, (err, res) => {
  159. if (err) throw err;
  160. bcrypt.genSalt(10, (err, salt) => {
  161. if (err) throw err;
  162. bcrypt.hash(value, salt, (err, hash) => {
  163. if (err) throw err;
  164. user[property] = hash;
  165. });
  166. });
  167. });
  168. } else user[property] = value;
  169. user.save(err => {
  170. if (err) cb({ status: 'error', message: err.message });
  171. });
  172. } else {
  173. cb({ status: 'error', message: 'Field has not changed' });
  174. }
  175. });
  176. },
  177. };