users.js 7.6 KB

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