rsnext/examples/api-routes-apollo-server-and-client-auth/lib/auth.js
Luis Alvarez D 9dc902835c
[Examples] Move api-routes-apollo-server-and-client-auth to SSG (#13849)
Related to https://github.com/vercel/next.js/issues/11014

The authentication method has been replaced with an improved version of the passport example.
2020-06-10 03:46:11 +00:00

27 lines
808 B
JavaScript

import Iron from '@hapi/iron'
import { MAX_AGE, setTokenCookie, getTokenCookie } from './auth-cookies'
const TOKEN_SECRET = process.env.TOKEN_SECRET
export async function setLoginSession(res, session) {
const createdAt = Date.now()
// Create a session object with a max age that we can validate later
const obj = { ...session, createdAt, maxAge: MAX_AGE }
const token = await Iron.seal(obj, TOKEN_SECRET, Iron.defaults)
setTokenCookie(res, token)
}
export async function getLoginSession(req) {
const token = getTokenCookie(req)
if (!token) return
const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
const expiresAt = session.createdAt + session.maxAge * 1000
// Validate the expiration date of the session
if (Date.now() < expiresAt) {
return session
}
}