Unverified Commit ee372f47 authored by Hoang Vo's avatar Hoang Vo Committed by GitHub

feat(example): add CRUD example with next-connect and passport (#11359)

* Add with-next-connect example

* Update README

* Fix code and lint

* Fix typo

* Run prettier

* Include username

* Rename example

* Match with-passport styling

* Add comments in code

* Run prettier

* Rewrite example

* Add some comments

* Update README.md

* keys -> secret

* Updated package.json and readme

* UX changes

* Securely encrypt cookie with @hapi/iron

* Update README

* Abstract db related actions and update README

* security: add note on password hashing

* remove unused dep

* Updated readme
Co-authored-by: 's avatarLuis Alvarez <luis@zeit.co>
parent 65335155
# next-connect and Passport
This example creates a basic [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) app using [next-connect](https://github.com/hoangvvo/next-connect) and cookie-based authentication with [Passport.js](http://www.passportjs.org/). The cookie is securely encrypted using [@hapi/iron](https://github.com/hapijs/iron).
The example shows how to do a sign up, login, logout, and account deactivation. It utilizes [SWR](https://swr.now.sh/) to fetch the API.
For demo purpose, the users database is stored in the cookie session. You need to replace it with an actual database to store users in [db.js](lib/db.js).
In production, you must use a password hashing library, such as [argon2](https://github.com/ranisalt/node-argon2) or [bcrypt](https://www.npmjs.com/package/bcrypt).
## 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-passport-and-next-connect)
## How to use
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
npx create-next-app --example with-passport-and-next-connect with-passport-and-next-connect-app
# or
yarn create next-app --example with-passport-and-next-connect with-passport-and-next-connect-app
```
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 { useUser } from '../lib/hooks'
export default function Navbar() {
const [user, { mutate }] = useUser()
async function handleLogout() {
await fetch('/api/logout')
mutate({ user: null })
}
return (
<header>
<nav>
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
{user ? (
<>
<li>
<Link href="/profile">
<a>Profile</a>
</Link>
</li>
<li>
<a role="button" onClick={handleLogout}>
Logout
</a>
</li>
</>
) : (
<>
<li>
<Link href="/signup">
<a>Sign up</a>
</Link>
</li>
<li>
<Link href="/login">
<a>Login</a>
</Link>
</li>
</>
)}
</ul>
</nav>
<style jsx>{`
nav {
max-width: 42rem;
margin: 0 auto;
padding: 0.2rem 1.25rem;
}
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;
cursor: pointer;
}
header {
color: #fff;
background-color: #333;
}
`}</style>
</header>
)
}
export function getAllUsers(req) {
// For demo purpose only. You are not likely to have to return all users.
return req.session.users
}
export function createUser(req, user) {
// Here you should insert the user into the database
// await db.createUser(user)
req.session.users.push(user)
}
export function findUserByUsername(req, username) {
// Here you find the user based on id/username in the database
// const user = await db.findUserById(id)
return req.session.users.find(user => user.username === username)
}
export function updateUserByUsername(req, username, update) {
// Here you update the user based on id/username in the database
// const user = await db.updateUserById(id, update)
const user = req.session.users.find(u => u.username === username)
Object.assign(user, update)
return user
}
export function deleteUser(req, username) {
// Here you should delete the user in the database
// await db.deleteUser(req.user)
req.session.users = req.session.users.filter(
user => user.username !== req.user.username
)
}
import useSWR from 'swr'
export const fetcher = url => fetch(url).then(r => r.json())
export function useUser() {
const { data, mutate } = useSWR('/api/user', fetcher)
// if data is not defined, the query has not completed
const loading = !data
const user = data?.user
return [user, { mutate, loading }]
}
import passport from 'passport'
import LocalStrategy from 'passport-local'
import { findUserByUsername } from './db'
passport.serializeUser(function(user, done) {
// serialize the username into session
done(null, user.username)
})
passport.deserializeUser(function(req, id, done) {
// deserialize the username back into user object
const user = findUserByUsername(req, id)
done(null, user)
})
passport.use(
new LocalStrategy(
{ passReqToCallback: true },
(req, username, password, done) => {
// Here you lookup the user in your DB and compare the password/hashed password
const user = findUserByUsername(req, username)
// Security-wise, if you hashed the password earlier, you must verify it
// if (!user || await argon2.verify(user.password, password))
if (!user || user.password !== password) {
done(null, null)
} else {
done(null, user)
}
}
)
)
export default passport
import { parse, serialize } from 'cookie'
import Iron from '@hapi/iron'
export default function session({ name, secret, cookie: cookieOpts }) {
return async (req, res, next) => {
const cookie = req.headers?.cookie ? parse(req.headers.cookie) : null
let unsealed
if (cookie?.[name]) {
try {
// the cookie needs to be unsealed using the password `secret`
unsealed = await Iron.unseal(cookie[name], secret, Iron.defaults)
} catch (e) {
// To cookie is invalid, do nothing
}
}
// Initialize the session
req.session = unsealed || {}
// We are proxying res.end to commit the session cookie
const oldEnd = res.end
res.end = async function resEndProxy(...args) {
if (res.finished || res.writableEnded || res.headersSent) return
// sealing the cookie to be sent to client
const sealed = await Iron.seal(req.session, secret, Iron.defaults)
res.setHeader('Set-Cookie', serialize(name, sealed, cookieOpts))
oldEnd.apply(this, args)
}
next()
}
}
import nextConnect from 'next-connect'
import passport from '../lib/passport'
import session from '../lib/session'
const auth = nextConnect()
.use(
session({
name: 'sess',
secret: 'some_not_random_password_that_is_at_least_32_characters', // This should be kept securely, preferably in env vars
cookie: {
maxAge: 60 * 60 * 8, // 8 hours,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
},
})
)
.use((req, res, next) => {
// Initialize mocked database
// Remove this after you add your own database
req.session.users = req.session.users || []
next()
})
.use(passport.initialize())
.use(passport.session())
export default auth
{
"name": "with-passport-and-next-connect",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@hapi/iron": "6.0.0",
"cookie": "0.4.0",
"next": "latest",
"next-connect": "^0.6.1",
"passport": "^0.4.1",
"passport-local": "^1.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"swr": "^0.1.18"
},
"license": "ISC"
}
import Navbar from '../components/Navbar'
import '../styles.css'
export default function MyApp({ Component, pageProps }) {
return (
<>
<Navbar />
<main>
<div className="container">
<Component {...pageProps} />
</div>
</main>
</>
)
}
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import passport from '../../lib/passport'
const handler = nextConnect()
handler.use(auth).post(passport.authenticate('local'), (req, res) => {
res.json({ user: req.user })
})
export default handler
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
const handler = nextConnect()
handler.use(auth).get((req, res) => {
req.logOut()
res.status(204).end()
})
export default handler
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import { deleteUser, updateUserByUsername } from '../../lib/db'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
// You do not generally want to return the whole user object
// because it may contain sensitive field such as !!password!! Only return what needed
// const { name, username, favoriteColor } = req.user
// res.json({ user: { name, username, favoriteColor } })
res.json({ user: req.user })
})
.use((req, res, next) => {
// handlers after this (PUT, DELETE) all require an authenticated user
// This middleware to check if user is authenticated before continuing
if (!req.user) {
res.status(401).send('unauthenticated')
} else {
next()
}
})
.put((req, res) => {
const { name } = req.body
const user = updateUserByUsername(req, req.user.username, { name })
res.json({ user })
})
.delete((req, res) => {
deleteUser(req)
req.logOut()
res.status(204).end()
})
export default handler
import nextConnect from 'next-connect'
import auth from '../../middleware/auth'
import { getAllUsers, createUser, findUserByUsername } from '../../lib/db'
const handler = nextConnect()
handler
.use(auth)
.get((req, res) => {
// For demo purpose only. You will never have an endpoint which returns all users.
// Remove this in production
res.json({ users: getAllUsers(req) })
})
.post((req, res) => {
const { username, password, name } = req.body
if (!username || !password || !name) {
return res.status(400).send('Missing fields')
}
// Here you check if the username has already been used
const usernameExisted = !!findUserByUsername(req, username)
if (usernameExisted) {
return res.status(409).send('The username has already been used')
}
const user = { username, password, name }
// Security-wise, you must hash the password before saving it
// const hashedPass = await argon2.hash(password);
// const user = { username, password: hashedPass, name }
createUser(req, user)
req.logIn(user, err => {
if (err) throw err
// Log the signed up user in
res.status(201).json({
user,
})
})
})
export default handler
import { useUser, fetcher } from '../lib/hooks'
import useSWR from 'swr'
function UserList() {
const { data: { users } = {} } = useSWR('/api/users', fetcher)
return (
<>
<h2>All users</h2>
{!!users?.length && (
<ul>
{users.map(user => (
<li key={user.username}>{JSON.stringify(user)}</li>
))}
</ul>
)}
</>
)
}
export default function HomePage() {
const [user] = useUser()
return (
<>
<h1>
<a href="http://www.passportjs.org/">Passport.js</a> +{' '}
<a href="https://github.com/hoangvvo/next-connect">next-connect</a>{' '}
Example
</h1>
<h2>Steps to test the example:</h2>
<h3>Sign up</h3>
<ol>
<li>Click Sign up and enter a username and password.</li>
<li>You will be logged in and redirected home.</li>
<li>Click Logout. You will be redirected home.</li>
<li>
Try sign up again with the same username, you will see an error.
</li>
</ol>
<h3>Sign in</h3>
<ol>
<li>Click Login and login again using the same credential.</li>
<li>You will see an error if you use incorrect credential.</li>
<li>Otherwise, you will be authenticated and redirected home.</li>
</ol>
<h3>Edit profile</h3>
<ol>
<li>Click Profile</li>
<li>Enter a new name and click Update profile.</li>
<li>Notice how the name in Your profile has changed.</li>
<li>Click Delete profile</li>
<li>
The user is removed and is no longer shown in All users section in
Home
</li>
</ol>
{user && <p>Currently logged in as: {JSON.stringify(user)}</p>}
<UserList />
<style jsx>{`
li {
margin-bottom: 0.5rem;
}
`}</style>
</>
)
}
import { useState, useEffect } from 'react'
import Router from 'next/router'
import Link from 'next/link'
import { useUser } from '../lib/hooks'
export default function LoginPage() {
const [user, { mutate }] = useUser()
const [errorMsg, setErrorMsg] = useState('')
async function onSubmit(e) {
e.preventDefault()
const body = {
username: e.currentTarget.username.value,
password: e.currentTarget.password.value,
}
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (res.status === 200) {
const userObj = await res.json()
// set user to useSWR state
mutate(userObj)
} else {
setErrorMsg('Incorrect username or password. Try better!')
}
}
useEffect(() => {
// redirect to home if user is authenticated
if (user) Router.push('/')
}, [user])
return (
<>
<h1>Login to Example</h1>
{errorMsg && <p className="error">{errorMsg}</p>}
<div className="form-container">
<form onSubmit={onSubmit}>
<label>
<span>Username</span>
<input type="text" name="username" required />
</label>
<label>
<span>Password</span>
<input type="password" name="password" required />
</label>
<div className="submit">
<button type="submit">Login</button>
<Link href="/signup">
<a>I don't have an account</a>
</Link>
</div>
</form>
</div>
</>
)
}
import { useEffect, useRef } from 'react'
import Router from 'next/router'
import { useUser } from '../lib/hooks'
function ProfileEdit() {
const [user, { mutate }] = useUser()
const nameRef = useRef()
useEffect(() => {
if (!user) return
nameRef.current.value = user.name
}, [user])
async function handleEditProfile(e) {
e.preventDefault()
const body = {
name: nameRef.current.value,
}
const res = await fetch(`/api/user`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const updatedUser = await res.json()
mutate(updatedUser)
}
async function handleDeleteProfile() {
const res = await fetch(`/api/user`, {
method: 'DELETE',
})
if (res.status === 204) {
mutate({ user: null })
Router.replace('/')
}
}
return (
<>
<div className="form-container">
<form onSubmit={handleEditProfile}>
<label>
<span>Name</span>
<input type="text" ref={nameRef} required />
</label>
<div className="submit">
<button type="submit">Update profile</button>
<a role="button" className="delete" onClick={handleDeleteProfile}>
Delete profile
</a>
</div>
</form>
</div>
<style jsx>{`
.delete {
color: #f44336;
cursor: pointer;
}
.delete:hover {
color: #b71c1c;
}
`}</style>
</>
)
}
export default function ProfilePage() {
const [user, { loading }] = useUser()
useEffect(() => {
// redirect user to login if not authenticated
if (!loading && !user) Router.replace('/login')
}, [user, loading])
return (
<>
<h1>Profile</h1>
{user && (
<>
<p>Your profile: {JSON.stringify(user)}</p>
<ProfileEdit />
</>
)}
</>
)
}
import { useState, useEffect } from 'react'
import Router from 'next/router'
import Link from 'next/link'
import { useUser } from '../lib/hooks'
export default function SignupPage() {
const [user, { mutate }] = useUser()
const [errorMsg, setErrorMsg] = useState('')
async function onSubmit(e) {
e.preventDefault()
const body = {
username: e.currentTarget.username.value,
password: e.currentTarget.password.value,
name: e.currentTarget.name.value,
}
if (body.password !== e.currentTarget.rpassword.value) {
setErrorMsg(`The passwords don't match`)
return
}
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (res.status === 201) {
const userObj = await res.json()
// set user to useSWR state
mutate(userObj)
} else {
setErrorMsg(await res.text())
}
}
useEffect(() => {
// redirect to home if user is authenticated
if (user) Router.push('/')
}, [user])
return (
<>
<h1>Sign up to Example</h1>
{errorMsg && <p className="error">{errorMsg}</p>}
<div className="form-container">
<form onSubmit={onSubmit}>
<label>
<span>Username</span>
<input type="text" name="username" required />
</label>
<label>
<span>Password</span>
<input type="password" name="password" required />
</label>
<label>
<span>Repeat password</span>
<input type="password" name="rpassword" required />
</label>
<label>
<span>Name</span>
<input type="text" name="name" required />
</label>
<div className="submit">
<button type="submit">Sign up</button>
<Link href="/login">
<a>I already have an account</a>
</Link>
</div>
</form>
</div>
</>
)
}
*,
*::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: 42rem;
margin: 0 auto;
padding: 2rem 1.25rem;
}
h1 {
text-align: center;
}
.form-container {
max-width: 21rem;
margin: 0 auto;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
form,
label {
display: flex;
flex-flow: column;
}
label > span {
font-weight: 600;
}
input {
padding: 8px;
margin: 0.3rem 0 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
.submit {
display: flex;
justify-content: flex-end;
align-items: center;
justify-content: space-between;
}
.submit > button {
padding: 0.5rem 1rem;
cursor: pointer;
background: #fff;
border: 1px solid #ccc;
border-radius: 4px;
}
.submit > button:hover {
border-color: #888;
}
.submit > a {
text-decoration: none;
}
.error {
color: brown;
margin: 0.5rem 0;
text-align: center;
}
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