Skip to content
This repository has been archived by the owner on Dec 9, 2024. It is now read-only.

Commit

Permalink
Set identity cookie for logged in users
Browse files Browse the repository at this point in the history
  • Loading branch information
solocommand committed Oct 30, 2023
1 parent c745f1e commit 97f7e24
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions packages/marko-web-identity-x/middleware.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const { asyncRoute } = require('@parameter1/base-cms-utils');
const IdentityX = require('./service');

/**
Expand All @@ -6,9 +7,23 @@ const IdentityX = require('./service');
* @param {IdentityXConfiguration} config The IdentityX config object
* @returns {function} The middleware function
*/
module.exports = (config) => (req, res, next) => {
module.exports = (config) => asyncRoute(async (req, res, next) => {
const service = new IdentityX({ req, res, config });
req.identityX = service;
res.locals.identityX = service;
next();
};

const cookie = service.getIdentity(res);

// Don't overwrite an existing cookie
if (cookie) return next();

// Set cookie for logged in users
if (service.token) {
const { user } = await service.loadActiveContext();
if (user && user.id) {
service.setIdentityCookie(user.id);
}
}

return next();
});

0 comments on commit 97f7e24

Please sign in to comment.