How to use Apostrophe CMS login to add code to user upon login

106 views Asked by At

I want to run a function when a user logs in to put a unique code onto the user. Then I can use this code to authenticate subsequent requests. I want to do something very similar to the weak2FA example on this page (https://v3.docs.apostrophecms.org/guide/custom-login-requirements.html#the-server-side), but I don't know how to structure the code so that it will not return the component to the frontend. Right now I get an error on the frontend because it's expecting a Vue component. I want the user to just enter in their username and password, and that's it. Then upon login it will add a code to the user model. Nothing more.

Does anyone know how this can be done?

1

There are 1 answers

0
Tom Boutell On

Since you're talking about doing this in the context of the built-in login page, you can take advantage of the afterSessionLogin promise event, like this:

// in modules/any-module-you-choose/index.js
module.exports = {
  handlers: {
    return {
      '@apostrophecms/login:afterSessionLogin': {
        async addCode(req) {
          await self.apos.doc.db.updateOne({ _id: req.user._id }, {
            $set: {
              code: myCodeHere
            }
          });
        }
      }
    };
  }
});

This code goes straight to MongoDB to set one property of the user document quickly without race conditions or permissions checks.