UNPKG

@block-auth.io/blockauth-sdk

Version:

Block-Auth Auth SDK is a SaaS service blockchain based authentication service. It provides a simple and secure way to authenticate users in your application.

453 lines (452 loc) 13 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WsClient = void 0; const socket_io_client_1 = __importDefault(require("socket.io-client")); /** * This class allow you to use WebSocket API * for Block-Auth service * * @class WsClient * @param reconnect - Allow to automatically reconnect * to the WebSocket API * @returns WsClient * @example * * import { WsClient } from '@blockauth/sdk' * const client = new WsClient() * await client.connect() * */ class WsClient { constructor(url = '', reconnect = false) { this._uiConfig = {}; this._accessToken = ''; this._refreshToken = ''; this._user = {}; this._users = []; this._roles = []; this._logs = []; this._kycIssuerByAddress = {}; this._wsUrl = url || 'wss://wss.block-auth.io/'; this._wsConfig = { transports: ['websocket'], reconnection: reconnect, reconnectionDelay: 100, reconnectionDelayMax: 3000, reconnectionAttempts: 30, }; this._uiConfig = {}; } /** * Check if the WebSocket API is connected * to Block-Auth service * @returns boolean */ isConnected() { if (!this._ws) return false; return this._ws.connected || false; } /** * Allow you to connect to the WebSocket API * for Block-Auth service * @param waitMs - time to wait for connection ready * @returns Promise<void> */ async connect(url = '', waitMs = 1000) { const _url = url || this._wsUrl; this._ws = (0, socket_io_client_1.default)(_url, this._wsConfig); // awaits for connection ready await new Promise((resolve) => { console.log(`[block-auth] waiting for connection...`); setTimeout(resolve, waitMs); }); // setup events this.on('connect', this.onConnect); this.on('reconnect_error', this.onReconnectError); this.on('reconnect_attempt', this.onReconnectAttempt); this.on('disconnect', this.onDisconnect); // sdk this.on('sdk:signin', this.onSdkSignin); this.on('sdk:refresh', this.onSdkRefresh); this.on('sdk:app', this.onSdkApp); this.on('sdk:user', this.onSdkUser); this.on('sdk:users', this.onSdkUsers); this.on('sdk:roles', this.onSdkRoles); this.on('sdk:logs', this.onSdkLogs); } /** * Allow you to subscribe to an event, and * verify if the event is already subscribed * for Block-Auth service * @param event - Event name * @param callback - Callback function * @returns void */ on(event, callback) { if (this != undefined && this._ws.hasListeners(event)) return console.log(`[block-auth] event ${event} already subscribed`); this._ws.on(event, callback); } /** * Allow you to unsubscribe to an event, and * verify if the event is already unsubscribed * for Block-Auth service * @param event - Event name * @param callback - Callback function * @returns void */ off(event, callback) { if (this != undefined && !this._ws.hasListeners(event)) return console.log(`[block-auth] event ${event} not subscribed`); this._ws.off(event, callback); } /** * Allow you to emit an event, and * verify if the event is already emitted * for Block-Auth service * @param event - Event name * @param data - Data to send * @returns void */ emit(event, data) { if (this != undefined && !this._ws.hasListeners(event)) return console.log(`[block-auth] event ${event} does not exist`); this._ws.emit(event, data); } /** * Allow you to close the connection * to the WebSocket API for Block-Auth service * @returns void */ close() { if (this != undefined && !this.isConnected()) return console.log(`[block-auth] WS not connected`); this._ws.close(); // reset tokens this._accessToken = ''; this._refreshToken = ''; } // EVENTs /** * Event fired when the WebSocket API * is connected to Block-Auth service * @returns void */ onConnect() { console.log('[block-auth] WS connecting...'); try { if (!this._ws) throw new Error('Failed to load WS'); const isConnected = this._ws.connected || false; if (!isConnected) throw new Error('Failed to connect'); console.log('[block-auth] WS connected!'); } catch (err) { console.log('[block-auth] WS connecting denied'); console.log(' [DEBUG]: ', err); } } /** * Event fired when the WebSocket API * got an error on reconnection to Block-Auth service */ onReconnectError(err) { console.log('[block-auth] WS reconnect_error: ', err); } /** * Event fired when the WebSocket API * try to reconnect to Block-Auth service * @param attempt - Number of attempt */ onReconnectAttempt(attempt) { if (attempt > 3) { this._ws.close(); console.log('[block-auth] WS reconnect_attempt: ', attempt, ' - closing socket'); } else { console.log('[block-auth] WS reconnect_attempt: ', attempt); } } /** * Event fired when the WebSocket API * need to signin to Block-Auth service * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { * success: true, * message: { * accessToken * refreshToken * } * } * ``` * */ onSdkSignin(data) { const { success, message } = data; if (!success && message === 'App not active') { console.log('[block-auth][WARNING] App not active'); return message; } if (!success) throw new Error(message); const { accessToken, refreshToken } = message; this._accessToken = accessToken; this._refreshToken = refreshToken; } /** * Event fired when the WebSocket API * need to refresh the signin to Block-Auth service * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { * "success": true, * "message": { * accessToken * refreshToken * } * } * ``` * */ onSdkRefresh(data) { const { success, message } = data; if (!success) throw new Error(message); const { accessToken, refreshToken } = message; // sometimes clients exec arbitary code to refresh tokens // in same second with a signin, same tokens are returned // and check is needed to avoid override tokens if (this._accessToken == accessToken || this._refreshToken == refreshToken) throw new Error('Refresh failed'); this._accessToken = accessToken; this._refreshToken = refreshToken; } /** * Event fired when the WebSocket API * need to check if an address is signed for * current APP at this current time * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { "success": false, "message": "User not signed in APP yet" } * ``` * */ onSdkSign(data) { const { success, message } = data; // if "Bad sign" == tokens are expired if (!success && message === 'Bad sign') { console.log('[block-auth][sdk:sign] expired, refreshing...'); this.emit('sdk:refresh', { refreshToken: this._refreshToken, }); } console.log('[block-auth][sdk:sign] isSigned=', data.success); // nothing to do with this event // response at onSdkRefresh will // update tokens for local instance } /** * Event fired when the WebSocket API * need to get APP config from Block-Auth service * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { "success": true, "message": { "domain": "example.com", "config": { ... } } } * ``` * */ onSdkApp(data) { const { success, message } = data; if (!success) throw new Error(message); const { domain, signinCallbackUrl, config } = message; this._uiConfig = { domain, signinCallbackUrl, ...config }; } /** * Event fired when the WebSocket API * need to get APP user from Block-Auth service * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { "success": true, "message": { "items": [ { ...profileProperties "did": "did:564", "address": "0x564", } ], } } * ``` * */ onSdkUser(data) { const { success, message } = data; const { items } = message; const user = success ? items[0] : message; this._user = { ...user }; } /** * Event fired when the WebSocket API * need to get APP users from Block-Auth service * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { "success": true, "message": { "pages": 1, "items": [ ... ], "total": 1, } } * ``` * */ onSdkUsers(data) { const { success, message } = data; if (!success) throw new Error(message); const { items } = message; this._users = [...items]; } /** * Event fired when the WebSocket API * need to get APP roles from Block-Auth service * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { "success": true, "message": { "pages": 1, "items": [ ... ], "total": 1, } } * ``` * */ onSdkRoles(data) { const { success, message } = data; if (!success) throw new Error(message); const { items } = message; this._roles = [...items]; } /** * Event fired when the WebSocket API * need to get APP logs from Block-Auth service * @param data - Data received from Block-Auth service * @returns void * @example * ```typescript * { "success": true, "message": { "pages": 1, "items": [ ... ], "total": 1, } } * ``` * */ onSdkLogs(data) { const { success, message } = data; if (!success) throw new Error(message); const { items } = message; this._logs = [...items]; } onSdkKycIssuer(data) { const { success, message } = data; if (!success) throw new Error(message); const { items } = message; const issuer = items[0] || {}; this._kycIssuerByAddress = { ...issuer }; } /** * Event fired when the WebSocket API * is disconnected from Block-Auth service */ onDisconnect(reason) { console.log('[block-auth] WS disconnect by: ', reason); } // GETTERs & SETTERs /** * Get SocketIO instance */ get ws() { return this._ws; } /** * Get WebSocket access token */ get accessToken() { return this._accessToken; } /** * Get WebSocket refresh token */ get refreshToken() { return this._refreshToken; } /** * Get WebSocket APP config */ get uiConfig() { return this._uiConfig; } /** * Get WebSocket APP user */ get user() { return this._user; } /** * Get WebSocket APP users */ get users() { return this._users; } /** * Get WebSocket APP roles */ get roles() { return this._roles; } /** * Get WebSocket APP logs */ get logs() { return this._logs; } /** * Get WebSocket APP issuer for an address * if module KYC is enabled */ get kycIssuerByAddress() { return this._kycIssuerByAddress; } } exports.WsClient = WsClient;