I took the code from node_modules\@strapi\admin\dist\server\index.js
and modified it to check if a Super Admin is using a public API route. In combination with a custom setting, this allows me to execute code or call a function inside of strapi —in my case, to run shelljs commands.
api controller code to check for super admin:
const { authorization } = ctx.request.header;
if (!authorization) {
return {
message: false
};
}
const parts = authorization.split(/\s+/);
if (parts[0].toLowerCase() !== 'bearer' || parts.length !== 2) {
return {
message: false
};
}
const token = parts[1];
const { payload, isValid } = strapi.service(`admin::token`).decodeJwtToken(token);
if (!isValid) {
return {
message: false
};
}
const user = await strapi.db.query('admin::user').findOne({
where: {
id: payload.id
},
populate: [
'roles'
]
});
const superAdminRole = user.roles.find(x => x.code === 'strapi-super-admin')
if (!user || !(user.isActive === true) || !superAdminRole) {
return {
message: false
};
}
return {message: true};
custom src\admin\app.tsx to show a button in the admin panel:
import React from 'react';
import { Main, Box, Button, Typography } from '@strapi/design-system';
const MyCustomButtonPage = () => {
const handleClick = async () => {
try {
const response = await fetch('/api/my-custom-endpoint', { method: 'POST' });
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
};
return (
<Main>
<Box padding={6}>
<Typography variant="alpha">Custom Button</Typography>
<Box marginTop={4}>
<Button variant="default" onClick={handleClick}>
Aktion ausführen
</Button>
</Box>
</Box>
</Main>
);
};
export default {
bootstrap(app) {
app.addSettingsLink('global', {
intlLabel: {
id: 'my-custom-settings.label',
defaultMessage: 'Custom Button',
},
id: 'my-custom-settings',
to: '/settings/my-custom-button',
Component: async () => {
const component = MyCustomButtonPage as any;
return component;
},
permissions: [],
});
},
};