Hello to all,
I had to implement socket.io in my strapi API, but I need to check if the JWT token I pass as parameter is still valid.
I get this token with /auth/local request
How can I do ?
Example:
io.on('connection', function (socket) {
if (isValidToken(socket.handshake.query.token)){
//..
}
}
isValideToken(token) {
...
}
in the handler :
{
name: "connection",
handler: async ({ strapi }, socket) => {
// Authenticate the user when connecting
console.log("User connecting");
const token = socket.handshake.auth.token;
if (!token) {
console.log("No token provided");
socket.disconnect();
return;
}
// Decode the JWT token
try {
const decoded = await strapi.plugins[
"users-permissions"
].services.jwt.verify(token);
console.log("Decoded token", decoded);
// get the user from the database populating the company
const user = await strapi.entityService.findOne(
"plugin::users-permissions.user",
decoded.id,
{
populate: ["company"],
}
);
console.log("User", user);
// get user company chambers and create a room for each chamber
const company = user.company;
const chambers = await strapi.entityService.findMany(
"api::chambre.chambre",
{ company: company.id }
);
console.log("Chambers", chambers);
chambers.forEach((chambre) => {
socket.join(`chambre-${chambre.id}`);
});
socket.on("message", (data) => {
console.log(`Received message: ${data}`);
// Emit the message to all other clients in the same rooms
chambers.forEach((chambre) => {
strapi.io.to(`chambre-${chambre.id}`).emit("newMessage", data);
});
});
} catch (err) {
console.log("Error decoding token", err);
socket.disconnect();
}
},
}```