users.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. const db = require("../db.js");
  2. var CryptoJS = require('crypto-js');
  3. class UserRepository {
  4. login(params){
  5. const {
  6. username,
  7. password
  8. } = params;
  9. return db.get('user:' + username).
  10. then((data) => {
  11. if (data.password === CryptoJS.SHA256(data.salt + password).toString()) {
  12. // match
  13. // generate token
  14. let Token = CryptoJS.SHA256(Math.random().toString() + data.salt).toString();
  15. data.token = Token;
  16. return db.put('user:' + username, data).then(() => data);
  17. }
  18. let error = new Error("Bad Credentials");
  19. error.name = "BadCredentials";
  20. throw error;
  21. });
  22. }
  23. register(params) {
  24. const {
  25. username,
  26. password,
  27. email
  28. } = params;
  29. const hashFn = CryptoJS.SHA256;
  30. const salt = CryptoJS.lib.WordArray.random(128 / 8).toString();
  31. const hash = hashFn(salt + password).toString();
  32. const newuser = {
  33. email,
  34. password: hash,
  35. salt: salt,
  36. username
  37. };
  38. //check if username exists
  39. return db.get('user:' + username).
  40. then((data) => {
  41. let error = new Error("Username exists: " + username);
  42. error.name = "UsernameExists";
  43. throw error;
  44. }).
  45. catch((err) => {
  46. if( err.name === "NotFoundError" ) {
  47. //register
  48. return db.put('user:' + username, newuser);
  49. }
  50. throw err;
  51. }).
  52. then(() => newuser);
  53. }
  54. getUser(token) {
  55. return db.search(['token', token]).then((data) => {
  56. if(data.length === 0) throw 'No such user ' + token;
  57. return data[0];
  58. });
  59. }
  60. getByID(id){
  61. return db.get("user:" + id);
  62. }
  63. save(item) {
  64. return db.put("user:" + item.username, item);
  65. }
  66. dropChannel(channel) {
  67. return db.search(['currentGame', 'channel', channel]).then((data) => {
  68. console.log("Found channel user");
  69. console.log(data);
  70. let proms = [];
  71. data.forEach((user) => {
  72. user.currentGame.channel = "";
  73. proms.push(this.save(user));
  74. });
  75. return Promise.all(proms);
  76. });
  77. }
  78. }
  79. let userRepository = null;
  80. function getSingleton() {
  81. return userRepository = ( userRepository === null ? new UserRepository(): userRepository);
  82. }
  83. module.exports = getSingleton();