const db = require("../db.js"); var CryptoJS = require('crypto-js'); class UserRepository { login(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(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); } getUser(token) { return new Promise((res,rej) => { db.search(['token', token]). on('data', (data) => { res(data); }). on('error', function (err) { let error = new Error("DB error"); error.name = "InternalError"; rej(error); }). on('close', function () { let error = new Error("Token invalid"); error.name = "TokenInvalid"; rej(error); }). on('end', function () { let error = new Error("Token invalid"); error.name = "TokenInvalid"; rej(error); }); }); } getByID(id){ return db.get("user:" + id); } } let userRepository = null; function getSingleton() { return userRepository = ( userRepository === null ? new UserRepository(): userRepository); } module.exports = getSingleton();