Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an example for Fauna using cookie based auth (round 2) #9986

Merged
merged 18 commits into from Jan 15, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions examples/with-cookie-auth-fauna/.env
@@ -0,0 +1,6 @@
FAUNA_SERVER_KEY="<ENTER YOU FAUNA SERVER KEY>"

// This key should have minimum permissions since it will be deployed
// to all frontends. It should only have read permission on the
// users_by_email index, for the purposes of logging in user.
FAUNA_CLIENT_KEY = "<ENTER YOU FAUNA CLIENT KEY>";
63 changes: 63 additions & 0 deletions examples/with-cookie-auth-fauna/README.md
@@ -0,0 +1,63 @@
# With Cookie Auth and Fauna

## How to use

### Using `create-next-app`

Download [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) to bootstrap the example:

```
npm i -g create-next-app
create-next-app --example with-cookie-auth-fauna with-cookie-auth-fauna-app
```

### Download manually

Download the example [or clone the repo](https://github.com/zeit/next.js):

```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-cookie-auth-fauna
cd with-cookie-auth-fauna
```

### Run locally

First, you'll need to create an account on [Fauna](https://fauna.com/), then you'll be able to create a database and add the following:

- `User` Collection
- `users_by_email` index
- server and client key

For more information on how to do this, please refer to the [User Authentication Tutorial in Fauna](https://app.fauna.com/tutorials/authentication).

Then add your server and client key to the `.env` file at the project root.

Now, install it and run:

```bash
npm install
npm run dev
# or
yarn
yarn dev
```

### Deploy

Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download)):

```bash
now
```

## The idea behind the example

In this example, we authenticate users and store a token in a secure (non-JS) cookie. The example only shows how the user session works, keeping a user logged in between pages.

This example uses [Fauna](https://fauna.com/) as the auth service and DB.

The repo includes a minimal auth backend built with the new [API Routes support](https://github.com/zeit/next.js/pull/7296) (`pages/api`), [Micro](https://www.npmjs.com/package/micro), [Fauna for Auth](https://app.fauna.com/tutorials/authentication) and [dotenv](https://github.com/zeit/next.js/tree/canary/examples/with-dotenv) for environment variables. The backend allows the user to create an account (a User document), login, and see their user id (User ref id).

Session is synchronized across tabs. If you logout your session gets removed on all the windows as well. We use the HOC `withAuthSync` for this.

The helper function `auth` helps to retrieve the token across pages and redirects the user if not token was found.
63 changes: 63 additions & 0 deletions examples/with-cookie-auth-fauna/components/header.js
@@ -0,0 +1,63 @@
import Link from 'next/link'
import { logout } from '../utils/auth'

const Header = props => (
<header>
<nav>
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/login">
<a>Login</a>
</Link>
</li>
<li>
<Link href="/signup">
<a>Signup</a>
</Link>
</li>
<li>
<Link href="/profile">
<a>Profile</a>
</Link>
</li>
<li>
<button onClick={logout}>Logout</button>
</li>
</ul>
</nav>
<style jsx>{`
ul {
display: flex;
list-style: none;
margin-left: 0;
padding-left: 0;
}

li {
margin-right: 1rem;
}

li:first-child {
margin-left: auto;
}

a {
color: #fff;
text-decoration: none;
}

header {
padding: 0.2rem;
color: #fff;
background-color: #333;
}
`}</style>
</header>
)

export default Header
39 changes: 39 additions & 0 deletions examples/with-cookie-auth-fauna/components/layout.js
@@ -0,0 +1,39 @@
import Head from 'next/head'
import Header from './header'

const Layout = props => (
<>
<Head>
<title>With Cookies</title>
</Head>
<style jsx global>{`
*,
*::before,
*::after {
box-sizing: border-box;
}

body {
margin: 0;
color: #333;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'Helvetica Neue', Arial, Noto Sans, sans-serif, 'Apple Color Emoji',
'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
}

.container {
max-width: 65rem;
margin: 1.5rem auto;
padding-left: 1rem;
padding-right: 1rem;
}
`}</style>
<Header />

<main>
<div className="container">{props.children}</div>
</main>
</>
)

export default Layout
8 changes: 8 additions & 0 deletions examples/with-cookie-auth-fauna/next.config.js
@@ -0,0 +1,8 @@
require('dotenv').config()

module.exports = {
env: {
// Set the fauna server key in the .env file and make it available at Build Time.
FAUNA_SERVER_KEY: process.env.FAUNA_SERVER_KEY,
},
}
18 changes: 18 additions & 0 deletions examples/with-cookie-auth-fauna/package.json
@@ -0,0 +1,18 @@
{
"name": "with-cookie-auth",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"dotenv": "8.2.0",
"faunadb": "2.10.0",
"isomorphic-unfetch": "^3.0.0",
"js-cookie": "^2.2.0",
"next": "^9.0.1",
"cookie": "^0.4.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
}
}
29 changes: 29 additions & 0 deletions examples/with-cookie-auth-fauna/pages/api/login.js
@@ -0,0 +1,29 @@
import { query as q } from 'faunadb'
import { serverClient, serializeFaunaCookie } from '../../utils/fauna-auth'

export default async (req, res) => {
const { email, password } = await req.body

try {
if (!email || !password) {
throw new Error('Email and password must be provided.')
}

const loginRes = await serverClient.query(
q.Login(q.Match(q.Index('users_by_email'), email), {
password,
})
)
if (!loginRes.secret) {
throw new Error('No secret present in login query response.')
}
var cookieSerialized = serializeFaunaCookie(loginRes.secret)
res.setHeader('Set-Cookie', cookieSerialized)
res.status(200).json({ email })
} catch (error) {
const { response } = error
return response
? res.status(response.status).json({ message: response.statusText })
: res.status(400).json({ message: error.message })
}
}
25 changes: 25 additions & 0 deletions examples/with-cookie-auth-fauna/pages/api/logout.js
@@ -0,0 +1,25 @@
import { query as q } from 'faunadb'
import cookie from 'cookie'
import { faunaClient, FAUNA_SECRET_COOKIE } from '../../utils/fauna-auth'

export default async (req, res) => {
const cookies = cookie.parse(req.headers.cookie ?? '')
const faunaSecret = cookies[FAUNA_SECRET_COOKIE]
if (!faunaSecret) {
// Already logged out.
res.status(200).json({})
return
}
// Invalidate secret (ie. logout from Fauna).
await faunaClient(faunaSecret).query(q.Logout(false))
// Clear cookie.
const cookieSerialized = cookie.serialize(FAUNA_SECRET_COOKIE, '', {
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
maxAge: -1,
httpOnly: true,
path: '/',
})
res.setHeader('Set-Cookie', cookieSerialized)
res.status(200).json({})
}
18 changes: 18 additions & 0 deletions examples/with-cookie-auth-fauna/pages/api/profile.js
@@ -0,0 +1,18 @@
import { query as q } from 'faunadb'
import cookie from 'cookie'
import { faunaClient, FAUNA_SECRET_COOKIE } from '../../utils/fauna-auth'

export const profileApi = async faunaSecret => {
const ref = await faunaClient(faunaSecret).query(q.Identity())
return ref.id
}

export default async (req, res) => {
const cookies = cookie.parse(req.headers.cookie ?? '')
const faunaSecret = cookies[FAUNA_SECRET_COOKIE]
if (!faunaSecret) {
return res.status(401).send('Auth cookie missing.')
}

res.status(200).json({ userId: await profileApi(faunaSecret) })
}
44 changes: 44 additions & 0 deletions examples/with-cookie-auth-fauna/pages/api/signup.js
@@ -0,0 +1,44 @@
import { query as q } from 'faunadb'
import { serverClient, serializeFaunaCookie } from '../../utils/fauna-auth'

export default async (req, res) => {
const { email, password } = await req.body

try {
if (!email || !password) {
throw new Error('Email and password must be provided.')
}
console.log(`email: ${email} trying to create user.`)
let createRes
try {
createRes = await serverClient.query(
q.Create(q.Collection('User'), {
credentials: { password },
data: { email },
})
)
} catch (err) {
console.error('ERR', err)
throw new Error('User already exists.')
}
if (!createRes.ref) {
throw new Error('No ref present in create query response.')
}
const loginRes = await serverClient.query(
q.Login(createRes.ref, {
password,
})
)
if (!loginRes.secret) {
throw new Error('No secret present in login query response.')
}
var cookieSerialized = serializeFaunaCookie(loginRes.secret)
res.setHeader('Set-Cookie', cookieSerialized)
res.status(200).json({ email })
} catch (error) {
const { response } = error
return response
? res.status(response.status).json({ message: response.statusText })
: res.status(400).json({ message: error.message })
}
}
29 changes: 29 additions & 0 deletions examples/with-cookie-auth-fauna/pages/index.js
@@ -0,0 +1,29 @@
import React from 'react'
import Layout from '../components/layout'

const Home = () => (
<Layout>
<h1>Cookie-based authentication example</h1>

<p>Steps to test the functionality:</p>

<ol>
<li>Click signup and create an account, this will also log you in.</li>
<li>
Click home and click profile again, notice how your session is being
used through a token stored in a cookie.
</li>
<li>
Click logout and try to go to profile again. You'll get redirected to
the `/login` route.
</li>
</ol>
<style jsx>{`
li {
margin-bottom: 0.5rem;
}
`}</style>
</Layout>
)

export default Home