Created
May 18, 2020 16:09
-
-
Save rhyskentish/979f86a35c5a7a8ad608fd06c1b14c4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { KeyManagementServiceClient } = require('@google-cloud/kms'); | |
const projectId = <YourProjectID>; | |
const locationId = <YourPreferedStorageLocationID>; //Based on the google cloud regions e.g. us-central1 | |
const keyRingId = <KeyRingID>; | |
const keyId = <YourKeyId>; | |
const kmsClient = new KeyManagementServiceClient(); | |
const locationName = kmsClient.locationPath(projectId, locationId); | |
admin.initializeApp({ | |
credential: admin.credential.applicationDefault() | |
}); | |
const db = admin.firestore(); | |
const collection = <YourCollectId> | |
async function getToken() { | |
const docRef = db.collection(collection).doc(<YourDocId>); | |
const value = docRef.get().then(async doc => { | |
const data = doc.data(); | |
if (!doc.exists || !data) { | |
return | |
} | |
const [resultAccess] = await kmsClient.decrypt({ | |
name: keyName, | |
ciphertext: Buffer.from(data.api_tokens.access_token) | |
}); | |
const plaintextAccess = resultAccess.plaintext.toString('utf8'); | |
const [resultRefresh] = await kmsClient.decrypt({ | |
name: keyName, | |
ciphertext: Buffer.from(data.api_tokens.refresh_token) | |
}); | |
const plainTextRefresh = resultRefresh.plaintext.toString('utf8'); | |
return { | |
access_token: plaintextAccess, | |
expiry_date: data.api_tokens.expiry_date, | |
refresh_token: plainTextRefresh, | |
scope: data.api_tokens.scope, | |
token_type: data.api_tokens.token_type | |
}; | |
}) | |
.catch(err => { | |
console.log('Error getting document', err); | |
return | |
}); | |
return value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment