Skip to content

Commit

Permalink
[PM-194] Browser Account Switcher UI (#6772)
Browse files Browse the repository at this point in the history
* Handle switch messaging

TODO: handle loading state for account switcher

* Async updates required for state

* Fallback to email for current account avatar

* Await un-awaited promises

* Remove unnecessary Prune

Prune was getting confused in browser and deleting memory in browser on
account switch. This method isn't needed since logout already removes
memory data, which is the condition for pruning

* Fix temp password in browser

* Use direct memory access until data is serializable

Safari uses a different message object extraction than firefox/chrome
and is removing `UInt8Array`s. Until all data passed into StorageService
is guaranteed serializable, we need to use direct access in state
service

* Reload badge and context menu on switch

* Gracefully switch account as they log out.

* Maintain location on account switch

* Remove unused state definitions

* Prefer null for state

undefined can be misinterpreted to indicate a value has not been set.

* Hack: structured clone in memory storage

We are currently getting dead objects on account switch due to updating
the object in the foreground state service. However, the storage service
is owned by the background. This structured clone hack ensures that all
objects stored in memory are owned by the appropriate context

* Null check nullable values

active account can be null, so we should include null safety in the
equality

* Correct background->foreground switch command

* Already providing background memory storage

* Handle connection and clipboard on switch account

* Prefer strict equal

* Ensure structuredClone is available to jsdom

This is a deficiency in jsdom --
jsdom/jsdom#3363 -- structured clone is well
supported.

* Fixup types in faker class

* add avatar and simple navigation to header

* add options buttons

* add app-header to necessary pages

* add back button and adjust avatar sizes

* add helper text when account limit reached

* convert magic number to constant

* add clarifying comment

* adjust homepage header styles

* navigate to previousp page upon avatar click when already on '/account-switcher'

* move account UI to own component

* add i18n

* show correct auth status

* add aria-hidden to icons

* use listbox role

* add screen reader accessibility to account component

* more SR a11y updates to account component

* add hover and focus states to avatar

* refactor hover and focus states for avatar

* add screen reader text for avatar

* add slide-down animation on account switcher close

* remove comment

* setup account component story

* add all stories

* move navigation call to account component

* implement account lock

* add button hover effect

* implement account logout

* implement lockAll accounts functionality

* replace 'any' with custom type

* add account switcher button to /home login page

* use <main> tag (enables scrolling)

* change temp server filler name

* temporarily remove server arg from account story

* don't show avatar on /home if no accounts, and don't show 'lock'/'logout' buttons if no currentAccount

* add translation and a11y to /home avatar

* add correct server url to account component

* add 'server' to AccountOption type

* Enabled account switching client-side feature flag.

* add slide-in transition to /account-switcher page

* change capitalization to reflect figma design

* make screen reader read active account email, address more capitalization

* fix web avatar misalignment

* make avatar color based on user settings and in sync with other clients

* make property private

* change accountOptions to availableAccounts for clarity

* refactor to remove 'else' template ref

* remove empty scss rule

* use tailwind instead of scss

* rename isSelected to isActive

* add 'isButton' to /home page avatar

* move files to services folder

* update import

* Remove duplicate active account button

* Move no account button to current-account component

* Always complete logging out

Fixes PM-4866

* make screenreader read off email, not name

* refactor avatar for button case

* Do not next object updates

StateService's init was calling `updateState` at multiple layers,
once overall and then again for each account updated. Because
we were not maintaining a single state object through the
process, it was ending up in a consistent, but incomplete state.
Fixed by returning the updated state everywhere. This very well
may not be all the bugs associated with this

* Treat null switch account as no active user

* Listen for switchAccountFinish before routing (#6950)

* adjust avatar style when wrapped in a button

* show alt text for favicon setting

* move stories to browser

* Send Finish Message on null

* Dynamically set active user when locking all

This is required because some user lock states are not recoverable after
process reload (those with logout timeout). This waits until reload is
occurring, then sets the next user appropriately

* Move Finished Message to Finally Block

Fix tests

* Drop problematic key migration

Fixes PM-4933. This was an instance of foreground/background collision
when writing state. We have several other fallbacks of clearing
these deprecated keys.

* Prefer location to homebrew router service

* Initialize account disk cache from background

Uses the `isRecoveredSession` bool to re-initialize foreground caches
from a background message. This avoids a lengthy first-read for
foregrounds

* PM-4865 - Browser Acct Switcher - only show lock btn for lockable accounts (#6991)

* Lock of active account first, when locking multiple.

Fixes PM-4996

* Fix linter

* Hide lock now for locked users (#7020)

* Hide lock now for locked users

* Prefer disabling button to removing

* Add tooltip to TDE without unlock method

* Load all auth states on state init (#7027)

This is a temporary fix until the owning services can update state
themselves. It uses the presence of an auto key to surmise unlocked
state on init. This is safe since it's run only once on extension start.

* Ps/pm 5004/add load to account switcher (#7032)

* Add load spinner to account switcher

* Remove ul list icons

* Properly size account switcher in popout

* [PM-5005] Prevent Double Navigation (#7035)

* Delete Overriden Method

* Add Lock Transition

* truncate email and server name

* remove account.stories.ts (will add in separate PR)

* Do not switch user at reload if no user is active

* fix prettier issues

---------

Co-authored-by: Matt Gibson <[email protected]>
Co-authored-by: Todd Martin <[email protected]>
Co-authored-by: Justin Baur <[email protected]>
Co-authored-by: Jared Snider <[email protected]>
Co-authored-by: bnagawiecki <[email protected]>
  • Loading branch information
6 people authored Dec 6, 2023
1 parent 00faefa commit ac899be
Show file tree
Hide file tree
Showing 33 changed files with 740 additions and 167 deletions.
3 changes: 2 additions & 1 deletion apps/browser/config/development.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
},
"flags": {
"showPasswordless": true,
"enableCipherKeyEncryption": false
"enableCipherKeyEncryption": false,
"accountSwitching": true
}
}
3 changes: 2 additions & 1 deletion apps/browser/config/production.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"flags": {
"enableCipherKeyEncryption": false
"enableCipherKeyEncryption": false,
"accountSwitching": true
}
}
39 changes: 39 additions & 0 deletions apps/browser/src/_locales/en/messages.json
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,9 @@
"unlockMethodNeededToChangeTimeoutActionDesc": {
"message": "Set up an unlock method to change your vault timeout action."
},
"unlockMethodNeeded": {
"message": "Set up an unlock method in Settings"
},
"rateExtension": {
"message": "Rate the extension"
},
Expand Down Expand Up @@ -405,6 +408,9 @@
"lockNow": {
"message": "Lock now"
},
"lockAll": {
"message": "Lock all"
},
"immediately": {
"message": "Immediately"
},
Expand Down Expand Up @@ -1131,6 +1137,9 @@
"faviconDesc": {
"message": "Show a recognizable image next to each login."
},
"faviconDescAlt": {
"message": "Show a recognizable image next to each login. Applies to all logged in accounts."
},
"enableBadgeCounter": {
"message": "Show badge counter"
},
Expand Down Expand Up @@ -2796,5 +2805,35 @@
},
"lastPassYubikeyDesc": {
"message": "Insert the YubiKey associated with your LastPass account into your computer's USB port, then touch its button."
},
"switchAccount": {
"message": "Switch account"
},
"switchAccounts": {
"message": "Switch accounts"
},
"switchToAccount": {
"message": "Switch to account"
},
"activeAccount": {
"message": "Active account"
},
"accountLimitReached": {
"message": "Account limit reached. Log out of an account to add another."
},
"active": {
"message": "active"
},
"locked": {
"message": "locked"
},
"unlocked": {
"message": "unlocked"
},
"server": {
"message": "server"
},
"hostedAt": {
"message": "hosted at"
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,70 @@
<div *ngIf="accountOptions$ | async as accountOptions" class="box-content">
<div *ngFor="let accountOption of accountOptions" class="box-content-row box-content-row-flex">
<button type="button" (click)="selectAccount(accountOption.id)" class="row-main">
{{ accountOption.name }}
</button>
<app-header>
<div class="left">
<button type="button" (click)="back()">{{ "close" | i18n }}</button>
</div>
</div>
<div class="center tw-font-bold">{{ "switchAccounts" | i18n }}</div>
</app-header>

<main
*ngIf="loading"
class="tw-absolute tw-z-50 tw-box-border tw-flex tw-cursor-not-allowed tw-items-center tw-justify-center tw-bg-background tw-opacity-60"
>
<i class="bwi bwi-spinner bwi-2x bwi-spin" aria-hidden="true"></i>
</main>
<main>
<div class="tw-p-2">
<div *ngIf="availableAccounts$ | async as availableAccounts">
<ul class="tw-grid tw-list-none tw-gap-2" role="listbox">
<li *ngFor="let availableAccount of availableAccounts" role="option">
<auth-account [account]="availableAccount" (loading)="loading = $event"></auth-account>
</li>
</ul>
<!--
If the user has not reached the account limit, the last 'availableAccount' will have an 'id' of
'SPECIAL_ADD_ACCOUNT_ID'. Since we don't want to count this as one of the actual accounts,
we check to make sure the 'id' of the last 'availableAccount' is not equal to 'SPECIAL_ADD_ACCOUNT_ID'
-->
<p
class="tw-text-sm tw-text-muted"
*ngIf="
availableAccounts.length >= accountLimit &&
availableAccounts[availableAccounts.length - 1].id !== specialAddAccountId
"
>
{{ "accountLimitReached" | i18n }}
</p>
</div>

<div class="tw-mt-8" *ngIf="currentAccount$ | async as currentAccount">
<div class="tw-mb-2 tw-uppercase tw-text-muted">{{ "options" | i18n }}</div>
<div class="tw-grid tw-gap-2">
<button
type="button"
class="tw-flex tw-w-full tw-items-center tw-gap-3 tw-rounded-md tw-bg-background tw-p-3 hover:tw-bg-background-alt disabled:tw-cursor-not-allowed disabled:tw-border-text-muted/60 disabled:!tw-text-muted/60"
(click)="lock()"
[disabled]="currentAccount.status === lockedStatus || !activeUserCanLock"
[title]="!activeUserCanLock ? ('unlockMethodNeeded' | i18n) : ''"
>
<i class="bwi bwi-lock tw-text-2xl" aria-hidden="true"></i>
{{ "lockNow" | i18n }}
</button>
<button
type="button"
class="tw-flex tw-w-full tw-items-center tw-gap-3 tw-rounded-md tw-bg-background tw-p-3 hover:tw-bg-background-alt"
(click)="logOut()"
>
<i class="bwi bwi-sign-out tw-text-2xl" aria-hidden="true"></i>
{{ "logOut" | i18n }}
</button>
<button
type="button"
class="tw-mt-2 tw-flex tw-w-full tw-items-center tw-gap-3 tw-rounded-md tw-bg-background tw-p-3 hover:tw-bg-background-alt"
(click)="lockAll()"
>
<i class="bwi bwi-lock tw-text-2xl" aria-hidden="true"></i>
{{ "lockAll" | i18n }}
</button>
</div>
</div>
</div>
</main>
Original file line number Diff line number Diff line change
@@ -1,25 +1,113 @@
import { Component } from "@angular/core";
import { Location } from "@angular/common";
import { Component, OnDestroy, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { Subject, firstValueFrom, map, switchMap, takeUntil } from "rxjs";

import { BrowserRouterService } from "../../../platform/popup/services/browser-router.service";
import { AccountSwitcherService } from "../services/account-switcher.service";
import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service";
import { VaultTimeoutService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout.service";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { DialogService } from "@bitwarden/components";

import { AccountSwitcherService } from "./services/account-switcher.service";

@Component({
templateUrl: "account-switcher.component.html",
})
export class AccountSwitcherComponent {
export class AccountSwitcherComponent implements OnInit, OnDestroy {
readonly lockedStatus = AuthenticationStatus.Locked;
private destroy$ = new Subject<void>();

loading = false;
activeUserCanLock = false;

constructor(
private accountSwitcherService: AccountSwitcherService,
private accountService: AccountService,
private vaultTimeoutService: VaultTimeoutService,
private messagingService: MessagingService,
private dialogService: DialogService,
private location: Location,
private router: Router,
private routerService: BrowserRouterService,
private vaultTimeoutSettingsService: VaultTimeoutSettingsService,
) {}

get accountOptions$() {
return this.accountSwitcherService.accountOptions$;
get accountLimit() {
return this.accountSwitcherService.ACCOUNT_LIMIT;
}

get specialAddAccountId() {
return this.accountSwitcherService.SPECIAL_ADD_ACCOUNT_ID;
}

get availableAccounts$() {
return this.accountSwitcherService.availableAccounts$;
}

get currentAccount$() {
return this.accountService.activeAccount$;
}

async ngOnInit() {
const availableVaultTimeoutActions = await firstValueFrom(
this.vaultTimeoutSettingsService.availableVaultTimeoutActions$(),
);
this.activeUserCanLock = availableVaultTimeoutActions.includes(VaultTimeoutAction.Lock);
}

back() {
this.location.back();
}

async lock(userId?: string) {
this.loading = true;
await this.vaultTimeoutService.lock(userId ? userId : null);
this.router.navigate(["lock"]);
}

async lockAll() {
this.loading = true;
this.availableAccounts$
.pipe(
map((accounts) =>
accounts
.filter((account) => account.id !== this.specialAddAccountId)
.sort((a, b) => (a.isActive ? -1 : b.isActive ? 1 : 0)) // Log out of the active account first
.map((account) => account.id),
),
switchMap(async (accountIds) => {
if (accountIds.length === 0) {
return;
}

// Must lock active (first) account first, then order doesn't matter
await this.vaultTimeoutService.lock(accountIds.shift());
await Promise.all(accountIds.map((id) => this.vaultTimeoutService.lock(id)));
}),
takeUntil(this.destroy$),
)
.subscribe(() => this.router.navigate(["lock"]));
}

async logOut() {
this.loading = true;
const confirmed = await this.dialogService.openSimpleDialog({
title: { key: "logOut" },
content: { key: "logOutConfirmation" },
type: "info",
});

if (confirmed) {
this.messagingService.send("logout");
}

this.router.navigate(["account-switcher"]);
}

async selectAccount(id: string) {
await this.accountSwitcherService.selectAccount(id);
this.router.navigate([this.routerService.getPreviousUrl() ?? "/home"]);
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<button
*ngIf="account.id !== specialAccountAddId"
type="button"
class="tw-flex tw-w-full tw-items-center tw-gap-3 tw-rounded-md tw-border-none tw-bg-background tw-p-3 hover:tw-bg-background-alt"
(click)="selectAccount(account.id)"
>
<div class="tw-flex-shrink-0">
<bit-avatar
[id]="account.id"
[text]="account.name"
[color]="account.avatarColor"
size="small"
aria-hidden="true"
></bit-avatar>
</div>
<div class="tw-text-left">
<span class="tw-sr-only" *ngIf="status.text === 'active'"> {{ "activeAccount" | i18n }}: </span>
<span class="tw-sr-only" *ngIf="status.text !== 'active'">
{{ "switchToAccount" | i18n }}
</span>
<div class="tw-max-w-64 tw-truncate tw-text-main">
{{ account.email }}
</div>
<div class="tw-max-w-64 tw-truncate tw-text-sm tw-text-muted">
<span class="tw-sr-only">{{ "hostedAt" | i18n }}</span>
{{ account.server }}
</div>
<div class="tw-text-sm tw-italic tw-text-muted" [attr.aria-hidden]="status.text === 'active'">
<span class="tw-sr-only">(</span>
{{ status.text }}
<span class="tw-sr-only">)</span>
</div>
</div>
<div class="tw-ml-auto tw-flex-shrink-0">
<i class="bwi tw-text-2xl tw-text-main" [ngClass]="status.icon" aria-hidden="true"></i>
</div>
</button>

<button
*ngIf="account.id === specialAccountAddId"
type="button"
class="tw-flex tw-w-full tw-items-center tw-gap-3 tw-rounded-md tw-border-none tw-bg-background tw-p-3 hover:tw-bg-background-alt"
(click)="selectAccount(account.id)"
>
<i class="bwi bwi-plus tw-text-2xl tw-text-main" aria-hidden="true"></i>
<div class="tw-text-main">
{{ account.name }}
</div>
</button>
55 changes: 55 additions & 0 deletions apps/browser/src/auth/popup/account-switching/account.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { CommonModule, Location } from "@angular/common";
import { Component, EventEmitter, Input, Output } from "@angular/core";
import { Router } from "@angular/router";

import { JslibModule } from "@bitwarden/angular/jslib.module";
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { AvatarModule } from "@bitwarden/components";

import { AccountSwitcherService, AvailableAccount } from "./services/account-switcher.service";

@Component({
standalone: true,
selector: "auth-account",
templateUrl: "account.component.html",
imports: [CommonModule, JslibModule, AvatarModule],
})
export class AccountComponent {
@Input() account: AvailableAccount;
@Output() loading = new EventEmitter<boolean>();

constructor(
private accountSwitcherService: AccountSwitcherService,
private router: Router,
private location: Location,
private i18nService: I18nService,
) {}

get specialAccountAddId() {
return this.accountSwitcherService.SPECIAL_ADD_ACCOUNT_ID;
}

async selectAccount(id: string) {
this.loading.emit(true);
await this.accountSwitcherService.selectAccount(id);

if (id === this.specialAccountAddId) {
this.router.navigate(["home"]);
} else {
this.location.back();
}
}

get status() {
if (this.account.isActive && this.account.status !== AuthenticationStatus.Locked) {
return { text: this.i18nService.t("active"), icon: "bwi-check-circle" };
}

if (this.account.status === AuthenticationStatus.Unlocked) {
return { text: this.i18nService.t("unlocked"), icon: "bwi-unlock" };
}

return { text: this.i18nService.t("locked"), icon: "bwi-lock" };
}
}
Loading

0 comments on commit ac899be

Please sign in to comment.