All files / services/core credential-storage-service.ts

100% Statements 8/8
100% Branches 2/2
100% Functions 6/6
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                    6x 6x       6x                 2x                 3x 3x               1x                 1x    
import * as vscode from 'vscode';
import { container } from 'tsyringe';
import { AuthCredential } from './credential';
import { ServiceToken } from '@src/services/tokens';
 
/**
 * Service for managing credentials using the SecretStorage of Visual Studio Code.
 */
export class CredentialStorageService {
    private get _secretStorage(): vscode.SecretStorage {
        const context = container.resolve<vscode.ExtensionContext>(ServiceToken.ExtensionContext);
        return context.secrets;
    }
 
    private _getKey(uri: string): string {
        return `mentor.credentials:${uri}`;
    }
 
    /**
     * Stores a credential for the given URI.
     * @param uri The URI for which to store the credential.
     * @param credential The credential to store.
     */
    async saveCredential(uri: string, credential: AuthCredential): Promise<void> {
        await this._secretStorage.store(this._getKey(uri), JSON.stringify(credential));
    }
 
    /**
     * Retrieves the stored credential for the given URI.
     * @param uri The URI for which to retrieve the credential.
     * @returns The stored credential, or undefined if none is found.
     */
    async getCredential(uri: string): Promise<AuthCredential | undefined> {
        const value = await this._secretStorage.get(this._getKey(uri));
        return value ? JSON.parse(value) as AuthCredential : undefined;
    }
 
    /**
     * Deletes the stored credential for the given URI.
     * @param uri The URI for which to delete the credential.
     */
    async deleteCredential(uri: string): Promise<void> {
        await this._secretStorage.delete(this._getKey(uri));
    }
 
    /**
     * Updates the stored credential for the given URI.
     * @param uri The URI for which to update the credential.
     * @param credential The new credential to store.
     */
    async updateCredential(uri: string, credential: AuthCredential): Promise<void> {
        await this.saveCredential(uri, credential);
    }
}