All files api.token.js

63.16% Statements 12/19
0% Branches 0/2
40% Functions 2/5
63.16% Lines 12/19

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        5x 5x 5x 5x   5x                   5x                                             5x         4x 4x 4x 4x                       4x  
// @flow
import got from 'got'
import { asserts, joinParams, toBody } from './util'
 
const oauth2_uri = 'https://accounts.google.com/o/oauth2'
const auth_uri = `${oauth2_uri}/auth`
const token_uri = `${oauth2_uri}/token`
const redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
 
export const authURL = (client_id: string): string => {
  asserts(client_id, `[chenv] client_id is required`)
  return auth_uri + joinParams({
    client_id,
    redirect_uri,
    response_type: 'code',
    scope: 'https://www.googleapis.com/auth/chromewebstore'
  })
}
 
export const getRefreshToken = ({ client_id, client_secret, code }: {
  client_id: string,
  client_secret: string,
  code: string
} = {}): Promise<string> => {
  asserts(client_id, `[chenv] client_id is required`)
  asserts(client_secret, `[chenv] client_secret is required`)
  asserts(code, `[chenv] code is required`)
  return got(token_uri, {
    method: 'POST',
    json: true,
    body: {
      client_id,
      client_secret,
      code,
      redirect_uri,
      grant_type: 'authorization_code',
    }
  })
  .then(toBody)
  .then(({ refresh_token }) => refresh_token)
}
 
export const getAccessToken = ({ client_id, client_secret, refresh_token }: {
  client_id: string,
  client_secret: string,
  refresh_token: string
} = {}): Promise<string> => {
  asserts(client_id, `[chenv] client_id is required`)
  asserts(client_secret, `[chenv] client_secret is required`)
  asserts(refresh_token, `[chenv] refresh_token is required`)
  return got(token_uri, {
    method: 'POST',
    json: true,
    body: {
      client_id,
      client_secret,
      refresh_token,
      redirect_uri,
      grant_type: 'refresh_token'
    }
  })
  .then(toBody)
  .then(({ access_token }) => access_token)
}