All files Encoder.ts

0% Statements 0/22
0% Branches 0/6
0% Functions 0/5
0% Lines 0/22

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 63 64 65 66 67 68 69 70                                                                                                                                           
import { Base64 } from 'js-base64'
 
export interface ServiceAccountKey {
  type: string
  project_id: string
  client_id: string
}
 
export interface WebAppsApiKey {
  apiKey: string
  projectId: string
  authDomain: string
}
 
export default class Encoder {
  public static encode(json: Object | JSON): string {
    return Base64.encode(JSON.stringify(json))
  }
 
  public static decode(
    str: string,
  ): { success: boolean; error: string | null } | WebAppsApiKey {
    try {
      const decodingData = Base64.decode(str)
      const json = JSON.parse(decodingData)
      return json
    } catch (e) {
      console.error('Decoding error', e)
      return { success: false, error: e.code }
    }
  }
 
  public static toWebAppsApiKeyFromBase64(str: string): WebAppsApiKey {
    const encodedData = this.decode(str)
    if (
      'apiKey' in encodedData &&
      'projectId' in encodedData &&
      'authDomain' in encodedData
    ) {
      return encodedData
    }
    console.warn('Failed decoding Web apps api key')
    return {
      apiKey: 'error or empty',
      projectId: 'error or empty',
      authDomain: 'error or empty',
      ...encodedData,
    }
  }
 
  public static toAccountKeyFromBase64(str: string): ServiceAccountKey {
    const encodedData = this.decode(str)
    if (
      'project_id' in encodedData &&
      'type' in encodedData &&
      'client_id' in encodedData
    ) {
      return encodedData
    }
    console.warn('Failed decoding service account key')
    console.info('encodedData', encodedData)
    return {
      project_id: 'error or empty',
      client_id: 'error or empty',
      type: 'error or empty',
      ...encodedData,
    }
  }
}