userDataSyncAccount.ts 8.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import { IAuthenticationService } from 'vs/workbench/services/authentication/browser/authenticationService';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IAuthenticationTokenService } from 'vs/platform/authentication/common/authentication';
import { IProductService } from 'vs/platform/product/common/productService';
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { localize } from 'vs/nls';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { AuthenticationSession } from 'vs/editor/common/modes';
import { Event, Emitter } from 'vs/base/common/event';
import { getUserDataSyncStore, IUserDataSyncEnablementService } from 'vs/platform/userDataSync/common/userDataSync';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { distinct } from 'vs/base/common/arrays';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';

type UserAccountClassification = {
	id: { classification: 'EndUserPseudonymizedInformation', purpose: 'BusinessInsight' };
};

type UserAccountEvent = {
	id: string;
};

export interface IUserDataSyncAccount {
	providerId: string;
	sessionId: string;
	accountName: string;
}

export class UserDataSyncAccountManager extends Disposable {

	private static LAST_USED_SESSION_STORAGE_KEY = 'userDataSyncAccountPreference';

	_serviceBrand: any;

	readonly userDataSyncAccountProvider: string | undefined;

	private _activeAccount: IUserDataSyncAccount | undefined | null;
	get activeAccount(): IUserDataSyncAccount | undefined | null { return this._activeAccount; }
	private readonly _onDidChangeActiveAccount = this._register(new Emitter<{ previous: IUserDataSyncAccount | undefined | null, current: IUserDataSyncAccount | null }>());
	readonly onDidChangeActiveAccount = this._onDidChangeActiveAccount.event;

	constructor(
		@IAuthenticationService private readonly authenticationService: IAuthenticationService,
		@IAuthenticationTokenService private readonly authenticationTokenService: IAuthenticationTokenService,
		@IQuickInputService private readonly quickInputService: IQuickInputService,
		@IStorageService private readonly storageService: IStorageService,
		@IUserDataSyncEnablementService private readonly userDataSyncEnablementService: IUserDataSyncEnablementService,
		@ITelemetryService private readonly telemetryService: ITelemetryService,
		@IProductService productService: IProductService,
		@IConfigurationService configurationService: IConfigurationService,
	) {
		super();
		this.userDataSyncAccountProvider = getUserDataSyncStore(productService, configurationService)?.authenticationProviderId;
		if (this.userDataSyncAccountProvider) {
60 61 62 63 64
			if (authenticationService.isAuthenticationProviderRegistered(this.userDataSyncAccountProvider)) {
				this.initialize();
			} else {
				this._register(Event.once(Event.filter(this.authenticationService.onDidRegisterAuthenticationProvider, providerId => providerId === this.userDataSyncAccountProvider))(() => this.initialize()));
			}
65 66 67
		}
	}

68 69 70 71 72 73 74 75 76 77 78 79 80 81
	private async initialize(): Promise<void> {
		await this.update();
		this._register(
			Event.any(
				Event.filter(
					Event.any(
						this.authenticationService.onDidRegisterAuthenticationProvider,
						this.authenticationService.onDidUnregisterAuthenticationProvider,
						Event.map(this.authenticationService.onDidChangeSessions, e => e.providerId)
					), providerId => providerId === this.userDataSyncAccountProvider),
				this.authenticationTokenService.onTokenFailed)
				(() => this.update()));
	}

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
	private async update(): Promise<void> {
		if (!this.userDataSyncAccountProvider) {
			return;
		}
		let activeSession: AuthenticationSession | undefined = undefined;
		if (this.lastUsedSessionId) {
			const sessions = await this.authenticationService.getSessions(this.userDataSyncAccountProvider);
			if (sessions?.length) {
				activeSession = sessions.find(session => session.id === this.lastUsedSessionId);
			}
		}

		let activeAccount: IUserDataSyncAccount | null = null;
		if (activeSession) {
			try {
				const token = await activeSession.getAccessToken();
				await this.authenticationTokenService.setToken(token);
				activeAccount = {
					providerId: this.userDataSyncAccountProvider,
					sessionId: activeSession.id,
					accountName: activeSession.accountName
				};
			} catch (e) {
				// Ignore and log error
			}
		}

		if (!this.areSameAccounts(activeAccount, this._activeAccount)) {
			const previous = this._activeAccount;
			this._activeAccount = activeAccount;
			this._onDidChangeActiveAccount.fire({ previous, current: this._activeAccount });
		}
	}

	async login(): Promise<void> {
		if (this.userDataSyncAccountProvider) {
			const session = await this.authenticationService.login(this.userDataSyncAccountProvider, ['https://management.core.windows.net/.default', 'offline_access']);
			await this.switch(session.id);
		}
	}

	async select(): Promise<void> {
		if (!this.activeAccount) {
			throw new Error('Requires Login');
		}
		await this.update();
		if (!this.activeAccount) {
			throw new Error('Requires Login');
		}
		const { providerId, sessionId } = this.activeAccount;
		await new Promise(async (c, e) => {
			const disposables: DisposableStore = new DisposableStore();
			const quickPick = this.quickInputService.createQuickPick<{ label: string, session?: AuthenticationSession, detail?: string }>();
			disposables.add(quickPick);

			quickPick.title = localize('pick account', "{0}: Pick an account", this.authenticationService.getDisplayName(providerId));
			quickPick.ok = false;
			quickPick.placeholder = localize('choose account placeholder', "Pick an account for syncing");
			quickPick.ignoreFocusOut = true;
			disposables.add(quickPick.onDidAccept(async () => {
				const selected = quickPick.selectedItems[0];
				if (selected) {
					if (selected.session) {
						await this.switch(selected.session.id);
					} else {
						await this.login();
					}
					quickPick.hide();
					c();
				}
			}));
			disposables.add(quickPick.onDidHide(() => disposables.dispose()));
			quickPick.show();

			quickPick.busy = true;
			quickPick.items = await this.getSessionQuickPickItems(providerId, sessionId);
			quickPick.busy = false;

		});
	}

	async switch(sessionId: string): Promise<void> {
		if (this.userDataSyncEnablementService.isEnabled() && (this.lastUsedSessionId && this.lastUsedSessionId !== sessionId)) {
			// accounts are switched while sync is enabled.
		}
		this.lastUsedSessionId = sessionId;
		this.telemetryService.publicLog2<UserAccountEvent, UserAccountClassification>('sync.userAccount', { id: sessionId.split('/')[1] });
		await this.update();
	}

	private async getSessionQuickPickItems(providerId: string, sessionId: string): Promise<{ label: string, session?: AuthenticationSession, detail?: string }[]> {
		const quickPickItems: { label: string, session?: AuthenticationSession, detail?: string }[] = [];

		let sessions = await this.authenticationService.getSessions(providerId) || [];
		const lastUsedSession = sessions.filter(session => session.id === sessionId)[0];

		if (lastUsedSession) {
			sessions = sessions.filter(session => session.accountName !== lastUsedSession.accountName);
			quickPickItems.push({
				label: lastUsedSession.accountName,
				session: lastUsedSession,
				detail: localize('previously used', "Last used")
			});
		}

		quickPickItems.push(...distinct(sessions, session => session.accountName).map(session => ({ label: session.accountName, session })));
		quickPickItems.push({ label: localize('choose another', "Use another account") });
		return quickPickItems;
	}

	private get lastUsedSessionId(): string | undefined {
		return this.storageService.get(UserDataSyncAccountManager.LAST_USED_SESSION_STORAGE_KEY, StorageScope.GLOBAL);
	}

	private set lastUsedSessionId(lastUserSessionId: string | undefined) {
		if (lastUserSessionId === undefined) {
			this.storageService.remove(UserDataSyncAccountManager.LAST_USED_SESSION_STORAGE_KEY, StorageScope.GLOBAL);
		} else {
			this.storageService.store(UserDataSyncAccountManager.LAST_USED_SESSION_STORAGE_KEY, lastUserSessionId, StorageScope.GLOBAL);
		}
	}

	private areSameAccounts(a: IUserDataSyncAccount | undefined | null, b: IUserDataSyncAccount | undefined | null): boolean {
		if (a === b) {
			return true;
		}
		if (a && b
			&& a.providerId === b.providerId
			&& a.sessionId === b.sessionId
		) {
			return true;
		}
		return false;
	}

}