Skip to content

Commit

Permalink
feat: logout sync for embed
Browse files Browse the repository at this point in the history
feat: logout for embed
  • Loading branch information
jiafuei committed Jul 13, 2022
1 parent edb5d33 commit 00cd5bf
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 27 deletions.
53 changes: 30 additions & 23 deletions src/controllers/TorusController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
Expand Down Expand Up @@ -777,7 +779,7 @@ export default class TorusController extends BaseController<TorusControllerConfi
logout(req: JRPCRequest<[]>, res: JRPCResponse<boolean>, _: JRPCEngineNextCallback, end: JRPCEngineEndCallback): void {
this.handleLogout();
res.result = true;
end();
setTimeout(() => end(), 100); // Make sure all async ops are executed.
}

public handleLogout(): void {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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!");
Expand All @@ -1411,6 +1406,32 @@ export default class TorusController extends BaseController<TorusControllerConfi
return this.preferencesController.getDappList();
}

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

const channelName = getLogoutBcChannelName(this.origin, this.userInfo);
const bc = new BroadcastChannel<LogoutMessage>(channelName);
this.logoutBcAttached = true;

const thisInstance = this.instanceId.slice(0, 8);
const eventListener = (msg: LogoutMessage) => {
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);

Expand Down Expand Up @@ -1700,18 +1721,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
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);

Expand Down
5 changes: 2 additions & 3 deletions src/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,9 +210,8 @@ export const logoutWithBC = async (origin: string, _instanceId: string, userInfo
const bc = new BroadcastChannel<LogoutMessage>(`${channelName}`, { 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));
await bc.postMessage({ instanceId, timestamp });
await bc.close();
};

export function getBrowserKey() {
Expand Down

0 comments on commit 00cd5bf

Please sign in to comment.