Path: blob/main/extensions/microsoft-authentication/src/common/cachePlugin.ts
3320 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import { ICachePlugin, TokenCacheContext } from '@azure/msal-node';6import { Disposable, EventEmitter, SecretStorage } from 'vscode';78export class SecretStorageCachePlugin implements ICachePlugin, Disposable {9private readonly _onDidChange: EventEmitter<void> = new EventEmitter<void>();10readonly onDidChange = this._onDidChange.event;1112private _disposable: Disposable;1314private _value: string | undefined;1516constructor(17private readonly _secretStorage: SecretStorage,18private readonly _key: string19) {20this._disposable = Disposable.from(21this._onDidChange,22this._registerChangeHandler()23);24}2526private _registerChangeHandler() {27return this._secretStorage.onDidChange(e => {28if (e.key === this._key) {29this._onDidChange.fire();30}31});32}3334async beforeCacheAccess(tokenCacheContext: TokenCacheContext): Promise<void> {35const data = await this._secretStorage.get(this._key);36this._value = data;37if (data) {38tokenCacheContext.tokenCache.deserialize(data);39}40}4142async afterCacheAccess(tokenCacheContext: TokenCacheContext): Promise<void> {43if (tokenCacheContext.cacheHasChanged) {44const value = tokenCacheContext.tokenCache.serialize();45if (value !== this._value) {46await this._secretStorage.store(this._key, value);47}48}49}5051dispose() {52this._disposable.dispose();53}54}555657