Unverified Commit 4094dfef authored by Luis Alvarez D's avatar Luis Alvarez D Committed by GitHub

Remove with-cookie-auth (#11865)

parent 5713bcbb
# Example app utilizing cookie-based authentication This example has been deprecated and removed in favor of one of the following examples:
In this example, we authenticate users and store a token in a cookie. The example only shows how the user session works, keeping a user logged in between pages. - [auth0](https://github.com/zeit/next.js/tree/canary/examples/auth0)
- [with-cookie-auth-fauna](https://github.com/zeit/next.js/tree/canary/examples/with-cookie-auth-fauna)
This example is backend agnostic and uses [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) to do the API calls on the client and the server. - [with-passport](https://github.com/zeit/next.js/tree/canary/examples/with-passport)
The repo includes a minimal passwordless 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) and the [GitHub API](https://developer.github.com/v3/). The backend allows the user to log in with their GitHub username.
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.
## Deploy your own
Deploy the example using [ZEIT Now](https://zeit.co/now):
[![Deploy with ZEIT Now](https://zeit.co/button)](https://zeit.co/import/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-cookie-auth)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npm init next-app --example with-cookie-auth with-cookie-auth-app
# or
yarn create next-app --example with-cookie-auth with-cookie-auth-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
cd with-cookie-auth
```
### Run locally
After you clone the repository you can install the dependencies, run `yarn dev` and start hacking! You'll be able to see the application running locally as if it were deployed.
```bash
$ cd with-cookie-auth
$ (with-cookie-auth/) yarn install
$ (with-cookie-auth/) yarn dev
```
### Deploy
Deploy it to the cloud with [ZEIT Now](https://zeit.co/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
import Link from 'next/link'
import { logout } from '../utils/auth'
const Header = () => (
<header>
<nav>
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/login">
<a>Login</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
import React from 'react'
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
{
"name": "with-cookie-auth",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"isomorphic-unfetch": "latest",
"js-cookie": "latest",
"next": "latest",
"next-cookies": "latest",
"react": "latest",
"react-dom": "latest"
}
}
import fetch from 'isomorphic-unfetch'
export default async (req, res) => {
const { username } = await req.body
console.log('username', username)
const url = `https://api.github.com/users/${username}`
try {
const response = await fetch(url)
if (response.ok) {
const { id } = await response.json()
return res.status(200).json({ token: id })
} else {
// https://github.com/developit/unfetch#caveats
const error = new Error(response.statusText)
error.response = response
throw error
}
} catch (error) {
const { response } = error
return response
? res.status(response.status).json({ message: response.statusText })
: res.status(400).json({ message: error.message })
}
}
import fetch from 'isomorphic-unfetch'
export default async (req, res) => {
if (!('authorization' in req.headers)) {
return res.status(401).send('Authorization header missing')
}
const auth = await req.headers.authorization
try {
const { token } = JSON.parse(auth)
const url = `https://api.github.com/user/${token}`
const response = await fetch(url)
if (response.ok) {
const js = await response.json()
// Need camelcase in the frontend
const data = Object.assign({}, { avatarUrl: js.avatar_url }, js)
return res.status(200).json({ data })
} else {
// https://github.com/developit/unfetch#caveats
const error = new Error(response.statusText)
error.response = response
throw error
}
} catch (error) {
const { response } = error
return response
? res.status(response.status).json({ message: response.statusText })
: res.status(400).json({ message: error.message })
}
}
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 login and enter your GitHub username.</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
import React, { useState } from 'react'
import fetch from 'isomorphic-unfetch'
import Layout from '../components/layout'
import { login } from '../utils/auth'
const Login = () => {
const [userData, setUserData] = useState({ username: '', error: '' })
const handleSubmit = async event => {
event.preventDefault()
setUserData(Object.assign({}, userData, { error: '' }))
const username = userData.username
const url = '/api/login'
try {
const response = await fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username }),
})
if (response.status === 200) {
const { token } = await response.json()
await login({ token })
} else {
console.log('Login failed.')
// https://github.com/developit/unfetch#caveats
let error = new Error(response.statusText)
error.response = response
throw error
}
} catch (error) {
console.error(
'You have an error in your code or there are Network issues.',
error
)
const { response } = error
setUserData(
Object.assign({}, userData, {
error: response ? response.statusText : error.message,
})
)
}
}
return (
<Layout>
<div className="login">
<form onSubmit={handleSubmit}>
<label htmlFor="username">GitHub username</label>
<input
type="text"
id="username"
name="username"
value={userData.username}
onChange={event =>
setUserData(
Object.assign({}, userData, { username: event.target.value })
)
}
/>
<button type="submit">Login</button>
{userData.error && <p className="error">Error: {userData.error}</p>}
</form>
</div>
<style jsx>{`
.login {
max-width: 340px;
margin: 0 auto;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
form {
display: flex;
flex-flow: column;
}
label {
font-weight: 600;
}
input {
padding: 8px;
margin: 0.3rem 0 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
.error {
margin: 0.5rem 0 0;
color: brown;
}
`}</style>
</Layout>
)
}
export default Login
import React from 'react'
import Router from 'next/router'
import fetch from 'isomorphic-unfetch'
import nextCookie from 'next-cookies'
import Layout from '../components/layout'
import { withAuthSync } from '../utils/auth'
import getHost from '../utils/get-host'
const Profile = props => {
const { name, login, bio, avatarUrl } = props.data
return (
<Layout>
<img src={avatarUrl} alt="Avatar" />
<h1>{name}</h1>
<p className="lead">{login}</p>
<p>{bio}</p>
<style jsx>{`
img {
max-width: 200px;
border-radius: 0.5rem;
}
h1 {
margin-bottom: 0;
}
.lead {
margin-top: 0;
font-size: 1.5rem;
font-weight: 300;
color: #666;
}
p {
color: #6a737d;
}
`}</style>
</Layout>
)
}
Profile.getInitialProps = async ctx => {
const { token } = nextCookie(ctx)
const apiUrl = getHost(ctx.req) + '/api/profile'
const redirectOnError = () =>
typeof window !== 'undefined'
? Router.push('/login')
: ctx.res.writeHead(302, { Location: '/login' }).end()
try {
const response = await fetch(apiUrl, {
credentials: 'include',
headers: {
Authorization: JSON.stringify({ token }),
},
})
if (response.ok) {
const js = await response.json()
console.log('js', js)
return js
} else {
// https://github.com/developit/unfetch#caveats
return await redirectOnError()
}
} catch (error) {
// Implementation or Network error
return redirectOnError()
}
}
export default withAuthSync(Profile)
import { useEffect } from 'react'
import Router from 'next/router'
import nextCookie from 'next-cookies'
import cookie from 'js-cookie'
export const login = ({ token }) => {
cookie.set('token', token, { expires: 1 })
Router.push('/profile')
}
export const auth = ctx => {
const { token } = nextCookie(ctx)
// If there's no token, it means the user is not logged in.
if (!token) {
if (typeof window === 'undefined') {
ctx.res.writeHead(302, { Location: '/login' })
ctx.res.end()
} else {
Router.push('/login')
}
}
return token
}
export const logout = () => {
cookie.remove('token')
// to support logging out from all windows
window.localStorage.setItem('logout', Date.now())
Router.push('/login')
}
export const withAuthSync = WrappedComponent => {
const Wrapper = props => {
const syncLogout = event => {
if (event.key === 'logout') {
console.log('logged out from storage!')
Router.push('/login')
}
}
useEffect(() => {
window.addEventListener('storage', syncLogout)
return () => {
window.removeEventListener('storage', syncLogout)
window.localStorage.removeItem('logout')
}
}, [])
return <WrappedComponent {...props} />
}
Wrapper.getInitialProps = async ctx => {
const token = auth(ctx)
const componentProps =
WrappedComponent.getInitialProps &&
(await WrappedComponent.getInitialProps(ctx))
return { ...componentProps, token }
}
return Wrapper
}
// This is not production ready, (except with providers that ensure a secure host, like Now)
// For production consider the usage of environment variables and NODE_ENV
function getHost(req) {
if (!req) return ''
const { host } = req.headers
if (host.startsWith('localhost')) {
return `http://${host}`
}
return `https://${host}`
}
export default getHost
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