-
Notifications
You must be signed in to change notification settings - Fork 27
/
security.util.js
38 lines (34 loc) · 1.06 KB
/
security.util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const util = require('util');
const randomBytes = util.promisify(crypto.randomBytes, crypto);
const bcryptHash = util.promisify(bcrypt.hash, bcrypt);
const compare = util.promisify(bcrypt.compare, bcrypt);
/**
* @desc Generates random string, useful for creating secure tokens
*
* @return {string} - random string
*/
exports.generateSecureToken = async (tokenLength = 48) => {
const buf = await randomBytes(tokenLength);
return buf.toString('hex');
};
/**
* @desc Generate hash from any string. Could be used to generate a hash from password
*
* @param text {string} - a text to produce hash from
* @return {Promise} - a hash from input text
*/
exports.getHash = (text) => {
return bcryptHash(text, 10);
};
/**
* @desc Compares if text and hash are equal
*
* @param text {string} - a text to compare with hash
* @param hash {string} - a hash to compare with text
* @return {Promise} - are hash and text equal
*/
exports.compareTextWithHash = (text, hash) => {
return compare(text, hash);
};