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'
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: {
authorization: `Bearer ${process.env.FAUNA_ADMIN_KEY}`,
authorization: `Bearer ${CLIENT_SECRET}`,
},
})
......
......@@ -5,7 +5,7 @@
"description": "Guestbook example with Next.js and Fauna.",
"scripts": {
"dev": "next",
"build": "next build",
"build": "yarn setup && next build",
"start": "next start",
"setup": "node ./scripts/setup.js"
},
......@@ -25,7 +25,7 @@
"autoprefixer": "10.3.1",
"postcss": "8.3.6",
"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')
const { Client, query: Q } = require('faunadb')
const streamToPromise = require('stream-to-promise')
const FAUNA_ADMIN_KEY = process.env.FAUNA_ADMIN_KEY
const MakeLatestEntriesIndex = () =>
Q.CreateIndex({
name: 'latestEntries',
......@@ -88,15 +86,29 @@ const MakeGuestbookKey = () =>
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({
input: process.stdin,
output: process.stdout,
})
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
rl.question('Please provide the Fauna admin key:\n', (res) => {
rl.close()
if (!res) {
return reject(
new Error('You need to provide a key, closing. Try again')
)
}
resolve(res)
})
})
......@@ -117,8 +129,6 @@ const importSchema = (adminKey) =>
const findImportError = (msg) => {
switch (true) {
case msg.startsWith('Invalid authorization header'):
return 'You need to provide a secret, closing. Try again'
case msg.startsWith('Invalid database secret'):
return 'The secret you have provided is not valid, closing. Try again'
case !msg.includes('success'):
......@@ -129,7 +139,16 @@ const findImportError = (msg) => {
}
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 importErrorMsg = findImportError(importMsg)
......@@ -137,9 +156,7 @@ const main = async () => {
return Promise.reject(new Error(importErrorMsg))
}
console.log('1. Successfully imported schema')
const client = new Client({ secret: adminKey })
console.log('- Successfully imported schema')
for (const Make of [
MakeLatestEntriesIndex,
......@@ -149,13 +166,18 @@ const main = async () => {
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) => {
......
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