users.js 8.6 KB

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