From 0adfa65b00dcfb4d538a2bca51b3f52c23aa806d Mon Sep 17 00:00:00 2001 From: dbvcode Date: Wed, 19 Jan 2022 17:27:23 +0200 Subject: [PATCH] Appened typescript version of code --- docs/getting-started.md | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/docs/getting-started.md b/docs/getting-started.md index fc396be..007c3af 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -118,6 +118,52 @@ module.exports = { defineAbilitiesFor }; +``` +Typescript version of the code: + +```js +// src/services/authentication/authentication.abilities.ts +import { createAliasResolver, makeAbilityFromRules } from 'feathers-casl'; +import { AbilityBuilder, Ability } from '@casl/ability'; + +// don't forget this, as `read` is used internally +const resolveAction = createAliasResolver({ + update: 'patch', // define the same rules for update & patch + read: ['get', 'find'], // use 'read' as a equivalent for 'get' & 'find' + delete: 'remove' // use 'delete' or 'remove' +}); + +export const defineRulesFor = (user: any) => { + // also see https://casl.js.org/v5/en/guide/define-rules + const { can, cannot, rules } = new AbilityBuilder(Ability); + + if (user.role && user.role.name === 'SuperAdmin') { + // SuperAdmin can do evil + can('manage', 'all'); + return rules; + } + + if (user.role && user.role.name === 'Admin') { + can('create', 'users'); + } + + can('read', 'users'); + can('update', 'users', { id: user.id }); + cannot('update', 'users', ['roleId'], { id: user.id }); + cannot('delete', 'users', { id: user.id }); + + can('manage', 'tasks', { userId: user.id }); + can('create-multi', 'posts', { userId: user.id }); + + return rules; +}; + +export const defineAbilitiesFor = (user: any) => { + const rules = defineRulesFor(user); + + return makeAbilityFromRules(rules, { resolveAction }); +}; + ``` ### Add abilities to hooks context