Skip to content

Verify and enrich session on server-side #203

Closed
@tobiasdiez

Description

@tobiasdiez

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:

  1. Implement a useRawSession method to directly access the h3 session (in other words make
    function _useSession(event: H3Event, config: Partial<SessionConfig> = {}) {
    public) - alternatively, add the sessionId to the public interface of UserSession
  2. Implement a server middleware that calls a hook where devs can check the validity of the sessionId (and update timestamps like "last active" etc)
  3. ...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()
    }
  }
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions