Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: logout sync for embed
Browse files Browse the repository at this point in the history
jiafuei committed Jul 13, 2022
1 parent edb5d33 commit 65a1e47
Showing 3 changed files with 45 additions and 27 deletions.
54 changes: 32 additions & 22 deletions src/controllers/TorusController.ts
Original file line number Diff line number Diff line change
@@ -219,6 +219,8 @@ export default class TorusController extends BaseController<TorusControllerConfi

private instanceId = "";

private logoutBcAttached!: boolean;

constructor({ _config, _state }: { _config: Partial<TorusControllerConfig>; _state: Partial<TorusControllerState> }) {
super({ config: _config, state: _state });
}
@@ -1241,9 +1243,6 @@ export default class TorusController extends BaseController<TorusControllerConfi
});
if (waitSaving) await saveToOpenLogin;

if (isMain) {
this.attachLogoutBC();
}
this.emit("LOGIN_RESPONSE", null, address);
return result;
} catch (error) {
@@ -1389,11 +1388,7 @@ export default class TorusController extends BaseController<TorusControllerConfi
// This call sync and refresh blockchain state
this.setSelectedAccount(selectedAddress, true);

// Listen to logout events across tabs
if (isMain) {
this.attachLogoutBC();
}

this.attachLogoutBC();
return true;
} catch (e) {
log.error(e, "Error restoring state after successful decrypt!");
@@ -1411,6 +1406,35 @@ export default class TorusController extends BaseController<TorusControllerConfi
return this.preferencesController.getDappList();
}

attachLogoutBC() {
if (this.logoutBcAttached) {
log.info("Logout BC already attached");
return;
}

const channelName = getLogoutBcChannelName(this.origin, this.userInfo);
const bc = new BroadcastChannel<LogoutMessage>(channelName, { type: "server" });
this.logoutBcAttached = true;
const thisInstance = this.instanceId.slice(0, 8);
global.console.log("attaching to logout bc");
global.console.log(`Tab instance: ${thisInstance}`);
global.console.log(`Logout channel: ${channelName}`);
const eventListener = (msg: LogoutMessage) => {
global.console.log(`received logout msg from ${msg.instanceId}`);
if (thisInstance === msg.instanceId) return;
bc.removeEventListener("message", eventListener);
bc.close()
.then(() => {
this.logoutBcAttached = false;
this.emit("logout", true);
if (!isMain) this.notifyEmbedLogout();
return null;
})
.catch((err) => log.error("broadcastchannel close error", err));
};
bc.addEventListener("message", eventListener);
}

private async providerRequestAccounts(req: JRPCRequest<unknown>) {
const accounts = await this.requestAccounts(req);

@@ -1700,18 +1724,4 @@ export default class TorusController extends BaseController<TorusControllerConfi
};
this.embedController.initializeProvider(commProviderHandlers);
}

private attachLogoutBC() {
const channelName = getLogoutBcChannelName(this.origin, this.userInfo);
const bc = new BroadcastChannel<LogoutMessage>(channelName);
const thisInstance = this.instanceId.slice(0, 8);
const eventListener = (msg: LogoutMessage) => {
if (thisInstance === msg.instanceId) return;
bc.removeEventListener("message", eventListener);
bc.close()
.then(() => this.emit("logout", true))
.catch((err) => log.error("broadcastchannel close error", err));
};
bc.addEventListener("message", eventListener);
}
}
7 changes: 6 additions & 1 deletion src/modules/controllers.ts
Original file line number Diff line number Diff line change
@@ -418,6 +418,11 @@ class ControllerModule extends VuexModule {
this.torus.on("logout", (fromBC?: boolean) => {
this.logout(fromBC);
});
this.torus.on("LOGIN_RESPONSE", (message?: string, address?: string) => {
if (message === null && address) {
this.torus.attachLogoutBC();
}
});
this.setInstanceId(instanceId);

if (!isMain) {
@@ -490,8 +495,8 @@ class ControllerModule extends VuexModule {
async logout(fromBC?: boolean): Promise<void> {
if (isMain && this.selectedAddress) {
this.openloginLogout();
if (!fromBC) logoutWithBC(this.torus.origin, this.instanceId, this.torus.userInfo);
}
if (!fromBC) await logoutWithBC(this.torus.origin, this.instanceId, this.torus.userInfo);
const initialState = { ...cloneDeep(DEFAULT_STATE) };
// this.updateTorusState(initialState);

11 changes: 7 additions & 4 deletions src/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -207,12 +207,15 @@ export const logoutWithBC = async (origin: string, _instanceId: string, userInfo
const channelName = getLogoutBcChannelName(origin, userInfo);
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const bc = new BroadcastChannel<LogoutMessage>(`${channelName}`, { server: { timeout: 5 } });
const bc = new BroadcastChannel<LogoutMessage>(`${channelName}`, { type: "server", server: { timeout: 5 } });
const timestamp = new Date().getTime();
const instanceId = _instanceId.slice(0, 8);
bc.postMessage({ instanceId, timestamp })
.then(() => bc.close())
.catch((err) => log.error(err));
global.console.log("Posting to logout BC");
global.console.log(`Tab instance: ${instanceId}`);
global.console.log(`Post to channel: ${channelName}`);

await bc.postMessage({ instanceId, timestamp });
await bc.close();
};

export function getBrowserKey() {

0 comments on commit 65a1e47

Please sign in to comment.