Session
Session plugins define an encoding/decoding scheme for converting raw session information
to (cookie) strings -- the designated storage mechanism for credentials in aponia.js
.
Session plugins are minimal, and can be used headlessly to handle session information.
When used with the framework, session plugins add post-request handlers to encode/decode any sessions that are defined during the authentication flow.
Headless Functionality
This section may be relocated to
getSession
Read a compatible cookies object, extract, decode, and return any session information stored in the cookie.
getRefresh
Read a compatible cookies object, extract, decode, and return any refresh information stored in the cookie.
createCookiesFromSession
Convert raw session information to cookie information. The cookie information is an object with the name, value, and options.
createCookiesFromRefresh
Convert raw refresh information to cookie information. The cookie information is an object with the name, value, and options.
Getting Started
- Initialize an instance of the plugin.
// src/session.ts
import { SessionPlugin } from '@aponia.js/core/plugins/session'
export const session = new SessionPlugin()
With an auth instance.
// src/auth.ts
import { Auth } from '@aponia.js/core'
import { session } from './session'
export const auth = new Auth({
plugins: [session]
})
Headless (express.js)
This example shows how a session can be retrieved, validated, and set on the Request
object on every request in express.js.
It also demonstrates how a session can be created and set as a cookie.
// src/routes.ts
import express from 'express'
import cookieParser from 'cookie-parser'
import { session } from './session'
const app = express()
// On every request, define `req.session` if there's a valid session found in the cookies.
app.use(async (req) => {
const cookieSession = await session.getSession(req.cookies)
const isValid = cookieSession.expires > Date.now()
if (isValid) {
req.session = cookieSession
}
})
// After logging in successfully, create a session cookie.
app.post('/auth/login', async (req, res) => {
// Create new session.
const newSession = {
id: "1"
}
// Create aponia.js cookie object.
const sessionCookie = await session.createCookiesFromSession(newSession)
// Set cookie using express.js API.
res.cookie(sessionCookie.name, sessionCookie.value, sessionCookie.options)
})