Unverified Commit 8724352b authored by Artyom Kurnikov's avatar Artyom Kurnikov Committed by GitHub

Update Fauna example to create Fauna resources properly (#27757)

- fix `with-fauna` example to populate client secret properly when auto-deploy on changes happens
- improve security by avoiding usage of the `FAUNA_ADMIN_KEY` in the application, now it's used in the setup script only
parent bce06f50
import { GraphQLClient, gql } from 'graphql-request' import { GraphQLClient, gql } from 'graphql-request'
const graphQLClient = new GraphQLClient('https://graphql.fauna.com/graphql', { const CLIENT_SECRET =
process.env.FAUNA_ADMIN_KEY || process.env.FAUNA_CLIENT_SECRET
const FAUNA_GRAPHQL_BASE_URL = 'https://graphql.fauna.com/graphql'
const graphQLClient = new GraphQLClient(FAUNA_GRAPHQL_BASE_URL, {
headers: { headers: {
authorization: `Bearer ${process.env.FAUNA_ADMIN_KEY}`, authorization: `Bearer ${CLIENT_SECRET}`,
}, },
}) })
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
"description": "Guestbook example with Next.js and Fauna.", "description": "Guestbook example with Next.js and Fauna.",
"scripts": { "scripts": {
"dev": "next", "dev": "next",
"build": "next build", "build": "yarn setup && next build",
"start": "next start", "start": "next start",
"setup": "node ./scripts/setup.js" "setup": "node ./scripts/setup.js"
}, },
...@@ -25,7 +25,7 @@ ...@@ -25,7 +25,7 @@
"autoprefixer": "10.3.1", "autoprefixer": "10.3.1",
"postcss": "8.3.6", "postcss": "8.3.6",
"prettier": "2.3.2", "prettier": "2.3.2",
"tailwindcss": "2.2.7", "stream-to-promise": "3.0.0",
"stream-to-promise": "3.0.0" "tailwindcss": "2.2.7"
} }
} }
...@@ -6,8 +6,6 @@ const request = require('request') ...@@ -6,8 +6,6 @@ const request = require('request')
const { Client, query: Q } = require('faunadb') const { Client, query: Q } = require('faunadb')
const streamToPromise = require('stream-to-promise') const streamToPromise = require('stream-to-promise')
const FAUNA_ADMIN_KEY = process.env.FAUNA_ADMIN_KEY
const MakeLatestEntriesIndex = () => const MakeLatestEntriesIndex = () =>
Q.CreateIndex({ Q.CreateIndex({
name: 'latestEntries', name: 'latestEntries',
...@@ -88,15 +86,29 @@ const MakeGuestbookKey = () => ...@@ -88,15 +86,29 @@ const MakeGuestbookKey = () =>
role: Q.Role('GuestbookRole'), role: Q.Role('GuestbookRole'),
}) })
const askAdminKey = () => { const isDatabasePrepared = ({ client }) =>
client.query(Q.Exists(Q.Index('latestEntries')))
const resolveAdminKey = () => {
if (process.env.FAUNA_ADMIN_KEY) {
return Promise.resolve(process.env.FAUNA_ADMIN_KEY)
}
const rl = readline.createInterface({ const rl = readline.createInterface({
input: process.stdin, input: process.stdin,
output: process.stdout, output: process.stdout,
}) })
return new Promise((resolve) => { return new Promise((resolve, reject) => {
rl.question('Please provide the Fauna admin key:\n', (res) => { rl.question('Please provide the Fauna admin key:\n', (res) => {
rl.close() rl.close()
if (!res) {
return reject(
new Error('You need to provide a key, closing. Try again')
)
}
resolve(res) resolve(res)
}) })
}) })
...@@ -117,8 +129,6 @@ const importSchema = (adminKey) => ...@@ -117,8 +129,6 @@ const importSchema = (adminKey) =>
const findImportError = (msg) => { const findImportError = (msg) => {
switch (true) { switch (true) {
case msg.startsWith('Invalid authorization header'):
return 'You need to provide a secret, closing. Try again'
case msg.startsWith('Invalid database secret'): case msg.startsWith('Invalid database secret'):
return 'The secret you have provided is not valid, closing. Try again' return 'The secret you have provided is not valid, closing. Try again'
case !msg.includes('success'): case !msg.includes('success'):
...@@ -129,7 +139,16 @@ const findImportError = (msg) => { ...@@ -129,7 +139,16 @@ const findImportError = (msg) => {
} }
const main = async () => { const main = async () => {
const adminKey = FAUNA_ADMIN_KEY || (await askAdminKey()) const adminKey = await resolveAdminKey()
const client = new Client({ secret: adminKey })
if (await isDatabasePrepared({ client })) {
return console.info(
'Fauna resources have already been prepared. ' +
'If you want to install it once again, please, create a fresh database and re-run the script with the other key'
)
}
const importMsg = await importSchema(adminKey) const importMsg = await importSchema(adminKey)
const importErrorMsg = findImportError(importMsg) const importErrorMsg = findImportError(importMsg)
...@@ -137,9 +156,7 @@ const main = async () => { ...@@ -137,9 +156,7 @@ const main = async () => {
return Promise.reject(new Error(importErrorMsg)) return Promise.reject(new Error(importErrorMsg))
} }
console.log('1. Successfully imported schema') console.log('- Successfully imported schema')
const client = new Client({ secret: adminKey })
for (const Make of [ for (const Make of [
MakeLatestEntriesIndex, MakeLatestEntriesIndex,
...@@ -149,13 +166,18 @@ const main = async () => { ...@@ -149,13 +166,18 @@ const main = async () => {
await client.query(Make()) await client.query(Make())
} }
const { secret } = await client.query(MakeGuestbookKey()) console.log('- Created Fauna resources')
if (process.env.FAUNA_ADMIN_KEY) {
// Assume it's a Vercel environment, no need for .env.local file
return
}
console.log('2. Created Fauna resources') const { secret } = await client.query(MakeGuestbookKey())
await fs.promises.writeFile('.env.local', `FAUNADB_CLIENT_SECRET=${secret}\n`) await fs.promises.writeFile('.env.local', `FAUNA_CLIENT_SECRET=${secret}\n`)
console.log('3. Created .env.local file with secret') console.log('- Created .env.local file with secret')
} }
main().catch((err) => { main().catch((err) => {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment