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

100% Statements 10/10
100% Branches 4/4
100% Functions 8/8
100% Lines 10/10

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 55 56 57 58 59 60 61 62                8x     6x       6x                 2x                 3x 3x               1x                 1x             2x 2x    
import * as vscode from 'vscode';
import { AuthCredential, MicrosoftAuthCredential } from './credential';
import { loginMicrosoftAuthProvider } from '@src/commands/login-microsoft-auth-provider';
 
/**
 * Service for managing credentials using the SecretStorage of Visual Studio Code.
 */
export class CredentialStorageService {
    constructor(private readonly _context: vscode.ExtensionContext) { }
 
    private get _secretStorage(): vscode.SecretStorage {
        return this._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);
    }
 
    /**
     * Acquires a Microsoft access token via the Mentor Microsoft auth provider command.
     */
    async fetchMicrosoftCredential(scopes: string[]): Promise<MicrosoftAuthCredential | null> {
        const credential = await vscode.commands.executeCommand<MicrosoftAuthCredential | null>(loginMicrosoftAuthProvider.id, scopes);
        return credential ?? null;
    }
}