const db = require("../db.js"); var CryptoJS = require('crypto-js'); const userRepository = { login: function(params){ const { username, password } = params; return db.get('user:' + username). then((data) => { if (data.password === CryptoJS.SHA256(data.salt + password).toString()) { // match // generate token let Token = CryptoJS.SHA256(Math.random().toString() + data.salt).toString(); data.token = Token; return db.put('user:' + username, data).then(() => data); } let error = new Error("Bad Credentials"); error.name = "BadCredentials"; throw error; }); }, register: function(params) { const { username, password, email } = params; const hashFn = CryptoJS.SHA256; const salt = CryptoJS.lib.WordArray.random(128 / 8).toString(); const hash = hashFn(salt + password).toString(); const newuser = { email, password: hash, salt: salt, username }; //check if username exists return db.get('user:' + username). then((data) => { let error = new Error("Username exists: " + username); error.name = "UsernameExists"; throw error; }). catch((err) => { if( err.name === "NotFoundError" ) { //register return db.put('user:' + username, newuser); } throw err; }). then(() => newuser); }, getByID: function(id){ return db.get("user:" + id); }, } module.exports = userRepository;