Skip to content
Merged
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
16 changes: 4 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,11 @@ DeviceHive module
| [options.accessToken] | <code>string</code> | Access token |
| [options.refreshToken] | <code>string</code> | Refresh token |
| [options.login] | <code>string</code> | Login |
| [options.password] | <code>string</code> | Paaword |
| [options.password] | <code>string</code> | Password |
| options.mainServiceURL | <code>string</code> | Main Service URL |
| [options.authServiceURL] | <code>string</code> | Auth Service URL (required only for http) |
| [options.pluginServiceURL] | <code>string</code> | Alug inServi ceURL (required only for http) |
| [options.pluginServiceURL] | <code>string</code> | Plugin Service URL (required only for http) |
| [options.autoUpdateSession] | <code>boolean</code> | Flag to enable/disable autoupdating session. Default: true |

<a name="DeviceHive+connect"></a>

Expand Down Expand Up @@ -2552,7 +2553,7 @@ Creates Plugin Update Query model
| [options.returnCommands] | <code>boolean</code> | Checks if commands should be returned |
| [options.returnUpdatedCommands] | <code>boolean</code> | Checks if updated commands should be returned |
| [options.returnNotifications] | <code>boolean</code> | Checks if commands should be returned |
| [options.status] | <code>string</code> | Plugin status - active or disabled (ACTIVE | DISABLED | CREATED) |
| [options.status] | <code>string</code> | Plugin status - active or disabled (ACTIVE | INACTIVE | CREATED) |
| [options.name] | <code>string</code> | Plugin name |
| [options.description] | <code>string</code> | Plugin description |
| [options.parameters] | <code>string</code> | Plugin parameters |
Expand Down Expand Up @@ -2621,12 +2622,3 @@ Creates User List Query

### userListQuery.toObject() ⇒ <code>Object</code>
Returns instance as a plain JS object



## License

[DeviceHive] is developed by [DataArt] Apps and distributed under Open Source
[Apache 2.0 license](https://en.wikipedia.org/wiki/Apache_License).

© Copyright 2018 [DataArt] Apps © All Rights Reservedstrong text
7 changes: 6 additions & 1 deletion example/node/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const DeviceHive = require(`../../index`);


const httpDeviceHive = new DeviceHive({
login: `dhadmin`,
password: `dhadmin_#911`,
Expand All @@ -11,7 +12,8 @@ const httpDeviceHive = new DeviceHive({
const wsDeviceHive = new DeviceHive({
login: `dhadmin`,
password: `dhadmin_#911`,
mainServiceURL: 'ws://localhost:8080/dh/websocket'
mainServiceURL: 'ws://localhost:8080/dh/websocket',
autoUpdateSession: true
});

const DeviceListQuery = DeviceHive.models.query.DeviceListQuery;
Expand Down Expand Up @@ -48,7 +50,10 @@ void async function start () {
console.log(await wsDeviceHive.network.list(networkListQuery));
console.log(await wsDeviceHive.token.refresh(refreshToken));
}

} catch (error) {
console.warn(error);
}

process.exit(1);
}();
42 changes: 22 additions & 20 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"license": "Apache-2.0",
"dependencies": {
"isomorphic-fetch": "^2.2.1",
"jwt-decode": "^2.2.0",
"query-string": "^5.1.0",
"string-template": "^1.0.0",
"universal-websocket-client": "^1.0.1"
Expand All @@ -25,13 +26,13 @@
"@babel/core": "^7.0.0-beta.40",
"@babel/preset-env": "^7.0.0-beta.40",
"babel-core": "^6.26.0",
"babel-loader": "^8.0.0-beta.0",
"babel-loader": "^8.0.0-beta.2",
"babelify": "^8.0.0",
"browserify": "^15.2.0",
"chai": "^4.1.2",
"exorcist": "^1.0.1",
"mocha": "^5.0.1",
"tinyify": "^2.4.0",
"ws": "^4.0.0"
"ws": "^4.1.0"
}
}
17 changes: 14 additions & 3 deletions src/ApiStrategy.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ class ApiStrategy extends EventEmitter {
static getType(url) {
let result;

if (url.startsWith('http') || url.startsWith('https')) {
if (url.startsWith(HTTP.TYPE)) {
result = HTTP;
} else if (url.startsWith('ws') || url.startsWith('wss')) {
} else if (url.startsWith(WS.TYPE)) {
result = WS;
} else {
throw new UnsupportedTransportError();
Expand All @@ -40,6 +40,8 @@ class ApiStrategy extends EventEmitter {

const me = this;

me.reconnectionHandler = null;

me.urlsMap = new Map();

me.urlsMap.set(API.MAIN_BASE, mainServiceURL);
Expand Down Expand Up @@ -83,7 +85,16 @@ class ApiStrategy extends EventEmitter {
}

return me.strategy.send(sendData)
.then((response) => API.normalizeResponse(me.strategy.type, key, response));
.then((response) => API.normalizeResponse(me.strategy.type, key, response))
.catch(error => {
if (error === Utils.TOKEN_EXPIRED_MARK && me.reconnectionHandler) {
return me.reconnectionHandler()
.then(() => me.strategy.send(sendData))
.then((response) => API.normalizeResponse(me.strategy.type, key, response));
} else {
throw error;
}
});
}
}

Expand Down
48 changes: 38 additions & 10 deletions src/DeviceHive.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const Utils = require(`./utils/Utils`);
const EventEmitter = require('events');
const APIStrategy = require('./ApiStrategy');
const InfoAPI = require('./controllers/ServerInfoAPI');
Expand Down Expand Up @@ -98,7 +99,7 @@ class DeviceHive extends EventEmitter {
* @param {string} [options.authServiceURL] - Auth Service URL (required only for http)
* @param {string} [options.pluginServiceURL] - Alug inServi ceURL (required only for http)
*/
constructor({ accessToken, refreshToken, login, password, mainServiceURL, authServiceURL, pluginServiceURL }) {
constructor({ mainServiceURL, authServiceURL, pluginServiceURL, accessToken, refreshToken, login, password, autoUpdateSession = true }) {
super();

const me = this;
Expand All @@ -107,6 +108,7 @@ class DeviceHive extends EventEmitter {
me.refreshToken = refreshToken;
me.login = login;
me.password = password;
me.autoUpdateSession = autoUpdateSession;

me.strategy = new APIStrategy({ mainServiceURL, authServiceURL, pluginServiceURL });

Expand All @@ -130,22 +132,48 @@ class DeviceHive extends EventEmitter {
* Connect to the DeviceHive service
* @returns {Promise<DeviceHive>}
*/
async connect() {
async connect({ accessToken, refreshToken, login, password } = {}) {
const me = this;

if (me.accessToken || me.refreshToken || (me.login && me.password)) {
if (!accessToken && !refreshToken && !(login && password)) {
accessToken = accessToken || me.accessToken;
refreshToken = refreshToken || me.refreshToken;
login = login || me.login;
password = password || me.password;
}

if (accessToken || refreshToken || (login && password)) {
try {
if (me.accessToken) {
await me.strategy.authorize(me.accessToken);
} else if (me.refreshToken) {
const accessToken = await me.token.refresh(me.refreshToken);
if (login && password) {
const { accessToken, refreshToken } = await me.token.login(login, password);

await me.strategy.authorize(accessToken);
} else if (me.login && me.password) {
const { accessToken } = await me.token.login(me.login, me.password);

me.accessToken = accessToken;
me.refreshToken = refreshToken;
} else if (refreshToken) {
const { accessToken } = await me.token.refresh(refreshToken);

await me.strategy.authorize(accessToken);

me.accessToken = accessToken;
me.refreshToken = refreshToken;
} else if (accessToken) {
await me.strategy.authorize(accessToken);

me.accessToken = accessToken;
}

if (me.autoUpdateSession === true) {
const userTokens = await me.token.createUserToken(
Utils.createUserTokenFromJWT(me.accessToken));

me.accessToken = userTokens.accessToken;
me.refreshToken = userTokens.refreshToken;
me.strategy.reconnectionHandler = () => me.connect({ refreshToken: me.refreshToken });
}
} catch (error) {
throw new InvalidCredentialsError();
throw new InvalidCredentialsError(error);
}
} else {
throw new NoAuthCredentialsError();
Expand Down
10 changes: 5 additions & 5 deletions src/controllers/transportResolvers/ApiMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,15 +156,15 @@ class ApiMap {
}


apiMap.set(ApiMap.login, { http: { method: 'POST', uri: '/token', base: ApiMap.AUTH_BASE }, ws: { action: 'token', response: [`accessToken`, `refreshToken`] } });
apiMap.set(ApiMap.login, { http: { method: 'POST', uri: '/token', base: ApiMap.AUTH_BASE, noAuth: true }, ws: { action: 'token', response: [`accessToken`, `refreshToken`] } });
apiMap.set(ApiMap.createUserToken, { http: { method: 'POST', uri: '/token/create', base: ApiMap.AUTH_BASE }, ws: { action: 'token/create', bodyKey: 'payload', response: [`accessToken`, `refreshToken`] } });
apiMap.set(ApiMap.createPluginToken, { http: { method: 'POST', uri: '/token/plugin/create', base: ApiMap.AUTH_BASE } });
apiMap.set(ApiMap.refreshToken, { http: { method: 'POST', uri: '/token/refresh', base: ApiMap.AUTH_BASE }, ws: { action: 'token/refresh', response: [`accessToken`] } });
apiMap.set(ApiMap.refreshToken, { http: { method: 'POST', uri: '/token/refresh', base: ApiMap.AUTH_BASE, noAuth: true }, ws: { action: 'token/refresh', response: [`accessToken`] } });
apiMap.set(ApiMap.authenticatePlugin, { http: { method: 'GET', uri: '/token/plugin/authenticate', base: ApiMap.AUTH_BASE } });

apiMap.set(ApiMap.getServerInfo, { http: { method: 'GET', uri: '/info', base: ApiMap.MAIN_BASE }, ws: { action: 'server/info', response: { bodyKey: `info` } } });
apiMap.set(ApiMap.getCacheInfo, { http: { method: 'GET', uri: '/info/cache', base: ApiMap.MAIN_BASE } });
apiMap.set(ApiMap.getClusterInfo, { http: { method: 'GET', uri: '/info/config/cluster', base: ApiMap.MAIN_BASE }, ws: { action: 'cluster/info', response: { bodyKey: `clusterInfo` } } });
apiMap.set(ApiMap.getServerInfo, { http: { method: 'GET', uri: '/info', base: ApiMap.MAIN_BASE, noAuth: true }, ws: { action: 'server/info', response: { bodyKey: `info` } } });
apiMap.set(ApiMap.getCacheInfo, { http: { method: 'GET', uri: '/info/cache', base: ApiMap.MAIN_BASE, noAuth: true } });
apiMap.set(ApiMap.getClusterInfo, { http: { method: 'GET', uri: '/info/config/cluster', base: ApiMap.MAIN_BASE, noAuth: true }, ws: { action: 'cluster/info', response: { bodyKey: `clusterInfo` } } });

apiMap.set(ApiMap.getConfiguration, { http: { method: 'GET', uri: '/configuration/{name}', base: ApiMap.MAIN_BASE }, ws: { action: 'configuration/get', response: { bodyKey: `configuration` } } });
apiMap.set(ApiMap.putConfiguration, { http: { method: 'PUT', uri: '/configuration/{name}', base: ApiMap.MAIN_BASE }, ws: { action: 'configuration/put', response: { bodyKey: `configuration` } } });
Expand Down
5 changes: 4 additions & 1 deletion src/controllers/transportResolvers/HttpApiResolver.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,15 @@ class HttpApiResolver {
* @param {boolean} options.subscription
* @param {boolean} options.unsubscription
*/
constructor({ method, uri, base, subscription, unsubscription }) {
constructor({ method, uri, base, subscription, unsubscription, noAuth }) {
const me = this;

me.method = method;
me.uri = uri;
me.base = base;
me.subscription = subscription;
me.unsubscription = unsubscription;
me.noAuth = noAuth;
}

/**
Expand All @@ -76,13 +77,15 @@ class HttpApiResolver {

if (me.unsubscription === true) {
result = {
noAuth: me.noAuth,
unsubscription: me.unsubscription,
body: {
subscriptionId: parameters.subscriptionId
}
};
} else {
result = {
noAuth: me.noAuth,
method: me.method,
endpoint: HttpApiResolver.buildUrl(me.uri, parameters),
base: me.base,
Expand Down
4 changes: 2 additions & 2 deletions src/error/InvalidCredentialsError.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ class InvalidCredentialsError extends Error {
/**
* Creates new InvalidCredentialsError
*/
constructor() {
constructor(message) {
super();

this.message = `Invalid credentials error during attempt to authenticate.`;
this.message = `Invalid credentials error during attempt to authenticate. Error: ${message}`;
}
}

Expand Down
Loading