12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- 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 db.search(['token', token]).then((data) => {
- if(data.length === 0) throw 'No such user ' + token;
- return data[0];
- });
- }
- getByID(id){
- return db.get("user:" + id);
- }
- save(item) {
- return db.put("user:" + item.username, item);
- }
- dropChannel(channel) {
- return db.search(['currentGame', 'channel', channel]).then((data) => {
- console.log("Found channel user");
- console.log(data);
- let proms = [];
- data.forEach((user) => {
- user.currentGame.channel = "";
- proms.push(this.save(user));
- });
- return Promise.all(proms);
- });
- }
- }
- let userRepository = null;
- function getSingleton() {
- return userRepository = ( userRepository === null ? new UserRepository(): userRepository);
- }
- module.exports = getSingleton();
|