wordpress-auth.js
“use strict”;
const fetch = require(“node-fetch”);
module.exports = {
async verifyToken(ctx) {
console.log(“verifyToken called”);
const { token } = ctx.request.body;
if (!token) {
return ctx.badRequest("No token provided");
}
try {
const wpResponse = await fetch(
"https://wordpresswebsiteworksfine.com/wp-json/wp/v2/users/me",
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
if (!wpResponse.ok) {
throw new Error("Failed to fetch user data");
}
const wpUserData = await wpResponse.json();
console.log("WordPress User Data:", wpUserData);
// Assuming roles are directly usable and match with Strapi's permissions system
const strapiRoleName = wpUserData.acf.strapirole;
console.log("strapiRoleName:", strapiRoleName);
// Generate a JWT token with the role's permissions only
const jwt = strapi.plugins["users-permissions"].services.jwt.issue({
role: strapiRoleName,
});
// Respond with the Strapi JWT token
ctx.body = {
status: "success",
message: "Token verified",
token: jwt, // This JWT is for API access, with only the role's permissions
strapiRole: strapiRoleName,
};
} catch (error) {
console.error("Error verifying token:", error);
ctx.body = {
status: "error",
message: "Token verification failed",
error: error.message,
};
}
},
};