Closed
Description
Often one needs to check if a session is still valid on the server-side. For example, one may want to present the user with an option to logout on all devices, which then should invalidate all existing sessions.
For this, one needs to query for every request the a sever-side session storage (and perhaps update it). Currently, this is relatively hard to implement. A few suggestions to make this easier:
- Implement a
useRawSession
method to directly access the h3 session (in other words make public) - alternatively, add thesessionId
to the public interface ofUserSession
- Implement a server middleware that calls a hook where devs can check the validity of the
sessionId
(and update timestamps like "last active" etc) - ...and perhaps return some data that one would like to associate with the current session on all server routes but don't directly store in the user cookie (e.g. permissions)
Point two and three might look like:
export default defineEventHandler(async (event) => {
const session = await _useSession(event)
// session.id is not a good way to check if there is a session as it will always be set by h3 (except if one calls clearSession)
// use session.data instead, with the convention that if it is an empty object, there is no session ?
if (session.id && Object.keys(session.data).length !== 0) {
try {
// Check if session is valid
const info = await hooks.call('validateSession', {id: session.id, data: session.data})
// Is there a better to store data in the session object?
session.server = info
} catch {
// Clear session
await session.clear()
}
}
})