Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/microsoft-authentication/src/common/cachePlugin.ts
3320 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import { ICachePlugin, TokenCacheContext } from '@azure/msal-node';
7
import { Disposable, EventEmitter, SecretStorage } from 'vscode';
8
9
export class SecretStorageCachePlugin implements ICachePlugin, Disposable {
10
private readonly _onDidChange: EventEmitter<void> = new EventEmitter<void>();
11
readonly onDidChange = this._onDidChange.event;
12
13
private _disposable: Disposable;
14
15
private _value: string | undefined;
16
17
constructor(
18
private readonly _secretStorage: SecretStorage,
19
private readonly _key: string
20
) {
21
this._disposable = Disposable.from(
22
this._onDidChange,
23
this._registerChangeHandler()
24
);
25
}
26
27
private _registerChangeHandler() {
28
return this._secretStorage.onDidChange(e => {
29
if (e.key === this._key) {
30
this._onDidChange.fire();
31
}
32
});
33
}
34
35
async beforeCacheAccess(tokenCacheContext: TokenCacheContext): Promise<void> {
36
const data = await this._secretStorage.get(this._key);
37
this._value = data;
38
if (data) {
39
tokenCacheContext.tokenCache.deserialize(data);
40
}
41
}
42
43
async afterCacheAccess(tokenCacheContext: TokenCacheContext): Promise<void> {
44
if (tokenCacheContext.cacheHasChanged) {
45
const value = tokenCacheContext.tokenCache.serialize();
46
if (value !== this._value) {
47
await this._secretStorage.store(this._key, value);
48
}
49
}
50
}
51
52
dispose() {
53
this._disposable.dispose();
54
}
55
}
56
57