I’m trying to add user permissions to id token. This scripts works fine except for cache. The cache is always null. I tested this action in flow too. What am I doing wrong?
exports.onExecutePostLogin = async (event, api) => {
const ManagementClient = require('auth0').ManagementClient;
const jwt_decode = require('jwt-decode');
const axios = require('axios');
// Fetch cached token
const cachedTokenRecord = api.cache.get('token');
let token = cachedTokenRecord?.value;
const currentTime = Date.now().valueOf() / 1000;
let management;
if (token) {
console.log("Found cached access token.");
const decodedToken = jwt_decode(token);
if (decodedToken.exp > currentTime) {
management = new ManagementClient({
token: token,
domain: event.secrets.AUTH0_DOMAIN,
});
}
}
if (!management) {
try {
const response = await axios.post(`https://${event.secrets.AUTH0_DOMAIN}/oauth/token`, {
client_id: event.secrets.AUTH0_CLIENT_ID,
client_secret: event.secrets.AUTH0_CLIENT_SECRET,
audience: `https://${event.secrets.AUTH0_DOMAIN}/api/v2/`,
grant_type: 'client_credentials'
});
let newToken = response.data.access_token;
const cacheResult = api.cache.set('token', newToken);
if (cacheResult.type === 'error') {
console.error('Failed to set the token in the cache:', cacheResult.code);
} else {
console.log('Successfully set access token in cache');
}
management = new ManagementClient({
token: newToken,
domain: event.secrets.AUTH0_DOMAIN,
});
} catch (error) {
console.error('Error fetching new access token:', error);
throw new Error('Error fetching new access token');
}
}
try {
const params = { id: event.user.user_id, page: 0, per_page: 100, include_totals: true };
const permissions = await management.getUserPermissions(params);
const permissionsArr = permissions.permissions.map(permission => permission.permission_name);
api.idToken.setCustomClaim(`${event.secrets.NAMESPACE}user_authorization`, {
permissions: permissionsArr
});
} catch (err) {
console.error('Error fetching user permissions:', err);
throw new Error('Error fetching user permissions');
}
};