Created
July 3, 2019 03:38
-
-
Save kaave/6a34d41972ce6527393a05dd24ea4b57 to your computer and use it in GitHub Desktop.
Cloud Functionsから認証付きのCloud Firestoreを突破
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
import * as admin from 'firebase-admin'; | |
import * as functions from 'firebase-functions'; | |
const validReferrers = [ | |
'http://localhost:9012', | |
]; | |
admin.initializeApp(functions.config().firebase); | |
const db = admin.firestore(); | |
function checkIsValidRequest(referrer?: string) { | |
if (!referrer) return false; | |
return validReferrers.some(url => referrer.includes(url)); | |
} | |
async function getAllEntries() { | |
const snapshot = await db.collection('entries').get().catch(err => { | |
console.log('Error getting documents', err); | |
}); | |
const result: string[] = []; | |
if (!snapshot) return result; | |
snapshot.forEach((doc) => { | |
const { firstname, lastname } = doc.data(); | |
result.push(`${doc.id} => ${firstname} ${lastname}`); | |
}) | |
return result; | |
} | |
export const helloWorld = functions.https.onRequest(async (request, response) => { | |
const referrer = request.header('Referrer'); | |
const isValidRequest = checkIsValidRequest(referrer); | |
if (!isValidRequest) { | |
response.send(`request is invalid. referrer[${referrer}]`); | |
return; | |
} | |
/* | |
* add | |
*/ | |
const ref = await db.collection('entries').add({ firstname: 'add!', lastname: Date.now().toString() }) | |
const entries = await getAllEntries(); | |
response.send(`add ref.id:${ref.id}\nentries.\n${entries.join('\n')}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment