rsnext/examples/with-firebase-authentication-serverless/utils/middleware/cookieSession.js
Kevin Jennison 34f1aefa4a Add example: with-firebase-authentication-serverless (#10078)
* Start from existing example

* Upgrade some dependencies

* Use dotenv

* Remove custom server

* Add serverless Firebase auth

* Add TODOs

* Update project name

* Fix build script

* Remove server middleware from client JS bundle

* Add logout functionality

* Redirect to auth page on logout

* Remove TODO

* Add comments about the cookie-session approach

* Remove the sessions folder

* Add comments for eslint

* Remove unused files

* Clarify comment

* Update README.md

* Rename variable for clarity

* Update README.md

* Change some comments

* Add more to gitignore

* Remove the bundle analyzer

* Move server-side auth user logic from _app.js to a HOC to support static HTML rendering

Co-authored-by: Joe Haddad <timer150@gmail.com>
2020-01-20 16:12:48 -05:00

41 lines
1.2 KiB
JavaScript

import cookieSession from 'cookie-session'
export const addSession = (req, res) => {
// Ensure that session secrets are set.
if (
!(process.env.SESSION_SECRET_CURRENT && process.env.SESSION_SECRET_PREVIOUS)
) {
throw new Error(
'Session secrets must be set as env vars `SESSION_SECRET_CURRENT` and `SESSION_SECRET_PREVIOUS`.'
)
}
// An array is useful for rotating secrets without invalidating old sessions.
// The first will be used to sign cookies, and the rest to validate them.
// https://github.com/expressjs/cookie-session#keys
const sessionSecrets = [
process.env.SESSION_SECRET_CURRENT,
process.env.SESSION_SECRET_PREVIOUS,
]
// Example:
// https://github.com/billymoon/micro-cookie-session
const includeSession = cookieSession({
keys: sessionSecrets,
// TODO: set other options, such as "secure", "sameSite", etc.
// https://github.com/expressjs/cookie-session#cookie-options
maxAge: 604800000, // week
httpOnly: true,
overwrite: true,
})
includeSession(req, res, () => {})
}
export default handler => (req, res) => {
try {
addSession(req, res)
} catch (e) {
return res.status(500).json({ error: 'Could not get user session.' })
}
return handler(req, res)
}