trasherdk / hyper-express

High performance Node.js webserver with a simple-to-use API powered by uWebsockets.js under the hood.
MIT License
0 stars 0 forks source link

Snippet: Custom session handling with `hyper-express-session` example code snippet #5

Open trasherdk opened 2 years ago

trasherdk commented 2 years ago

This should, in theory, be possible to mix in some passport session middleware.

Quote: In regards to authentication, If you need to work with cookie based sessions then you can use the official hyper-express-session middleware. While the official hyper-express-session is built for cookie based session transport, you could in theory use it situationally with any means of token transport like this:

const SessionEngine = require('hyper-express-session');
const TestEngine = /* Assume this is a SessionEngine instance with proper methods attached */

// Example of a route which creates the session
webserver.post('/session/create', async (request, response) => {
   // Perform some authentication here to ensure this request is good to go for creating a session

   // Initiate a new session
   await request.session.start();

   // Store some data in this session
   request.session.set({
       account_id: 'some_account_id',
       some_param: 'some_data',
       some_other_param: 'some_other_data'
   });

   // Send the signed session id as a token to the requester
   // Be sure to only return the signed id, so in the future we can unsign this id with our session engine secret for security
   return response.json({
        token: request.session.signed_id
   });
});

// Example of a route which loads a previously created session through a provided token rather than cookie header
webserver.post('/api/user/some-endpoint', async (request, response) => {
     // Retrieve the token from somewhere in the request as sent by the requester
     const token = request.headers['x-access-token'];

     // Resume a session by setting the signed id to the received token
     request.session.set_signed_id(token);
     await request.session.start();

     // We can check that the user provided token is a valid session by checking if it is stored in our database
     // Or we can also just check the data of the session to see if its a valid session
     if (!request.session.stored || request.session.get('account_id') == undefined)
         return response.status(403).json({
             code: 'UNAUTHENTICATED',
             message: 'Please provide a valid access token'
         });

     // The user has been verified so run the rest of your logic here with the session data as needed
});

Reference: https://github.com/kartikk221/hyper-express/discussions/41#discussioncomment-1884475