Skip to content

Commit

Permalink
Updated files and added prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
lfades committed Jan 13, 2020
1 parent 8f44208 commit b5ae357
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 55 deletions.
5 changes: 2 additions & 3 deletions examples/with-cookie-auth-fauna/components/layout.js
@@ -1,9 +1,8 @@
import React from 'react'
import Head from 'next/head'
import Header from './header'

const Layout = props => (
<React.Fragment>
<>
<Head>
<title>With Cookies</title>
</Head>
Expand Down Expand Up @@ -34,7 +33,7 @@ const Layout = props => (
<main>
<div className="container">{props.children}</div>
</main>
</React.Fragment>
</>
)

export default Layout
3 changes: 2 additions & 1 deletion examples/with-cookie-auth-fauna/next.config.js
@@ -1,7 +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,
},
}
}
14 changes: 7 additions & 7 deletions examples/with-cookie-auth-fauna/pages/api/login.js
Expand Up @@ -8,18 +8,18 @@ export default async (req, res) => {
if (!email || !password) {
throw new Error('Email and password must be provided.')
}
const loginRes = (await serverClient.query(

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.');
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 });
var cookieSerialized = serializeFaunaCookie(loginRes.secret)
res.setHeader('Set-Cookie', cookieSerialized)
res.status(200).json({ email })
} catch (error) {
const { response } = error
return response
Expand Down
2 changes: 1 addition & 1 deletion examples/with-cookie-auth-fauna/pages/api/logout.js
@@ -1,4 +1,4 @@
import {query as q} from 'faunadb'
import { query as q } from 'faunadb'
import cookie from 'cookie'
import { faunaClient, FAUNA_SECRET_COOKIE } from '../../utils/fauna-auth'

Expand Down
6 changes: 3 additions & 3 deletions examples/with-cookie-auth-fauna/pages/api/profile.js
@@ -1,8 +1,8 @@
import {query as q} from 'faunadb'
import { query as q } from 'faunadb'
import cookie from 'cookie'
import { faunaClient, FAUNA_SECRET_COOKIE } from '../../utils/fauna-auth'

export const profileApi = async (faunaSecret) => {
export const profileApi = async faunaSecret => {
const ref = await faunaClient(faunaSecret).query(q.Identity())
return ref.id
}
Expand All @@ -14,5 +14,5 @@ export default async (req, res) => {
return res.status(401).send('Auth cookie missing.')
}

res.status(200).json({userId: await profileApi(faunaSecret)})
res.status(200).json({ userId: await profileApi(faunaSecret) })
}
17 changes: 9 additions & 8 deletions examples/with-cookie-auth-fauna/pages/api/signup.js
Expand Up @@ -18,22 +18,23 @@ export default async (req, res) => {
})
)
} catch (err) {
throw new Error('User already exists.');
console.error('ERR', err)
throw new Error('User already exists.')
}
if (!createRes.ref) {
throw new Error('No ref present in create query response.');
throw new Error('No ref present in create query response.')
}
const loginRes = (await serverClient.query(
const loginRes = await serverClient.query(
q.Login(createRes.ref, {
password,
})
))
)
if (!loginRes.secret) {
throw new Error('No secret present in login query response.');
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 });
var cookieSerialized = serializeFaunaCookie(loginRes.secret)
res.setHeader('Set-Cookie', cookieSerialized)
res.status(200).json({ email })
} catch (error) {
const { response } = error
return response
Expand Down
12 changes: 8 additions & 4 deletions examples/with-cookie-auth-fauna/pages/login.js
Expand Up @@ -7,10 +7,10 @@ const signin = async (email, password) => {
const url = '/api/login'
const response = await fetch(url, {
method: 'POST',

headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
})

if (response.status === 200) {
const { email } = await response.json()
login({ email })
Expand All @@ -19,13 +19,17 @@ const signin = async (email, password) => {
console.log('Login failed.')
// https://github.com/developit/unfetch#caveats
const { message } = await response.json()
let error = new Error(message ? message : response.statusText)
let error = new Error(message || response.statusText)
throw error
}
};
}

function Login() {
const [userData, setUserData] = useState({ email: '', password: '', error: '' })
const [userData, setUserData] = useState({
email: '',
password: '',
error: '',
})

async function handleSubmit(event) {
event.preventDefault()
Expand Down
49 changes: 23 additions & 26 deletions examples/with-cookie-auth-fauna/pages/profile.js
Expand Up @@ -13,7 +13,6 @@ const Profile = props => {
<h1>Your user id is {userId}</h1>

<style jsx>{`
h1 {
margin-bottom: 0;
}
Expand All @@ -24,34 +23,32 @@ const Profile = props => {

Profile.getInitialProps = async ctx => {
if (ctx.req) {
console.log(ctx.req.headers.cookie)
var cookies = cookie.parse(ctx.req.headers.cookie ?? '')
var faunaSecret = cookies[FAUNA_SECRET_COOKIE]
const cookies = cookie.parse(ctx.req.headers.cookie ?? '')
const faunaSecret = cookies[FAUNA_SECRET_COOKIE]

if (!faunaSecret) {
// If `ctx.req` is available it means we are on the server.
ctx.res.writeHead(302, { Location: '/login' });
ctx.res.end();
}
var profileInfo = await profileApi(faunaSecret);
return {userId: profileInfo};
} else {
const response = await fetch('/api/profile', {
method: 'POST',

headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
if (response.status === 200) {
const { userId } = await response.json()
return { userId }
} else {
console.log('Profile lookup failed.')
// https://github.com/developit/unfetch#caveats
const { message } = await response.json()
let error = new Error(message ? message : response.statusText)
throw error
ctx.res.writeHead(302, { Location: '/login' })
ctx.res.end()
return {}
}

const profileInfo = await profileApi(faunaSecret)

return { userId: profileInfo }
}

const response = await fetch('/api/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
const data = await response.json()

if (response.status !== 200) {
throw new Error(data.message || response.statusText)
}

return { userId: data.userId }
}

export default withAuthSync(Profile)
7 changes: 5 additions & 2 deletions examples/with-cookie-auth-fauna/pages/signup.js
Expand Up @@ -5,7 +5,11 @@ import { login } from '../utils/auth'
import Router from 'next/router'

function Signup() {
const [userData, setUserData] = useState({ email: '', password: '', error: '' })
const [userData, setUserData] = useState({
email: '',
password: '',
error: '',
})

async function handleSubmit(event) {
event.preventDefault()
Expand All @@ -28,7 +32,6 @@ function Signup() {
Router.push('/profile')
} else {
console.log('Signup failed.')
// https://github.com/developit/unfetch#caveats
const { message } = await response.json()
let error = new Error(message ? message : response.statusText)
throw error
Expand Down

0 comments on commit b5ae357

Please sign in to comment.