users.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const db = require("../db.js");
  2. var CryptoJS = require('crypto-js');
  3. const userRepository = {
  4. login: function(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: function(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. getByID: function(id){
  55. return db.get("user:" + id);
  56. },
  57. }
  58. module.exports = userRepository;