Skip to content

Added Promise wrap to async methods #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 75 additions & 35 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ require(["bcrypt"], function(bcrypt) {

Usage - Sync
------------
To hash a password:
To hash a password:

```javascript
var bcrypt = require('bcryptjs');
Expand All @@ -69,7 +69,7 @@ var hash = bcrypt.hashSync("B4c0/\/", salt);
// Store hash in your password DB.
```

To check a password:
To check a password:

```javascript
// Load hash from your password DB.
Expand All @@ -85,7 +85,7 @@ var hash = bcrypt.hashSync('bacon', 8);

Usage - Async
-------------
To hash a password:
To hash a password:

```javascript
var bcrypt = require('bcryptjs');
Expand All @@ -96,7 +96,7 @@ bcrypt.genSalt(10, function(err, salt) {
});
```

To check a password:
To check a password:

```javascript
// Load hash from your password DB.
Expand All @@ -115,6 +115,46 @@ bcrypt.hash('bacon', 8, function(err, hash) {
});
```

Usage-Promises
--------------
When bcrypt async functions are called without a callback promise is returned.

To hash a password:

```javascript
var bcrypt = require('bcryptjs');
bcrypt.genSalt(10)
.then(function(salt) {
return bcrypt.hash("B4c0/\/", salt);
}, function(err) {//...})
.then(function(hash) {
// Store hash in your password DB.
}, function(err) {//...});
```

To check a password:

```javascript
// Load hash from your password DB.
bcrypt.compare("B4c0/\/", hash)
.then(function(res) {
// res == true
},
function(err) {//...});
bcrypt.compare("not_bacon", hash)
.then(function(res) {
// res == false
},
function(err) {//...});
```

Auto-gen a salt and hash:

```javascript
bcrypt.hash('bacon', 8)
.then(function(hash) {}, function(err) {});
```

API
---
### setRandomFallback(random)
Expand All @@ -125,8 +165,8 @@ seeded properly!

| Parameter | Type | Description
|-----------------|-----------------|---------------
| random | *function(number):!Array.<number>* | Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values.
| **@see** | | http://nodejs.org/api/crypto.html
| random | *function(number):!Array.<number>* | Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values.
| **@see** | | http://nodejs.org/api/crypto.html
| **@see** | | http://www.w3.org/TR/WebCryptoAPI/

**Hint:** You might use [isaac.js](https://github.com/rubycon/isaac.js) as a CSPRNG but you still have to make sure to
Expand All @@ -138,84 +178,84 @@ Synchronously generates a salt.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| rounds | *number* | Number of rounds to use, defaults to 10 if omitted
| seed_length | *number* | Not supported.
| **@returns** | *string* | Resulting salt
| **@throws** | *Error* | If a random fallback is required but not set
| rounds | *number* | Number of rounds to use, defaults to 10 if omitted
| seed_length | *number* | Not supported.
| **@returns** | *string* | Resulting salt
| **@throws** | *Error* | If a random fallback is required but not set

### genSalt(rounds=, seed_length=, callback)

Asynchronously generates a salt.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| rounds | *number | function(Error, string=)* | Number of rounds to use, defaults to 10 if omitted
| seed_length | *number | function(Error, string=)* | Not supported.
| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting salt
| rounds | *number | function(Error, string=)* | Number of rounds to use, defaults to 10 if omitted
| seed_length | *number | function(Error, string=)* | Not supported.
| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting salt

### hashSync(s, salt=)

Synchronously generates a hash for the given string.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| s | *string* | String to hash
| salt | *number | string* | Salt length to generate or salt to use, default to 10
| **@returns** | *string* | Resulting hash
| s | *string* | String to hash
| salt | *number | string* | Salt length to generate or salt to use, default to 10
| **@returns** | *string* | Resulting hash

### hash(s, salt, callback, progressCallback=)

Asynchronously generates a hash for the given string.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| s | *string* | String to hash
| salt | *number | string* | Salt length to generate or salt to use
| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting hash
| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
| s | *string* | String to hash
| salt | *number | string* | Salt length to generate or salt to use
| callback | *function(Error, string=)* | Callback receiving the error, if any, and the resulting hash
| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.

### compareSync(s, hash)

Synchronously tests a string against a hash.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| s | *string* | String to compare
| hash | *string* | Hash to test against
| **@returns** | *boolean* | true if matching, otherwise false
| **@throws** | *Error* | If an argument is illegal
| s | *string* | String to compare
| hash | *string* | Hash to test against
| **@returns** | *boolean* | true if matching, otherwise false
| **@throws** | *Error* | If an argument is illegal

### compare(s, hash, callback, progressCallback=)

Asynchronously compares the given data against the given hash.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| s | *string* | Data to compare
| hash | *string* | Data to be compared to
| callback | *function(Error, boolean)* | Callback receiving the error, if any, otherwise the result
| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
| **@throws** | *Error* | If the callback argument is invalid
| s | *string* | Data to compare
| hash | *string* | Data to be compared to
| callback | *function(Error, boolean)* | Callback receiving the error, if any, otherwise the result
| progressCallback | *function(number)* | Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per `MAX_EXECUTION_TIME = 100` ms.
| **@throws** | *Error* | If the callback argument is invalid

### getRounds(hash)

Gets the number of rounds used to encrypt the specified hash.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| hash | *string* | Hash to extract the used number of rounds from
| **@returns** | *number* | Number of rounds used
| **@throws** | *Error* | If hash is not a string
| hash | *string* | Hash to extract the used number of rounds from
| **@returns** | *number* | Number of rounds used
| **@throws** | *Error* | If hash is not a string

### getSalt(hash)

Gets the salt portion from a hash. Does not validate the hash.

| Parameter | Type | Description
|-----------------|-----------------|---------------
| hash | *string* | Hash to extract the salt from
| **@returns** | *string* | Extracted salt part
| **@throws** | *Error* | If `hash` is not a string or otherwise invalid
| hash | *string* | Hash to extract the salt from
| **@returns** | *string* | Extracted salt part
| **@throws** | *Error* | If `hash` is not a string or otherwise invalid


Command line
Expand Down
55 changes: 55 additions & 0 deletions dist/bcrypt.js
Original file line number Diff line number Diff line change
Expand Up @@ -1220,5 +1220,60 @@
*/
bcrypt.decodeBase64 = base64_decode;

/**
* Names of async bcrypt methods
* @type {Array.<string>}
* @inner
*/
var asyncMethodNames = [
'hash',
'genSalt',
'compare'
];

asyncMethodNames.forEach(function(methodName) {
bcrypt[methodName] = makePromisePolyfill(bcrypt[methodName]);
});

/**
* Curries original method
* Returns a promise if last argument passed to the curried function is a function
* Calls a callback-style function if last argument passed to the curried function is not a function
* @function
* @param {function(data1,data2,callback,?progressCallback)} async bcrypt method
* @returns {?Promise}
* @inner
*/
function makePromisePolyfill(method) {
return function() {
var args = Array.prototype.slice.call(arguments);
var isPromise = typeof args[args.length] !== 'function';

if (isPromise) return makePromise(method, args);
else return method.apply(bcrypt, args);
}
}

/**
* Wraps callback-style function in a promise
* @function
* @param {function(data1,data2,callback,?progressCallback)} callee method
* @param {!Array.<(string|number|function)=>} array of callee method's arguments
* @returns {Promise}
* @inner
*/
function makePromise(method, args) {
return new Promise(function(resolve, reject) {
function callback(err, res) {
if (err) return reject(err);

resolve(res);
}

args.push(callback);
method.apply(bcrypt, args);
});
}

return bcrypt;
}));
55 changes: 55 additions & 0 deletions src/promisePolyfill.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Names of async bcrypt methods
* @type {Array.<string>}
* @inner
*/
var asyncMethodNames = [
'hash',
'genSalt',
'compare'
];

asyncMethodNames.forEach(function(methodName) {
bcrypt[methodName] = makePromisePolyfill(bcrypt[methodName]);
});

/**
* Curries original method
* Returns a promise if last argument passed to the curried function is a function
* Calls a callback-style function if last argument passed to the curried function is not a function
* @function
* @param {function(data1,data2,callback,?progressCallback)} async bcrypt method
* @returns {?Promise}
* @inner
*/
function makePromisePolyfill(method) {
return function() {
var args = Array.prototype.slice.call(arguments);
var isPromise = typeof args[args.length] !== 'function';
var promisesSupported = typeof Promise !== 'undefined';

if (isPromise && promisesSupported) return makePromise(method, args);
else return method.apply(bcrypt, args);
}
}

/**
* Wraps callback-style function in a promise
* @function
* @param {function(data1,data2,callback,?progressCallback)} callee method
* @param {!Array.<(string|number|function)=>} array of callee method's arguments
* @returns {Promise}
* @inner
*/
function makePromise(method, args) {
return new Promise(function(resolve, reject) {
function callback(err, res) {
if (err) return reject(err);

resolve(res);
}

args.push(callback);
method.apply(bcrypt, args);
});
}
2 changes: 2 additions & 0 deletions src/wrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,7 @@

//? include("bcrypt.js");

//? include("promisePolyfill.js");

return bcrypt;
}));
Loading