Directus custom hook extension to change role of current user based on current role and User-Agent This allows to dynamically allow some permissions in on App and allow other permissions on another App or Directus App
Last active
March 17, 2025 06:44
-
-
Save joselcvarela/fee969bbdc0245659b9fcf12273c8754 to your computer and use it in GitHub Desktop.
Switch Directus role based on current role and User Agent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function ({ init }, context) { | |
init('middlewares.after', async function ({ app }) { | |
app.use(async (req, res, next) => { | |
const newAccountability = [] | |
if (req.accountability.role === 'bc5ff02e-3c01-4349-a4c9-7171f8fb5c5a') { | |
if (req.accountability.userAgent.includes('My App')) { | |
// On my app, has full permissions | |
const roles = ['bc5ff02e-3c01-4349-a4c9-7171f8fb5c5a'] | |
newAccountability.push(['roles', roles]) | |
newAccountability.push(['role', roles[0]]) | |
} else { | |
// By default, has App access but read only | |
const roles = ['fde2fe5c-e7d2-4acf-85a2-f9b8f011c9e0'] | |
newAccountability.push(['roles', roles]) | |
newAccountability.push(['role', roles[0]]) | |
newAccountability.push(['app', true]) | |
} | |
} | |
if (newAccountability.length) { | |
Object.assign(req.accountability, Object.fromEntries(newAccountability)) | |
} | |
next(); | |
}) | |
}) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "change-role", | |
"description": "Change Directus role based on User Agent", | |
"version": "1.0.0", | |
"type": "module", | |
"directus:extension": { | |
"type": "hook", | |
"path": "index.js", | |
"source": "index.ts", | |
"host": ">=11.0.0" | |
} | |
} |
Comments are disabled for this gist.