npm.io
0.5.0 • Published 6 years ago

dashmachine-auth-request

Licence
MIT
Version
0.5.0
Deps
5
Size
83 kB
Vulns
0
Weekly
0

dashmachine-auth-request

A Library to Support Auth Requests fos Dash Platform Web Dapps.

Usage

Overview

This is an experimental project to explore methods of achieving a login flow with the Dash Platform.

The current specification can be found here.

This library contains the impementation of the server-side component. The client side component is the Dash Chrome Wallet.

Installation

Install as an npm package
npm i dashmachine-auth-request
Set Options

Sample options module

exports.options = {
  connection: {
    apps: {
      loginContract: {
        contractId: '9GHRxvyYDmWz7pBKRjPnxjsJbbgKLngtejWWp3kEY1vB',
      },
      dpnsContract: {
        contractId: '295xRRRMGYyAruG39XdAibaU9jMAzxhknkkAxFE7uVkW',
      },
    },
    network: 'testnet',
    seeds: { service: '34.215.175.142:3000' },
  },
  polling: {
    responsePollingTimeout: 30000,
    responsePollingFrequency: 5000,
    reponsePollingDelay: 3000,
  },
};

Usage

See the Examples below for possible usage.

Please note this library and documentation is experimental and in the early stages of development so should not be used in a production environment

Development

The following sections are only of interest if you wish to develop this project.

Clone this repo to a suitable location and switch into the project directory

git clone https://github.com/cloudwheels/dapp-auth-demo && cd dapp-auth-demo

It is recommended to install the npm nodemon package globally

npm i -g nodemon

The project can then be started in development mode using the following npm script:

npm run develop

Tests

Tests are configured using Jest and Supertest. The following scripts are available to run different sections of tests, optionally in watch mode:

npm test

Single run of all tests

npm test:watch

Runs all tests in watch mode

npm test-unit:watch

Runs only unit tests in watch mode

npm test-routes:watch

Runs only route tests (using supertest) in watch mode

npm test-services:watch

Runs only route services in watch mode

Generated Documentation (experimental)

The following is automatically generated from jsdoc annotaions in the code using the documentaion.js npm package.

You will need to install the documentation package globally:

npm i -g documentation

The run the npm scripts to generate the docs

docs-readme:lib



docs-readme:models
Library
Table of Contents
AuthRequest

AuthRequest class - A request for authorisation

Examples

Note: the libarary has been updated so that the global connection object is no loger automatically connected & disconnected for each method. You must call the (undocumented) connect() and disconnect() methods before (and after) the other calls.

const AuthRequest = require('./lib/auth-request');
const Options = require('./options');

(async () => {
try {
const req = new AuthRequest(
1,
'bob',
'1234',
'alice',
'uniform analyst paper father soldier toe lesson fetch exhaust jazz swim response',
'Web dApp Sample',
Options.options,
'Tweets are greets',
);

req.vendor = {
name: 'alice',
id: 'Aobc5KKaA4ZqzP7unc6WawQXQEK2S3y6EwrmvJLLn1ui',
identityId: 'CheZBPQHztvLNqN67i4KxcTU1XmDz7qG85X1XeJbc7K5',
identity: {
id: 'CheZBPQHztvLNqN67i4KxcTU1XmDz7qG85X1XeJbc7K5',
publicKeys: [
{
id: 0,
type: 0,
data: 'A0/qSE6tis4l6BtQlTXB2PHW+WV+Iy0rpF5hAvX8hDRz',
isEnabled: true,
},
],
balance: 9686447,
},
publicKey: 'A0/qSE6tis4l6BtQlTXB2PHW+WV+Iy0rpF5hAvX8hDRz',
privateKey:
'40148175614f062fb0b4e5c519be7b6f57b872ebb55ea719376322fd12547bff',
};

let createdDoc,
submittedDoc,
mockResponse,
foundResponses,
verifiedRequest;
try {
createdDoc = await req.create();
console.log(`createdDoc:${JSON.stringify(createdDoc)}`);
} catch (e) {
console.log(`createdDoc ERROR:${e}`);
}
if (createdDoc.success) {
try {
submittedDoc = await req.submit();
console.log(`submittedDoc:${JSON.stringify(submittedDoc)}`);
} catch (e) {
console.log(`submittedDoc ERROR:${e}`);
}
}

if (submittedDoc.success) {
try {
req.test_enduserMnemonic =
'liar fee island situate deal exotic flat direct save bag fiscal news';
req.test_enduserPrivateKey =
'219c8a8f9376750cee9f06e0409718f2a1b88df4acc61bf9ed9cf252c8602768';
mockResponse = await req.mockReponse();
console.log(`mockResponse:${JSON.stringify(mockResponse)}`);
} catch (e) {
console.log(`mockResponse ERROR:${e}`);
}
}
if (mockResponse.success) {
try {
foundResponses = await req.findResponses();
console.log(
`foundResponses:${JSON.stringify(foundResponses)}`,
);
} catch (e) {
console.log(`foundResponses ERROR:${e}`);
}
}
if (foundResponses.success) {
try {
verifiedRequest = await req.verify();
console.log(
`verifiedRequest:${JSON.stringify(verifiedRequest)}`,
);
} catch (e) {
console.log(`verifiedRequest ERROR:${e}`);
}
}
} catch (e) {
console.log(`errors: ${e}`); ////
}
})();
findEnduser

if this._enduser==null looks up user details from the network using the supplied connection details //

Returns Object this._enduser

findVendor

if this.vendor==null looks up user details from the network using the supplied connection details

Returns Object this._vendor

create

creates a request document of the required type if the username, pin and other options are valid ////

Returns Object the prepared request document

submit

Submits the document set as the value of this._requestDoc returns this._submittedRequestDoc if successful

Returns any Promise<{ success: boolean; data: any; error?: undefined; message?: undefined; } | { error: boolean; message: any; success?: undefined; data?: undefined; }>

mockReponse

Mock Reponse with known user private keys

findResponses

poll for responses matching criteria

Returns Object this._enduser

verify

Verifies all found responses to deternine if loginis successful

vendor
Parameters
enduser
Parameters
requestDoc
Parameters
responseDocType
Parameters
userResponses
Parameters
temp_timestamp
Parameters
entropy
Parameters
test_enduserPrivateKey
Parameters
  • newTest_enduserPrivateKey string
test_enduserMnemonic
Parameters
  • newTest_enduserMnemonic string
DashAccount

DashAccount class - represents a Dash Platform Account

Properties
  • mnemonic string The account mnemonic
mnemonic
Parameters
DashConnection

DashConnection class - represents a connection to Dash Platform

Properties
  • network string Network to connect to i.e. 'testet' (default), mainnet
  • mnemonic string Account mnemonic to use for the connection
  • apps Object named app identities
  • seeds Object additonal options, overrides other paramaters
  • client Object the connection instance client
connect

Intialises connection

disconnect

Closes and disconnect the connection

network
Parameters
mnemonic
Parameters
apps
Parameters
options
Parameters
client
Parameters
  • newClient any
DashUser

DashUser class - represents a registered Dash Platform Username

Properties
  • id string Unique id fopr the user record - the id of the DPNS document which registered the name
  • name string The registered username
  • identityId string identityId associated with the username
  • identity Object full identity object of the identityId
  • publicKey string private Key Associated wwith the user identity
  • privateKey string private Key Associated wwith the user identity
id
Parameters
name
Parameters
identityId
Parameters
identity
Parameters
  • newIdentity
  • newIdentityId Object
publicKey
Parameters
privateKey
Parameters
find

Finds the registered username on the network

Parameters
  • nameToFind
  • connection
DashUser#toJSON

Returns the DashUser instance in JSON format

Returns JSON

DPNSDocument

Extends DataDocument

DPNSDocument class - represents a anme registraion documents from Dash Platform Name Service

AuthRequestDocument

Extends DataDocument

AuthRequestDocument class - represents login documents sumitted to or retrieved from Dash Platform

DataDocument

DataDocument class - represents data docuemnts sumitted to or retrieved from Dash Platform

Properties
  • dataContractId string dataContractId the document is validated against
  • ownerId string identityId of the owner / submitter of the document
  • data JSON actual data of the document represented as JSON
  • signature string the signature on the document
submit

submits the document instance using the passed in connection

Parameters
  • connection A DashJS client containing the account and keys for signing the doc
dataContractId
Parameters
id
Parameters
ownerId
Parameters
data
Parameters
find

finds one of more documents based on suplied query params

Parameters
  • connection string A DashJS connection, with options set for the locator of the docs to be retrieved
  • locator string The document name
  • query object Object containing array of query parameters

Returns Array array of found docuemnts

waitFor

Calls find() over specified period at specifed frequency until result tis returned

Parameters
  • connection string A DashJS connection, with options set for the locator of the docs to be retrieved
  • locator string The document name
  • query Object Object containing array of query parameters
  • timeout number Number of millseconds until rejecting as timed out
  • frequency number Frequency of calls to find() in millisenconds

Returns Promise<Object> promise for JSON Object {success:true, data:array of found docuemnts} if resolved {error: true, message:[error message]} if rejected

AuthResponseDocument

Extends DataDocument

AuthResponseDocument class - represents auth response documents sumitted to or retrieved from Dash Platform

Models
Table of Contents
DashAccount

DashAccount class - represents a Dash Platform Account

Properties
  • mnemonic string The account mnemonic
mnemonic
Parameters
DashUser

DashUser class - represents a registered Dash Platform Username

Properties
  • id string Unique id fopr the user record - the id of the DPNS document which registered the name
  • name string The registered username
  • identityId string identityId associated with the username
  • identity Object full identity object of the identityId
  • privateKey string private Key Associated wwith the user identity
id
Parameters
name
Parameters
identityId
Parameters
identity
Parameters
  • newIdentity
  • newIdentityId Object
privateKey
Parameters
find

Finds the registered username on the network

Parameters
  • nameToFind
  • connection
DashUser#toJSON

Returns the DashUser instance in JSON format

Returns JSON

DataDocument

DataDocument class - represents data docuemnts sumitted to or retrieved from Dash Platform

Properties
  • dataContractId string dataContractId the document is validated against
  • ownerId string identityId of the owner / submitter of the document
  • data JSON actual data of the document represented as JSON
  • signature string the signature on the document
submit

submits the document instance using the passed in connection

Parameters
  • connection A DashJS client containing the account and keys for signing the doc
dataContractId
Parameters
id
Parameters
ownerId
Parameters
data
Parameters
find

finds one of more documents based on suplied query params

Parameters
  • connection string A DashJS connection, with options set for the locator of the docs to be retrieved
  • locator string The document name
  • query object Object containing array of query parameters

Returns Array array of found docuemnts

waitFor

Calls find() over specified period at specifed frequency until result tis returned

Parameters
  • connection string A DashJS connection, with options set for the locator of the docs to be retrieved
  • locator string The document name
  • query Object Object containing array of query parameters
  • timeout number Number of millseconds until rejecting as timed out
  • frequency number Frequency of calls to find() in millisenconds

Returns Promise<Object> promise for JSON Object {success:true, data:array of found docuemnts} if resolved {error: true, message:[error message]} if rejected

DPNSDocument

Extends DataDocument

DPNSDocument class - represents a anme registraion documents from Dash Platform Name Service

LoginDocument

Extends DataDocument

LoginDocument class - represents login documents sumitted to or retrieved from Dash Platform

LoginResponseDocument

Extends DataDocument

LoginResponseDocument class - represents login documents sumitted to or retrieved from Dash Platform

Tweet

Tweet class - represents a user tweet

Properties
  • username string The registered username
  • message string tweet content
  • date string date of the tweet
username
Parameters
message
Parameters
date
Parameters
Services
Table of Contents
DashConnection

DashConnection class - represents a connection to Dash Platform

Properties
  • network string Network to connect to i.e. 'tesnet' (default), livenet
  • account Object An instance of the DashAccount class containing mnemonic etc to use for the connection
  • apps Object named app identities
  • options Object additonal options, overrides other paramaters
  • client Object the connection instance client
connect

Intialises connection

disconnect

Closes and disconnect the connection

network
Parameters
account
Parameters
apps
Parameters
options
Parameters
client
Parameters
  • newClient any

Keywords