users.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. identifier = identifier.toLowerCase();
  13. async.waterfall([
  14. // check if a user with the requested identifier exists
  15. (next) => db.models.user.findOne({
  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. console.log(response, 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. } else {
  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. },
  125. logout: (session, cb) => {
  126. cache.hget('sessions', session.sessionId, (err, session) => {
  127. if (err || !session) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  128. cache.hdel('sessions', session.sessionId, (err) => {
  129. if (err) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  130. return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
  131. });
  132. });
  133. },
  134. findByUsername: (session, username, cb) => {
  135. db.models.user.find({ username }, (err, account) => {
  136. if (err) throw err;
  137. else if (account.length == 0) {
  138. return cb({
  139. status: 'error',
  140. message: 'Username cannot be found'
  141. });
  142. } else {
  143. account = account[0];
  144. return cb({
  145. status: 'success',
  146. data: {
  147. _id: account._id,
  148. username: account.username,
  149. role: account.role,
  150. email: account.email.address,
  151. password: '',
  152. createdAt: account.createdAt,
  153. statistics: account.statistics,
  154. liked: account.liked,
  155. disliked: account.disliked
  156. }
  157. });
  158. }
  159. });
  160. },
  161. //TODO Fix security issues
  162. findBySession: (session, cb) => {
  163. cache.hget('sessions', session.sessionId, (err, session) => {
  164. if (err) return cb({ 'status': 'error', message: err });
  165. if (!session) return cb({ 'status': 'error', message: 'You are not logged in' });
  166. db.models.user.findOne({ _id: session.userId }, {username: 1, "email.address": 1}, (err, user) => {
  167. if (err) { throw err; } else if (user) {
  168. return cb({
  169. status: 'success',
  170. data: user
  171. });
  172. }
  173. });
  174. });
  175. },
  176. updateUsername: hooks.loginRequired((session, newUsername, cb, userId) => {
  177. db.models.user.findOne({ _id: userId }, (err, user) => {
  178. if (err) console.error(err);
  179. if (!user) return cb({ status: 'error', message: 'User not found.' });
  180. if (user.username !== newUsername) {
  181. if (user.username.toLowerCase() !== newUsername.toLowerCase()) {
  182. db.models.user.findOne({username: new RegExp(`^${newUsername}$`, 'i')}, (err, _user) => {
  183. if (err) return cb({ status: 'error', message: err.message });
  184. if (_user) return cb({ status: 'failure', message: 'That username is already in use.' });
  185. db.models.user.update({_id: userId}, {$set: {username: newUsername}}, (err) => {
  186. if (err) return cb({ status: 'error', message: err.message });
  187. cb({ status: 'success', message: 'Username updated successfully.' });
  188. });
  189. });
  190. } else {
  191. db.models.user.update({_id: userId}, {$set: {username: newUsername}}, (err) => {
  192. if (err) return cb({ status: 'error', message: err.message });
  193. cb({ status: 'success', message: 'Username updated successfully.' });
  194. });
  195. }
  196. } else cb({ status: 'error', message: 'Username has not changed. Your new username cannot be the same as your old username.' });
  197. });
  198. }),
  199. updateEmail: hooks.loginRequired((session, newEmail, cb, userId) => {
  200. newEmail = newEmail.toLowerCase();
  201. db.models.user.findOne({ _id: userId }, (err, user) => {
  202. if (err) console.error(err);
  203. if (!user) return cb({ status: 'error', message: 'User not found.' });
  204. if (user.email.address !== newEmail) {
  205. db.models.user.findOne({"email.address": newEmail}, (err, _user) => {
  206. if (err) return cb({ status: 'error', message: err.message });
  207. if (_user) return cb({ status: 'failure', message: 'That email is already in use.' });
  208. db.models.user.update({_id: userId}, {$set: {"email.address": newEmail}}, (err) => {
  209. if (err) return cb({ status: 'error', message: err.message });
  210. cb({ status: 'success', message: 'Email updated successfully.' });
  211. });
  212. });
  213. } else cb({ status: 'error', message: 'Email has not changed. Your new email cannot be the same as your old email.' });
  214. });
  215. })
  216. };