import * as os from "os" ; import * as path from "path" ; import { Credentials } from "../credentials" ; import { Logger } from "../../utils/logger" ; import { inject , injectable } from "inversify" ; import { Constants , TYPES } from "../../utils/constants" ; import { CredentialsStore } from "../credentialsstore" ; import { FileTokenStorage } from "./file-token-storage" ; @ injectable ( ) export class LinuxFileApi implements CredentialsStore { private fileTokenStorage : FileTokenStorage ; private defaultFilename : string = "secrets.json" ; private defaultFolder : string = ".secrets" ; constructor ( @ inject ( TYPES . FileTokenStorage ) fileTokenStorage ) { const folder = this . defaultFolder ; const filename = this . defaultFilename ; this . fileTokenStorage = fileTokenStorage ; this . fileTokenStorage . setFilename ( path . join ( path . join ( os . homedir ( ) , folder , filename ) ) ) ; } public async getCredentials ( ) { let credentials ; const entries = await this . loadTeamCityCredentials ( ) ; if ( entries . length > 0 ) { credentials = this . createCredentials ( entries [ 0 ] ) ; } if ( entries . length > 1 ) { Logger . logWarning ( "[LinuxFileApi::getCredentials] there are more then one suitable credentials for the user! " + "The first will be taken." ) ; } return credentials ; } public async setCredentials ( credentials ) { const existingEntries = await this . loadCredentialsExceptTeamCity ( ) ; const newEntry = { username : credentials . user , password : credentials . password , url : credentials . serverURL , service : Constants . SERVICE_PREFIX } ; await this . fileTokenStorage . addEntries ( [ newEntry ] , existingEntries ) ; } public async removeCredentials ( ) { const existingEntries = await this . loadCredentialsExceptTeamCity ( ) ; await this . fileTokenStorage . keepEntries ( existingEntries ) ; } private createCredentials ( credentials ) { return new Credentials ( credentials . url , credentials . username , credentials . password , undefined , undefined ) ; } private async loadTeamCityCredentials ( ) { return this . loadCredentials ( true ) ; } private async loadCredentialsExceptTeamCity ( ) { return this . loadCredentials ( false ) ; } private async loadCredentials ( isTeamCityEntries ) { const allEntries = await this . fileTokenStorage . loadEntries ( ) ; if ( ! allEntries || allEntries . length === 0 ) { return [ ] ; } const userEntries = [ ] ; allEntries . forEach ( ( entry ) => { if ( isTeamCityEntries && entry . service === Constants . SERVICE_PREFIX ) { userEntries . push ( entry ) ; } else if ( ! isTeamCityEntries && entry . service !== Constants . SERVICE_PREFIX ) { userEntries . push ( entry ) ; } } ) ; return userEntries ; } getCredentialsSilently ( ) { throw new Error ( "Method not supported." ) ; } }