users.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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: 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: (sessionId, cb) => {
  125. cache.hget('sessions', sessionId, (err, session) => {
  126. if (err || !session) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  127. if (!session.userSessionId) return cb({ 'status': 'failure', message: 'You are not logged in.' });
  128. cache.hget('userSessions', session.userSessionId, (err, userSession) => {
  129. if (err || !userSession) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  130. if (!userSession) return cb({ 'status': 'failure', message: 'You are not logged in.' });
  131. cache.hdel('userSessions', session.userSessionId, (err) => {
  132. if (err || !userSession) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  133. return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
  134. });
  135. });
  136. });
  137. },
  138. findByUsername: (sessionId, username, cb) => {
  139. db.models.user.find({ username }, (err, account) => {
  140. if (err) throw err;
  141. else if (account.length == 0) {
  142. return cb({
  143. status: 'error',
  144. message: 'Username cannot be found'
  145. });
  146. } else {
  147. account = account[0];
  148. return cb({
  149. status: 'success',
  150. data: {
  151. _id: account._id,
  152. username: account.username,
  153. role: account.role,
  154. email: account.email.address,
  155. password: '',
  156. createdAt: account.createdAt,
  157. statistics: account.statistics
  158. }
  159. });
  160. }
  161. });
  162. },
  163. findBySession: (sessionId, cb) => {
  164. cache.hget('sessions', sessionId, (err, session) => {
  165. if (err || !session) return cb({ 'status': 'error', message: err });
  166. if (!session.userSessionId) return cb({ 'status': 'error', message: 'You are not logged in' });
  167. cache.hget('userSessions', session.userSessionId, (err, userSession) => {
  168. if (err || !userSession) return cb({ 'status': 'error', message: err });
  169. if (!userSession) return cb({ 'status': 'error', message: 'You are not logged in' });
  170. db.models.user.findOne({ _id: userSession.userId }, (err, user) => {
  171. if (err) { throw err; } else if (user) {
  172. return cb({
  173. status: 'success',
  174. data: user
  175. });
  176. }
  177. });
  178. });
  179. });
  180. },
  181. update: (sessionId, user_id, property, value, cb) => {
  182. db.models.user.findOne({ _id: user_id }, (err, user) => {
  183. if (err) throw err;
  184. else if (!user) cb({ status: 'error', message: 'Invalid User ID' });
  185. else if (user[property] !== undefined && user[property] !== value) {
  186. if (property == 'services.password.password') {
  187. bcrypt.compare(user[property], value, (err, res) => {
  188. if (err) throw err;
  189. bcrypt.genSalt(10, (err, salt) => {
  190. if (err) throw err;
  191. bcrypt.hash(value, salt, (err, hash) => {
  192. if (err) throw err;
  193. user[property] = hash;
  194. });
  195. });
  196. });
  197. } else user[property] = value;
  198. user.save(err => {
  199. if (err) cb({ status: 'error', message: err.message });
  200. else cb({ status: 'success', message: 'Field saved successfully' });
  201. });
  202. } else {
  203. cb({ status: 'error', message: 'Field has not changed' });
  204. }
  205. });
  206. },
  207. };