I want to get the user IP and store it in DB immediately after user registration.
I know that I can use model LifeCycles like (afterCreate or beforeCreate) but the problem is that there
I don’t have access to (ctx.request) …
And I think to write this logic in users_permissions Controller…
But how to (create/customize) this controller without affecting its own plugin logic?
Any hint will be useful …thanks
The best option that wouldn’t require messing with the users-permissions plugin would be to create a custom middleware that runs as the response payload is being sent back to the user.
Depending on where you place your logic will determine when the logic will run (basically before or after the await next()
module.exports = strapi => {
return {
initialize() {
strapi.app.use(async (ctx, next) => {
await next();
// You'll probably want to log the ctx.request.route and do some if() to check the route for only registrations or whatever
console.log(ctx.headers); // If using proxy, IP will be in an x-forwarded-for header
console.log(ctx.ip);
console.log(ctx.ips);
// From here you would have access to the ctx.response.body to grab the users ID
// And could do something like:
await strapi.query('user', 'users-permissions').update({ id: ctx.response.body.id}, { ipaddress: ctx.ip});
// or put it anywhere else
});
},
};
};
If you want to see an example middleware that might be useful to check what is available to middlewares I created a small debug middleware that will log out some stuff (they are all disabled by default so you’ll have to adjust the settings).
Hi @DMehaffy , Yes, I just created a custom endpoint which I’m calling from UI after the user is registered…so in this way, I have access to the request and all stuff I need… because from my point of view seems more cleaner to have 2 endpoints (one for registration and one for data setup after registration) instead of writing a middleware or rewriting things in users_permissions plugin…but yeah your idea is also good.