rsnext/examples/with-passport/lib/auth.js
Luis Alvarez D b540054388
Update authentication examples (#19330)
* Updated example readme

* Updated with-passport example

* Updated profile page for with-passport

* Updated with-passport-and-next-connect

* Updated with-magic

* Updated with-magic readme

* Updated with-iron-session

* Updated next version in with-iron-session

Co-authored-by: Lee Robinson <me@leerob.io>
2020-12-29 12:43:47 -05:00

29 lines
846 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) {
throw new Error('Session expired')
}
return session
}