|
| 1 | +#!/usr/bin/env ts-node |
| 2 | + |
| 3 | +/* |
| 4 | +Backend CLI, currently providing 3 commands for user management: |
| 5 | + npx cli addAdmin --sciper 1234 |
| 6 | + npx cli listUserPermissions --sciper 1234 |
| 7 | + npx cli removeAdmin --sciper 1234 |
| 8 | +*/ |
| 9 | + |
| 10 | +import { Command } from 'commander'; |
| 11 | +import { SequelizeAdapter } from 'casbin-sequelize-adapter'; |
| 12 | +import { newEnforcer } from 'casbin'; |
| 13 | + |
| 14 | +const program = new Command(); |
| 15 | + |
| 16 | +async function initEnforcer() { |
| 17 | + const dbAdapter = await SequelizeAdapter.newAdapter({ |
| 18 | + dialect: 'postgres', |
| 19 | + host: process.env.DATABASE_HOST, |
| 20 | + port: parseInt(process.env.DATABASE_PORT || '5432', 10), |
| 21 | + username: process.env.DATABASE_USERNAME, |
| 22 | + password: process.env.DATABASE_PASSWORD, |
| 23 | + database: 'casbin', |
| 24 | + }); |
| 25 | + |
| 26 | + return newEnforcer('src/model.conf', dbAdapter); |
| 27 | +} |
| 28 | + |
| 29 | +program |
| 30 | + .command('addAdmin') |
| 31 | + .description('Given a SCIPER number, the owner would gain full admin permissions') |
| 32 | + .requiredOption('-s, --sciper <char>', 'user SCIPER') |
| 33 | + .action(async ({ sciper }) => { |
| 34 | + const enforcer = await initEnforcer(); |
| 35 | + const permissions = [ |
| 36 | + [sciper, 'roles', 'add'], |
| 37 | + [sciper, 'roles', 'list'], |
| 38 | + [sciper, 'roles', 'remove'], |
| 39 | + [sciper, 'proxies', 'post'], |
| 40 | + [sciper, 'proxies', 'put'], |
| 41 | + [sciper, 'proxies', 'delete'], |
| 42 | + [sciper, 'election', 'create'], |
| 43 | + ]; |
| 44 | + await enforcer.addPolicies(permissions); |
| 45 | + console.log('Successfully imported permissions for user!'); |
| 46 | + }); |
| 47 | + |
| 48 | +program |
| 49 | + .command('listUserPermissions') |
| 50 | + .description('Lists the permissions -if any- of the owner of a given SCIPER') |
| 51 | + .requiredOption('-s, --sciper <char>', 'user SCIPER') |
| 52 | + .action(async ({ sciper }) => { |
| 53 | + const enforcer = await initEnforcer(); |
| 54 | + const userPermissions = await enforcer.getPermissionsForUser(sciper); |
| 55 | + console.log(userPermissions); |
| 56 | + }); |
| 57 | + |
| 58 | +program |
| 59 | + .command('removeAdmin') |
| 60 | + .description('Given a SCIPER number, the owner would lose all admin privileges -if any-') |
| 61 | + .requiredOption('-s, --sciper <char>', 'user SCIPER') |
| 62 | + .action(async ({ sciper }) => { |
| 63 | + const enforcer = await initEnforcer(); |
| 64 | + await enforcer.deletePermissionsForUser(sciper); |
| 65 | + console.log('Permissions removed successfully!'); |
| 66 | + }); |
| 67 | + |
| 68 | +program.parse(); |
0 commit comments