12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- 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;
|