users.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 new Promise((res,rej) => {
  56. db.search(['token', token]).
  57. on('data', (data) => {
  58. res(data);
  59. }).
  60. on('error', function (err) {
  61. let error = new Error("DB error");
  62. error.name = "InternalError";
  63. rej(error);
  64. }).
  65. on('close', function () {
  66. let error = new Error("Token invalid");
  67. error.name = "TokenInvalid";
  68. rej(error);
  69. }).
  70. on('end', function () {
  71. let error = new Error("Token invalid");
  72. error.name = "TokenInvalid";
  73. rej(error);
  74. });
  75. });
  76. }
  77. getByID(id){
  78. return db.get("user:" + id);
  79. }
  80. }
  81. let userRepository = null;
  82. function getSingleton() {
  83. return userRepository = ( userRepository === null ? new UserRepository(): userRepository);
  84. }
  85. module.exports = getSingleton();