123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- 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();
|