users.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. //if (json.success !== true) return next('Response from recaptcha was not successful');
  69. db.models.user.findOne({ username }, next);
  70. },
  71. // if the user already exists, respond with that
  72. // otherwise check if a user with the requested email already exists
  73. (user, next) => {
  74. if (user) return next(true, { status: 'failure', message: 'A user with that username already exists' });
  75. db.models.user.findOne({ 'email.address': email }, next);
  76. },
  77. // if the user already exists, respond with that
  78. // otherwise, generate a salt to use with hashing the new users password
  79. (user, next) => {
  80. if (user) return next(true, { status: 'failure', message: 'A user with that email already exists' });
  81. bcrypt.genSalt(10, next);
  82. },
  83. // hash the password
  84. (salt, next) => {
  85. bcrypt.hash(password, salt, next)
  86. },
  87. // save the new user to the database
  88. (hash, next) => {
  89. db.models.user.create({
  90. username,
  91. email: {
  92. address: email,
  93. verificationToken: utils.generateRandomString(64)
  94. },
  95. services: {
  96. password: {
  97. password: hash
  98. }
  99. }
  100. }, next);
  101. },
  102. // respond with the new user
  103. (newUser, next) => {
  104. next(null, { status: 'success', user: newUser })
  105. }
  106. ], (err, payload) => {
  107. // log this error somewhere
  108. if (err && err !== true) {
  109. console.error(err);
  110. return cb({ status: 'error', message: 'An error occurred while registering for an account' });
  111. }
  112. // respond with the payload that was passed to us earlier
  113. cb(payload);
  114. });
  115. },
  116. logout: (sessionId, cb) => {
  117. cache.hget('sessions', sessionId, (err, session) => {
  118. if (err || !session) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  119. if (!session.userSessionId) return cb({ 'status': 'failure', message: 'You are not logged in.' });
  120. cache.hget('userSessions', session.userSessionId, (err, userSession) => {
  121. if (err || !userSession) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  122. if (!userSession) return cb({ 'status': 'failure', message: 'You are not logged in.' });
  123. cache.hdel('userSessions', session.userSessionId, (err) => {
  124. if (err || !userSession) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  125. return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
  126. });
  127. });
  128. });
  129. },
  130. findByUsername: (sessionId, username, cb) => {
  131. db.models.user.find({ username }, (err, account) => {
  132. if (err) throw err;
  133. else if (account.length == 0) {
  134. return cb({
  135. status: 'error',
  136. message: 'Username cannot be found'
  137. });
  138. } else {
  139. account = account[0];
  140. return cb({
  141. status: 'success',
  142. data: {
  143. _id: account._id,
  144. username: account.username,
  145. role: account.role,
  146. email: account.email.address,
  147. password: '',
  148. createdAt: account.createdAt,
  149. statistics: account.statistics
  150. }
  151. });
  152. }
  153. });
  154. },
  155. findBySession: (sessionId, cb) => {
  156. cache.hget('sessions', sessionId, (err, session) => {
  157. if (err || !session) return cb({ 'status': 'error', message: err });
  158. if (!session.userSessionId) return cb({ 'status': 'error', message: 'You are not logged in' });
  159. cache.hget('userSessions', session.userSessionId, (err, userSession) => {
  160. if (err || !userSession) return cb({ 'status': 'error', message: err });
  161. if (!userSession) return cb({ 'status': 'error', message: 'You are not logged in' });
  162. db.models.user.findOne({ _id: userSession.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. },
  173. update: (sessionId, user_id, property, value, cb) => {
  174. db.models.user.findOne({ _id: user_id }, (err, user) => {
  175. if (err) throw err;
  176. else if (!user) cb({ status: 'error', message: 'Invalid User ID' });
  177. else if (user[property] !== undefined && user[property] !== value) {
  178. if (property == 'services.password.password') {
  179. bcrypt.compare(user[property], value, (err, res) => {
  180. if (err) throw err;
  181. bcrypt.genSalt(10, (err, salt) => {
  182. if (err) throw err;
  183. bcrypt.hash(value, salt, (err, hash) => {
  184. if (err) throw err;
  185. user[property] = hash;
  186. });
  187. });
  188. });
  189. } else user[property] = value;
  190. user.save(err => {
  191. if (err) cb({ status: 'error', message: err.message });
  192. else cb({ status: 'success', message: 'Field saved successfully' });
  193. });
  194. } else {
  195. cb({ status: 'error', message: 'Field has not changed' });
  196. }
  197. });
  198. },
  199. };