users.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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) => data[0]);
  56. }
  57. getByID(id){
  58. return db.get("user:" + id);
  59. }
  60. }
  61. let userRepository = null;
  62. function getSingleton() {
  63. return userRepository = ( userRepository === null ? new UserRepository(): userRepository);
  64. }
  65. module.exports = getSingleton();