users.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. const sha256 = require('sha256');
  11. module.exports = {
  12. login: (session, identifier, password, cb) => {
  13. identifier = identifier.toLowerCase();
  14. async.waterfall([
  15. // check if a user with the requested identifier exists
  16. (next) => db.models.user.findOne({
  17. $or: [{ 'username': identifier }, { 'email.address': identifier }]
  18. }, next),
  19. // if the user doesn't exist, respond with a failure
  20. // otherwise compare the requested password and the actual users password
  21. (user, next) => {
  22. if (!user) return next(true, { status: 'failure', message: 'User not found' });
  23. bcrypt.compare(sha256(password), user.services.password.password, (err, match) => {
  24. if (err) return next(err);
  25. // if the passwords match
  26. if (match) {
  27. // store the session in the cache
  28. let sessionId = utils.guid();
  29. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, user._id), (err) => {
  30. if (!err) {
  31. //TODO See if it is necessary to add new SID to socket.
  32. next(null, { status: 'success', message: 'Login successful', user, SID: sessionId });
  33. } else {
  34. next(null, { status: 'failure', message: 'Something went wrong' });
  35. }
  36. });
  37. }
  38. else {
  39. next(null, { status: 'failure', message: 'Incorrect password' });
  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(sha256(password), salt, next)
  88. },
  89. // save the new user to the database
  90. (hash, next) => {
  91. db.models.user.create({
  92. _id: utils.generateRandomString(12),//TODO Check if exists
  93. username,
  94. email: {
  95. address: email,
  96. verificationToken: utils.generateRandomString(64)
  97. },
  98. services: {
  99. password: {
  100. password: hash
  101. }
  102. }
  103. }, next);
  104. },
  105. // respond with the new user
  106. (newUser, next) => {
  107. //TODO Send verification email
  108. next(null, { status: 'success', user: newUser })
  109. }
  110. ], (err, payload) => {
  111. // log this error somewhere
  112. if (err && err !== true) {
  113. console.error(err);
  114. return cb({ status: 'error', message: 'An error occurred while registering for an account' });
  115. } else {
  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. },
  126. logout: (session, cb) => {
  127. cache.hget('sessions', session.sessionId, (err, session) => {
  128. if (err || !session) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  129. cache.hdel('sessions', session.sessionId, (err) => {
  130. if (err) return cb({ 'status': 'failure', message: 'Something went wrong while logging you out.' });
  131. return cb({ 'status': 'success', message: 'You have been successfully logged out.' });
  132. });
  133. });
  134. },
  135. findByUsername: (session, username, cb) => {
  136. db.models.user.find({ username }, (err, account) => {
  137. if (err) throw err;
  138. else if (account.length == 0) {
  139. return cb({
  140. status: 'error',
  141. message: 'Username cannot be found'
  142. });
  143. } else {
  144. account = account[0];
  145. return cb({
  146. status: 'success',
  147. data: {
  148. _id: account._id,
  149. username: account.username,
  150. role: account.role,
  151. email: account.email.address,
  152. password: '',
  153. createdAt: account.createdAt,
  154. statistics: account.statistics,
  155. liked: account.liked,
  156. disliked: account.disliked
  157. }
  158. });
  159. }
  160. });
  161. },
  162. //TODO Fix security issues
  163. findBySession: (session, cb) => {
  164. cache.hget('sessions', session.sessionId, (err, session) => {
  165. if (err) return cb({ 'status': 'error', message: err });
  166. if (!session) return cb({ 'status': 'error', message: 'You are not logged in' });
  167. db.models.user.findOne({ _id: session.userId }, {username: 1, "email.address": 1}, (err, user) => {
  168. if (err) { throw err; } else if (user) {
  169. return cb({
  170. status: 'success',
  171. data: user
  172. });
  173. }
  174. });
  175. });
  176. },
  177. updateUsername: hooks.loginRequired((session, newUsername, cb, userId) => {
  178. db.models.user.findOne({ _id: userId }, (err, user) => {
  179. if (err) console.error(err);
  180. if (!user) return cb({ status: 'error', message: 'User not found.' });
  181. if (user.username !== newUsername) {
  182. if (user.username.toLowerCase() !== newUsername.toLowerCase()) {
  183. db.models.user.findOne({username: new RegExp(`^${newUsername}$`, 'i')}, (err, _user) => {
  184. if (err) return cb({ status: 'error', message: err.message });
  185. if (_user) return cb({ status: 'failure', message: 'That username is already in use.' });
  186. db.models.user.update({_id: userId}, {$set: {username: newUsername}}, (err) => {
  187. if (err) return cb({ status: 'error', message: err.message });
  188. cb({ status: 'success', message: 'Username updated successfully.' });
  189. });
  190. });
  191. } else {
  192. db.models.user.update({_id: userId}, {$set: {username: newUsername}}, (err) => {
  193. if (err) return cb({ status: 'error', message: err.message });
  194. cb({ status: 'success', message: 'Username updated successfully.' });
  195. });
  196. }
  197. } else cb({ status: 'error', message: 'Username has not changed. Your new username cannot be the same as your old username.' });
  198. });
  199. }),
  200. updateEmail: hooks.loginRequired((session, newEmail, cb, userId) => {
  201. newEmail = newEmail.toLowerCase();
  202. db.models.user.findOne({ _id: userId }, (err, user) => {
  203. if (err) console.error(err);
  204. if (!user) return cb({ status: 'error', message: 'User not found.' });
  205. if (user.email.address !== newEmail) {
  206. db.models.user.findOne({"email.address": newEmail}, (err, _user) => {
  207. if (err) return cb({ status: 'error', message: err.message });
  208. if (_user) return cb({ status: 'failure', message: 'That email is already in use.' });
  209. db.models.user.update({_id: userId}, {$set: {"email.address": newEmail}}, (err) => {
  210. if (err) return cb({ status: 'error', message: err.message });
  211. cb({ status: 'success', message: 'Email updated successfully.' });
  212. });
  213. });
  214. } else cb({ status: 'error', message: 'Email has not changed. Your new email cannot be the same as your old email.' });
  215. });
  216. })
  217. };