Unverified Commit 91adb866 authored by Sean Li's avatar Sean Li Committed by GitHub

Add example with Magic authentication (#11810)

* Add example with Magic and Passport.js

* Tweaked wording on README

* Fixed lint error

* Fixed prettier error

* Update examples/magic/README.md

Removed Download manually section from README
Co-Authored-By: 's avatarJoe Haddad <timer150@gmail.com>

* Removed dependency on passport and express + cleanup

* Changed ZEIT brand to Vercel

* Updated readme instructions and secrets

* Renamed example

* Changed db comment
Co-authored-by: 's avatarJoe Haddad <timer150@gmail.com>
Co-authored-by: 's avatarLuis Alvarez <luis@zeit.co>
parent 7d2ff812
MAGIC_PUBLISHABLE_KEY=
MAGIC_SECRET_KEY=
# Magic Example
This example show how to use [Magic](https://magic.link) with Next.js. The example features cookie-based, passwordless authentication with email-based magic links.
The example shows how to do a login and logout; and to get the user info using a hook with [SWR](https://swr.now.sh).
A DB is not included. But you can add any DB you like!.
The login cookie is `httpOnly`, meaning it can only be accessed by the API, and it's encrypted using [@hapi/iron](https://hapi.dev/family/iron) for more security.
## Deploy your own
Deploy the example using [Vercel Now](https://vercel.com/docs/now-cli#commands/overview/basic-usage):
[![Deploy with Vercel Now](https://vercel.com/button)](https://vercel.com/new/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-magic)
## 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-magic with-magic-app
# or
yarn create next-app --example with-magic with-magic-app
```
## Configuration
Login to the [Magic Dashboard](https://dashboard.magic.link/) and get the keys of your application
![Magic Dashboard](https://gblobscdn.gitbook.com/assets%2F-M1XNjqusnKyXZc7t7qQ%2F-M3HsSftOAghkNs-ttU3%2F-M3HsllfdwdDmeFXBK3U%2Fdashboard-pk.png?alt=media&token=4d6e7543-ae20-4355-951c-c6421b8f1b5f)
Next, copy the `.env.example` file in this directory to .env (which will be ignored by Git):
```bash
cp .env.example .env
```
Then set each variable on `.env`:
- `MAGIC_PUBLISHABLE_KEY` should look like `pk_test_abc` or `pk_live_ABC`
- `MAGIC_SECRET_KEY` should look like `sk_test_ABC` or `sk_live_ABC`
To deploy on Vercel, you need to set the environment variables with **Now Secrets** using [Now CLI](https://vercel.com/download) ([Documentation](https://vercel.com/docs/now-cli#commands/secrets)).
Install [Now CLI](https://vercel.com/download), log in to your account from the CLI, and run the following commands to add the environment variables. Replace `<MAGIC_PUBLISHABLE_KEY>` and `<MAGIC_SECRET_KEY>` with the corresponding strings in `.env`:
```bash
now secrets add next_example_magic_publishable_key <MAGIC_PUBLISHABLE_KEY>
now secrets add next_example_magic_secret_key <MAGIC_SECRET_KEY>
```
const Form = ({ errorMessage, onSubmit }) => (
<form onSubmit={onSubmit}>
<label>
<span>Email</span>
<input type="email" name="email" required />
</label>
<div className="submit">
<button type="submit">Sign Up / Login</button>
</div>
{errorMessage && <p className="error">{errorMessage}</p>}
<style jsx>{`
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 > a {
text-decoration: none;
}
.submit > button {
padding: 0.5rem 1rem;
cursor: pointer;
background: #fff;
border: 1px solid #ccc;
border-radius: 4px;
}
.submit > button:hover {
border-color: #888;
}
.error {
color: brown;
margin: 1rem 0 0;
}
`}</style>
</form>
)
export default Form
import Link from 'next/link'
import { useUser } from '../lib/hooks'
const Header = () => {
const user = useUser()
return (
<header>
<nav>
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
{user ? (
<>
<li>
<Link href="/profile">
<a>Profile</a>
</Link>
</li>
<li>
<a href="/api/logout">Logout</a>
</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;
}
header {
color: #fff;
background-color: #333;
}
`}</style>
</header>
)
}
export default Header
import Head from 'next/head'
import Header from './header'
const Layout = props => (
<>
<Head>
<title>Magic</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<main>
<div className="container">{props.children}</div>
</main>
<footer>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by <img src="/vercel.svg" alt="Vercel Logo" />
</a>
</footer>
<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: 42rem;
margin: 0 auto;
padding: 2rem 1.25rem;
}
footer {
width: 100%;
height: 100px;
border-top: 1px solid #eaeaea;
display: flex;
justify-content: center;
align-items: center;
}
`}</style>
</>
)
export default Layout
import { serialize, parse } from 'cookie'
const TOKEN_NAME = 'token'
const MAX_AGE = 60 * 60 * 8 // 8 hours
export function setTokenCookie(res, token) {
const cookie = serialize(TOKEN_NAME, token, {
maxAge: MAX_AGE,
expires: new Date(Date.now() + MAX_AGE * 1000),
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
})
res.setHeader('Set-Cookie', cookie)
}
export function removeTokenCookie(res) {
const cookie = serialize(TOKEN_NAME, '', {
maxAge: -1,
path: '/',
})
res.setHeader('Set-Cookie', cookie)
}
export function parseCookies(req) {
// For API Routes we don't need to parse the cookies.
if (req.cookies) return req.cookies
// For pages we do need to parse the cookies.
const cookie = req.headers?.cookie
return parse(cookie || '')
}
export function getTokenCookie(req) {
const cookies = parseCookies(req)
return cookies[TOKEN_NAME]
}
import { useEffect } from 'react'
import Router from 'next/router'
import useSWR from 'swr'
const fetcher = url =>
fetch(url)
.then(r => r.json())
.then(data => {
return { user: data?.user || null }
})
export function useUser({ redirectTo, redirectIfFound } = {}) {
const { data, error } = useSWR('/api/user', fetcher)
const user = data?.user
const finished = Boolean(data)
const hasUser = Boolean(user)
useEffect(() => {
if (!redirectTo || !finished) return
if (
// If redirectTo is set, redirect if the user was not found.
(redirectTo && !redirectIfFound && !hasUser) ||
// If redirectIfFound is also set, redirect if the user was found
(redirectIfFound && hasUser)
) {
Router.push(redirectTo)
}
}, [redirectTo, redirectIfFound, finished, hasUser])
return error ? null : user
}
import Iron from '@hapi/iron'
import { getTokenCookie } from './auth-cookies'
// Use an environment variable here instead of a hardcoded value for production
const TOKEN_SECRET = 'this-is-a-secret-value-with-at-least-32-characters'
export function encryptSession(session) {
return Iron.seal(session, TOKEN_SECRET, Iron.defaults)
}
export async function getSession(req) {
const token = getTokenCookie(req)
return token && Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
}
const { Magic } = require('@magic-sdk/admin')
export const magic = new Magic(process.env.MAGIC_SECRET_KEY)
const nextEnv = require('next-env')
const dotenvLoad = require('dotenv-load')
dotenvLoad()
const withNextEnv = nextEnv()
module.exports = withNextEnv({
env: {
MAGIC_PUBLISHABLE_KEY: process.env.MAGIC_PUBLISHABLE_KEY,
MAGIC_SECRET_KEY: process.env.MAGIC_SECRET_KEY,
},
devIndicators: {
autoPrerender: false,
},
})
{
"env": {
"MAGIC_PUBLISHABLE_KEY": "@next_example_magic_publishable_key",
"MAGIC_SECRET_KEY": "@next_example_magic_secret_key"
},
"build": {
"env": {
"MAGIC_PUBLISHABLE_KEY": "@next_example_magic_publishable_key",
"MAGIC_SECRET_KEY": "@next_example_magic_secret_key"
}
}
}
{
"name": "with-magic",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@hapi/iron": "6.0.0",
"@magic-sdk/admin": "1.0.0",
"cookie": "0.4.0",
"dotenv-load": "^2.0.0",
"magic-sdk": "1.0.1",
"next": "latest",
"next-env": "^1.1.1",
"react": "latest",
"react-dom": "latest",
"swr": "0.1.16"
},
"license": "ISC"
}
import { magic } from '../../lib/magic'
import { encryptSession } from '../../lib/iron'
import { setTokenCookie } from '../../lib/auth-cookies'
export default async function login(req, res) {
try {
const didToken = req.headers.authorization.substr(7)
const metadata = await magic.users.getMetadataByToken(didToken)
const session = { ...metadata }
// The token is a string with the encrypted session
const token = await encryptSession(session)
setTokenCookie(res, token)
res.status(200).send({ done: true })
} catch (error) {
res.status(error.status || 500).end(error.message)
}
}
import { magic } from '../../lib/magic'
import { removeTokenCookie } from '../../lib/auth-cookies'
import { getSession } from '../../lib/iron'
export default async function logout(req, res) {
const session = await getSession(req)
await magic.users.logoutByIssuer(session.issuer)
removeTokenCookie(res)
res.writeHead(302, { Location: '/' })
res.end()
}
import { getSession } from '../../lib/iron'
export default async function user(req, res) {
const session = await getSession(req)
// After getting the session you may want to fetch for the user instead
// of sending the session's payload directly, this example doesn't have a DB
// so it won't matter in this case
res.status(200).json({ user: session || null })
}
import { useUser } from '../lib/hooks'
import Layout from '../components/layout'
const Home = () => {
const user = useUser()
return (
<Layout>
<h1>Magic Example</h1>
<p>Steps to test this authentication example:</p>
<ol>
<li>Click Login and enter an email.</li>
<li>
You'll be redirected to Home. Click on Profile, 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
Login.
</li>
</ol>
<p>
To learn more about Magic, visit their{' '}
<a
href="https://docs.magic.link/"
target="_blank"
rel="noopener noreferrer"
>
documentation
</a>
.
</p>
{user && (
<>
<p>Currently logged in as:</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
)}
<style jsx>{`
li {
margin-bottom: 0.5rem;
}
`}</style>
</Layout>
)
}
export default Home
import { useState } from 'react'
import Router from 'next/router'
import { useUser } from '../lib/hooks'
import Layout from '../components/layout'
import Form from '../components/form'
import { Magic } from 'magic-sdk'
const Login = () => {
useUser({ redirectTo: '/', redirectIfFound: true })
const [errorMsg, setErrorMsg] = useState('')
async function handleSubmit(e) {
event.preventDefault()
if (errorMsg) setErrorMsg('')
const body = {
email: e.currentTarget.email.value,
}
try {
const magic = new Magic(process.env.MAGIC_PUBLISHABLE_KEY)
const didToken = await magic.auth.loginWithMagicLink({
email: body.email,
})
const res = await fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + didToken,
},
body: JSON.stringify(body),
})
if (res.status === 200) {
Router.push('/')
} else {
throw new Error(await res.text())
}
} catch (error) {
console.error('An unexpected error happened occurred:', error)
setErrorMsg(error.message)
}
}
return (
<Layout>
<div className="login">
<Form errorMessage={errorMsg} onSubmit={handleSubmit} />
</div>
<style jsx>{`
.login {
max-width: 21rem;
margin: 0 auto;
padding: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
}
`}</style>
</Layout>
)
}
export default Login
import { useUser } from '../lib/hooks'
import Layout from '../components/layout'
const Profile = () => {
const user = useUser({ redirectTo: '/login' })
return (
<Layout>
<h1>Profile</h1>
{user && (
<>
<p>Your session:</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
)}
</Layout>
)
}
export default Profile
<svg width="70" height="16" viewBox="0 0 283 64" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/></svg>
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