src/modules/identity-crossapp.js
/**
* Identity SDK cross app helpers
*/
class IdentityCrossApp {
/**
* Set a list of available cookie names
* @param {Class} nativeController
*/
constructor(nativeController) {
Object.assign(this, {
_callbacks: {},
_nativeController: nativeController,
});
this._commandList = {
get: 'GetStoredCredentials',
remove: 'RemoveStoredCredentials',
set: 'StoreCredentials',
};
// Bind this to callback
this._onBridgeMessage = this._onBridgeMessage.bind(this);
}
/**
* Subscribe to native bridge messages
* @param {string} subject
* @param {Object} message
*/
_onBridgeMessage(subject, message) {
// Receive message from native bridge
switch (subject) {
case this._commandList.get:
if (this._callbacks.get && this._callbacks.get.length > 0) {
this._callbacks.get.forEach((callback) => callback(message));
}
break;
case this._commandList.remove:
if (this._callbacks.remove && this._callbacks.remove.length > 0) {
this._callbacks.remove.forEach((callback) => callback(message));
}
break;
case this._commandList.set:
if (this._callbacks.set && this._callbacks.set.length > 0) {
this._callbacks.set.forEach((callback) => callback(message));
}
break;
}
}
/**
* Initialize the cross app bridge
* @return {Promise}
*/
init() {
return new Promise((resolve, reject) => {
this._nativeController.init().then(() => {
// Subscribe to the bridge
this._nativeController.subscribe(this._onBridgeMessage);
return resolve();
}).catch(() => reject());
});
}
/**
* Send command through the cross app bridge
* @param {string} name - command name
* @param {Object} payload - keychain options
* @return {Error}
*/
command(name, payload) {
const command = this._commandList[name];
if (!command) return Error('Command name does not exist.');
this._nativeController.sendCommand(command, payload);
}
/**
* Set callbacks
* @param {string} name
* @param {function} callback
* @return {Error}
*/
on(name, callback) {
const command = this._commandList[name];
if (!command) return Error('Command name does not exist.');
if (!this._callbacks[name]) this._callbacks[name] = [];
this._callbacks[name].push(callback);
}
/**
* Remove all cross app user data from the iOS keychain
* @param {string} token - IDM session token
*/
remove(token) {
this.command('remove', {});
}
}
export default IdentityCrossApp;