Created
May 18, 2020 16:05
-
-
Save rhyskentish/d20af78b35b45239033f3ae044dd2696 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 encryptAndStoreToken(token: any) { | |
const keyName = kmsClient.cryptoKeyPath(projectId, locationId, keyRingId, keyId); | |
const [encryptedAccessTokenResponse] = await kmsClient.encrypt({ | |
name: keyName, | |
plaintext: Buffer.from(token.access_token) | |
}); | |
const [encryptedRefreshTokenResponse] = await kmsClient.encrypt({ | |
name: keyName, | |
plaintext: Buffer.from(token.refresh_token) | |
}); | |
const encryptedTokens = { | |
access_token: encryptedAccessTokenResponse.ciphertext, | |
expiry_date: token.expiry_date, | |
refresh_token: encryptedRefreshTokenResponse.ciphertext, | |
scope: token.scope, | |
token_type: token.token_type | |
}; | |
const data = { | |
api_tokens: encryptedTokens | |
}; | |
const docRef = db.collection(collection).doc(<YourDocId>); | |
docRef.set(data, {merge: true}) | |
.then(() => { | |
return | |
}) | |
.catch(err => { | |
console.log('Error setting document', err); | |
return | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment