Skip to content
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

WIP:add did auth storage tingo #477

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 1.3.13 (September 29, 2020)

- add did auth storage tingo
- [skip travis] update readme

## 1.3.12 (August 31, 2020)

- [skip travis] update readme
Expand Down
13 changes: 13 additions & 0 deletions did/did-auth-storage-tingo/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2018-2019 ArcBlock

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
51 changes: 51 additions & 0 deletions did/did-auth-storage-tingo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
![did-auth-storage-tingo](https://www.arcblock.io/.netlify/functions/badge/?text=did-auth-storage-tingo)

[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)

> Storage engine that uses tingo to store data, implements interfaces defined in `@arcblock/did-auth-storage`.


## Table of Contents

* [Install](#install)
* [Usage](#usage)
* [Contributors](#contributors)


## Install

```sh
npm install @arcblock/did-auth-storage-tingo
// or
yarn add @arcblock/did-auth-storage-tingo
```


## Usage

```js
const tingoStorage = require('@arcblock/did-auth-storage-tingo');

const storage = new tingoStorage({
dbPath: '/some/local/path',
collection: 'did_auth_tokens',
});

// Listen on events of the storage
storage.on('create', d => console.log('create', d));
storage.on('update', d => console.log('update', d));
storage.on('destroy', d => console.log('destroy', d));

(async () => {
const token = '123456';
const item = await storage.create(token);
})();
```


## Contributors

| Name | Website |
| ---------------- | -------------------------- |
| **wangshijun** | <https://ocap.arcblock.io> |
| **NateRobinson** | <https://ocap.arcblock.io> |
7 changes: 7 additions & 0 deletions did/did-auth-storage-tingo/docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

## Contributors

| Name | Website |
| ---------------- | -------------------------- |
| **wangshijun** | <https://ocap.arcblock.io> |
| **NateRobinson** | <https://ocap.arcblock.io> |
9 changes: 9 additions & 0 deletions did/did-auth-storage-tingo/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
browser: false,
clearMocks: true,
coverageDirectory: 'coverage',
testEnvironment: 'node',
testMatch: ['**/__tests__/**/*.js?(x)', '**/?(*.)+(spec).js?(x)'],
};
59 changes: 59 additions & 0 deletions did/did-auth-storage-tingo/lib/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Generate by [[email protected]](https://github.com/whxaxes/js2dts#readme)

import { EventEmitter } from 'events';
/**
* Defines the interface of DID-Auth Token Storage
* Which is used to persist state during the DID-Auth process in a dApp
*
* @class AuthStorage
* @see @arcblock/did-auth-storage-firebase
* @see @arcblock/did-auth-storage-mongo
* @see @arcblock/did-auth-storage-keystone
* @extends {EventEmitter}
*/
declare class AuthStorage extends EventEmitter {
/**
* Creates an instance of AuthStorage.
*
* @class
* @param {object} options
*/
constructor(options: any);
create(token: any, status?: string): void;
read(token: any): void;
update(token: any, updates: any): void;
delete(token: any): void;
exist(token: any, did: any): void;
}
declare class TingoAuthStorage extends AuthStorage {
collectionName: string;
options: _Lib.T100;
db: any;
/**
* Creates an instance of TingoAuthStorage.
*
* @class
* @param {Object} options { collection, url }
* @param {string} options.dbPath - tingodb connection string
* @param {string} [options.collection='did_auth_tokens'] - which collection to store did auth tokens
*/
constructor(options: _Lib.T100);
connectionFailed(err: any): void;
setCollection(collection: any): void;
collectionReady(): any;
read(token: any): any;
create(token: any, status?: string): any;
update(token: any, updates: any, upsert?: boolean): any;
delete(token: any): any;
exist(token: any, did: any): any;
clear(): any;
close(): void;
}
declare const _Lib: typeof TingoAuthStorage;
declare namespace _Lib {
export interface T100 {
dbPath: string;
collection?: string;
}
}
export = _Lib;
137 changes: 137 additions & 0 deletions did/did-auth-storage-tingo/lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/* eslint-disable max-len */
/* eslint-disable compat/compat */
/* eslint-disable prefer-destructuring */
/* eslint-disable no-param-reassign */
/* eslint-disable no-underscore-dangle */
const Db = require('tingodb')().Db;
const StorageInterface = require('@arcblock/did-auth-storage');

const debug = require('debug')(require('../package.json').name);

const promiseUpdateOrInsert = (collection, token, updates, upsert = false) =>
new Promise((resolve, reject) => {
collection.update({ token }, { $set: updates }, { upsert }, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
});

const promiseFindOne = (collection, condition) =>
new Promise((resolve, reject) => {
collection.findOne(condition, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
});

const promiseDelete = (collection, condition) =>
new Promise((resolve, reject) => {
collection.remove(condition, (err, result) => {
if (err) {
return reject(err);
}
return resolve(result);
});
});

module.exports = class TingoAuthStorage extends StorageInterface {
/**
* Creates an instance of TingoAuthStorage.
*
* @class
* @param {Object} options { collection, url }
* @param {string} options.dbPath - tingodb connection string
* @param {string} [options.collection='did_auth_tokens'] - which collection to store did auth tokens
*/
constructor(options) {
options = options || {};

super(options);

this.collectionName = options.collection || 'did_auth_tokens';
this.options = options;

if (options.dbPath) {
this.db = new Db(options.dbPath, {});
this.setCollection(this.db.collection(this.collectionName));
} else {
throw new Error('Connection strategy not found');
}
}

connectionFailed(err) {
throw err;
}

setCollection(collection) {
this.collectionReadyPromise = undefined;
this.collection = collection;
}

collectionReady() {
let promise = this.collectionReadyPromise;
if (!promise) {
// eslint-disable-next-line no-unused-vars
promise = new Promise((resolve, reject) => resolve(this.collection));
this.collectionReadyPromise = promise;
}
return promise;
}

read(token) {
return this.collectionReady().then(collection => promiseFindOne(collection, { token }));
}

create(token, status = 'created') {
return this.update(token, { status }, true);
}

update(token, updates, upsert = false) {
if (!updates.updatedAt) {
updates.updatedAt = new Date();
}
debug('update', { token, updates });
return this.collectionReady()
.then(collection => promiseUpdateOrInsert(collection, token, updates, upsert))
.then(rawResponse => {
if (rawResponse.result) {
rawResponse = rawResponse.result;
}
const data = Object.assign({ token }, updates);

if (rawResponse && rawResponse.upserted) {
this.emit('create', data);
debug('emit.create', { token, updates });
} else {
this.emit('update', data);
debug('emit.update', { token, updates });
}

return data;
});
}

delete(token) {
return this.collectionReady()
.then(collection => promiseDelete(collection, { token }))
.then(() => this.emit('destroy', token));
}

exist(token, did) {
return this.collectionReady().then(collection => promiseFindOne(collection, { token, did }));
}

clear() {
return this.collectionReady().then(collection => collection.drop());
}

close() {
if (this.db) {
this.db.close();
}
}
};
70 changes: 70 additions & 0 deletions did/did-auth-storage-tingo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"name": "@arcblock/did-auth-storage-tingo",
"description": "Storage engine that uses tingodb for did-auth",
"version": "1.2.7",
"author": "wangshijun <[email protected]> (https://ocap.arcblock.io)",
"bugs": {
"url": "https://github.com/ArcBlock/forge-js/issues",
"email": "[email protected]"
},
"publishConfig": {
"access": "public"
},
"contributors": [
"wangshijun <[email protected]> (https://ocap.arcblock.io)",
"NateRobinson <[email protected]> (https://ocap.arcblock.io)"
],
"devDependencies": {
"j2d": "^1.0.3-dev",
"jest": "^23.5.0",
"remark-cli": "^5.0.0",
"remark-preset-github": "^0.0.9"
},
"remarkConfig": {
"plugins": [
"preset-github",
[
"validate-links",
{
"repository": "ArcBlock/forge-js"
}
]
]
},
"homepage": "https://github.com/ArcBlock/forge-js/tree/master/did/did-auth-storage-tingo",
"keywords": [
"forge",
"blockchain",
"arcblock",
"sdk",
"nodejs"
],
"license": "Apache-2.0",
"main": "./lib/index.js",
"files": [
"lib"
],
"repository": {
"type": "git",
"url": "https://github.com/ArcBlock/forge-js/tree/master/did/did-auth-storage-tingo"
},
"scripts": {
"lint": "eslint lib tests",
"docs": "yarn generate-dts && yarn generate-docs && yarn cleanup-docs && yarn format-docs",
"cleanup-docs": "node ../../tools/cleanup-docs.js docs/README.md $npm_package_name",
"generate-docs": "jsdoc2md lib/index.js > docs/README.md",
"generate-dts": "j2d lib/index.js",
"format-docs": "remark . -o",
"precommit": "CI=1 yarn test",
"prepush": "CI=1 yarn test",
"test": "npm run lint && node tools/jest.js",
"coverage": "npm run lint && yarn test -- --coverage"
},
"gitHead": "87990c8b5e215107fc587c1ced0d6b3e2cd2483e",
"dependencies": {
"@arcblock/did-auth-storage": "^1.2.7",
"debug": "^4.1.1",
"mongodb": "1.4.x",
"tingodb": "^0.6.1"
}
}
5 changes: 5 additions & 0 deletions did/did-auth-storage-tingo/tests/index.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
describe('#Storage', () => {
test('should have test', () => {
expect(true).toBeTruthy();
});
});
25 changes: 25 additions & 0 deletions did/did-auth-storage-tingo/tools/jest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/* eslint no-console: "off" */
// Do this as the first thing so that any code reading it knows the right env.
process.env.BABEL_ENV = 'test';
process.env.NODE_ENV = 'test';
process.env.PUBLIC_URL = '';
process.env.DEBUG = '@arcblock/*,-@arcblock/forge-proto';

// Makes the script crash on unhandled rejections instead of silently
// ignoring them. In the future, promise rejections that are not handled will
// terminate the Node.js process with a non-zero exit code.
process.on('unhandledRejection', err => {
console.trace(err);
process.exit(1);
});

const jest = require('jest');
let argv = process.argv.slice(2);
argv.push('--forceExit');

// Watch unless on CI or in coverage mode
if (!process.env.CI && argv.indexOf('--coverage') < 0) {
argv.push('--watch');
}

jest.run(argv);
2 changes: 1 addition & 1 deletion version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.3.12
1.3.13
Loading