Skip to content

Instantly share code, notes, and snippets.

@mannyyang
Last active March 14, 2022 07:42
Show Gist options
  • Select an option

  • Save mannyyang/1ce43c2a08423d2886db29c66a7e34ab to your computer and use it in GitHub Desktop.

Select an option

Save mannyyang/1ce43c2a08423d2886db29c66a7e34ab to your computer and use it in GitHub Desktop.
firebase cloudflare
import { getTokenFromGCPServiceAccount } from '@sagi.io/workers-jwt'
/**
* Getting the access token to use in the header.
*/
// For example's sake, the file contents (modified) from the private key has been
// listed below, but the recommended way would be to use environment variables.
export async function getAccessToken() {
const jwtToken = await getTokenFromGCPServiceAccount({
serviceAccountJSON: {
type: 'service_account',
project_id: 'notion-potions',
private_key_id: '12345678910',
private_key:
'-----BEGIN PRIVATE KEY-----',
client_email:
'[email protected]',
client_id: '10283',
auth_uri: 'https://accounts.google.com/o/oauth2/auth',
token_uri: 'https://oauth2.googleapis.com/token',
auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
client_x509_cert_url:
'https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-777%40your-project.iam.gserviceaccount.com',
},
aud: 'https://oauth2.googleapis.com/token',
payloadAdditions: {
scope: [
// scope required for firestore
'https://www.googleapis.com/auth/datastore',
// The following scopes are required only for realtime database
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/firebase.database',
].join(' '),
},
})
const accessToken = await (
await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion: jwtToken, // the JWT token generated in the previous step
}),
})
).json()
return accessToken
}
/**
* Get all documents in a collection
*/
export async function getCollection() {
const accessToken = await getAccessToken()
const response = await (
await fetch(
'https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/<COLLECTIONNAME>',
{
method: 'GET',
headers: {
Authorization: 'Bearer ' + accessToken.access_token,
},
}
)
).json()
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment