4

I have an authentication module with methods I would like to use across the server. I would like to use the rndString() method in both the module itself and export it to use in other ways throughout the app. What am I doing wrong to cause this to not work?

const crypto = require('crypto');

let sha512 = (password, salt) => {
    let hash = crypto.createHmac('sha512', salt);
    hash.update(password);
    let value = hash.digest('hex');
    return {
        salt: salt,
        passwordHash: value
    }
};

module.exports = {
    rndString: (length) => {
        return crypto.randomBytes(Math.ceil(length/2))
            .toString('hex')
            .slice(0,length);
    },
    hashId: (id) => {
        let key  = crypto.createCipher('aes-128-cbc', 'kranky');
        let hash = key.update(id, 'utf8', 'hex');
        hash += key.final('hex');
        return hash;
    },
    saltPass: (userpassword) => {
        let salt         = this.rndString(16);
        let passwordData = sha512(userpassword, salt);
        return {
            hashValue: passwordData.passwordHash,
            salt: passwordData.salt
        }
    },
    userSalt: (userpassword, salt) => {
        let passwordData = sha512(userpassword, salt);
        return passwordData.passwordHash;
    }
};

1 Answer 1

2

You are referencing the rndString function as this.rndString inside a function that is assigned to the object key here:

saltPass: (userpassword) => {
    let salt         = this.rndString(16);
    let passwordData = sha512(userpassword, salt);

In this case, this is actually referring to the function, rather than the object in which the function is nested. You can alternatively use ES6 method syntax to get the right context:

module.exports = {
  rndString(length) {
    return crypto.randomBytes(Math.ceil(length/2))
        .toString('hex')
        .slice(0,length);
  },
  hashId(id) {
    let key  = crypto.createCipher('aes-128-cbc', 'kranky');
    let hash = key.update(id, 'utf8', 'hex');
    hash += key.final('hex');
    return hash;
  },
  saltPass(userpassword) {
    let salt         = this.rndString(16);
    let passwordData = sha512(userpassword, salt);
    return {
        hashValue: passwordData.passwordHash,
        salt: passwordData.salt
    }
  },
  userSalt(userpassword, salt) {
    let passwordData = sha512(userpassword, salt);
    return passwordData.passwordHash;
  }
}

You can find good documentation here for object method shorthand: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.