GithubHelp home page GithubHelp logo

stalniy / casl-examples Goto Github PK

View Code? Open in Web Editor NEW
99.0 6.0 65.0 967 KB

CASL examples, integration with different frameworks

License: MIT License

JavaScript 25.17% HTML 2.99% CSS 10.82% TypeScript 47.39% Vue 9.99% SCSS 3.64%
casl aurealia angular vue react express example integration

casl-examples's Introduction

CASL Examples

This repository is a monorepo of CASL examples. Examples illustrate integrations with major frameworks. This repository uses pnpm to manage all examples as a monorepo but you are not restricted to use pnpm. If you are interested in particular example, just navigate to its folder and use whatever package manager you like.

You can find examples in packages folder. See README.md of the specific example for details.

Examples

Currently this repository contains the next examples:

Example Description Demo
CASL hello world hello world example to start playing with CASL HelloWorld
CASL React todo user roles in Todo app CASL React Todo
CASL React blog ACL in Blog app with REST API
CASL Angular todo user roles in Todo app
CASL Vue todo user roles in Todo app
CASL Vue blog ACL in Blog app with REST API
CASL Express API ACL in REST API for Blog app
CASL Fastify+Prisma API ACL in REST API for Blog app

Want to contribute?

Want to file a bug, contribute some code, or full example? Excellent! Read up on guidelines for contributing.

License

All examples are published by MIT license

casl-examples's People

Contributors

cantoute avatar mmanishh avatar olena-stotska avatar serhiistotskyi avatar stalniy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

casl-examples's Issues

Typescript Issue.

Hey,

Is there an example which is not in typescript, simple javascript or JSX code (for react example)? I don't know typescript and would like to avoid the hassle to learn it for now.

I am not able to figure out how do I define this..

// Define what abilities different items can have.
const AppAbilities =
    ['read', 'Dashboard'] |
    ['read', 'AdminTools'] |
    ['create' | 'read' | 'update' | 'delete', 'UserInvite']
;

export const AppAbility = Ability(AppAbilities)

Manage abilities already built on backend

I'm building a react app with an express js server.

I correctly implemented CASL on the express js server and I'm trying to integrate casl on the react app.

With the login api I already have the abilities built by the express js server, so I have the following object:

{permissions: { O: {}, g: [{โ€ฆ}], j: {User: {โ€ฆ}}, p: {}, s: false, v: {} } }

How can I integrate this in the react app?

Restricting fields access not working?

Hey,

I want the Admin only be able to update "role" and "active" not other fields.
but it's not working, Admin can update other fields as well. I should mention that other rules works.

so here is my rules:

function defineAdminRules({ can, cannot }, user) {
	can('read', 'User');
	can('update', 'User', ['role', 'active']);
}

and I'm checking it with this in my controller:

ForbiddenError.from(req.ability).throwUnlessCan('update', doc);

Node, Express, Mongo btw.

question about role control

Thank you so much for your nice library. its so powerful I want to know why you dont have a clear way to controlling roles?

Getting `Cannot GET /session` when trying to log into the react blog

Hi,
Probably a user error somehow but trying to get the react blog set up.
I've got the blog-express running (3000) and the db with the example Collection entries.

However, when booting up the react-blog and trying to log in I'm getting this response:
Cannot GET /session

I also get his when trying to access http://localhost:3000/session

Is there something I'm missing, perhaps an Auth set up? Cheers

๐Ÿ“š Add Next.js 13 Example to CASL Documentation

Hi ๐Ÿ‘‹

First of all, thank you for developing such an amazing library. I've been using CASL in my React projects, and now I'm migrating to a Next.js 13 project. While making the switch, I encountered some challenges in defining action & subject for a page/route. Afterwards, retrieving them in my server middleware and using can or some another way to redirect unauthorized or unauthenticated users to appropriate page.

I've gone through the documentation and examples you provided, but unfortunately, I couldn't find any guidance on how to integrate CASL with Next.js 13, particularly with server components and route protection.

I would greatly appreciate it if you could include a comprehensive example demonstrating how to implement CASL with Next.js 13 in the documentation. This addition would make it much smoother for developers like me to integrate CASL into their Next.js projects and benefit from its powerful features.

On a related note, since React now recommends using Next.js for new projects, this is an excellent opportunity to update the docs and replace React with Next.js in the CASL implementation guide. This update will make it more relevant and aligned with the latest trends in the frontend development ecosystem.

Looking forward to the Next.js 13 example and updated documentation!

Best Regards.

Webstorm - Typescript error on the able pipe

Hi there,

first off, thanks for casl, it's a great library. I've noticed that WebStorm 2020.2 complains on the able pipe even on the angular-todo example app.

Screenshot 2021-05-13 at 12 55 02 PM

The application compiles properly, but there seems to be an issue with the typescript checking on the IDE. I would be very much obliged if you could look into it

Prisma / nestjs example

Hello, I am sorry if the question is dumb as I am pretty new here. I am not sure if I have done correctly.

I am using prisma with nestjs, and want to add dynamic permissions using casl. As far as I understand from the docs, json defined rules would be my choice as I want to manage and assign the permissions to users via dashboard.

So according to https://casl.js.org/v5/en/cookbook/roles-with-persisted-permissions, I would choose the second option to build a permission model in prisma like this:

enum Action {
  Manage
  Create
  Update
  Read
  Delete
}

model Permission {
  id         String   @id @default(cuid())
  action     Action
  subject    String
  fields     String[]
  conditions Json?
  inverted   Boolean? @default(false)
  reason     String?
  role       Role     @relation(fields: [roleId], references: [id])
  roleId     String
}

and use prisma's methods to CRUD rules:

permissions.service.ts

 async readPermissions(query: Prisma.PermissionFindManyArgs): Promise<Permission[]> {
        return await this.prisma.permission.findMany(query)
    }

 async createPermission(data: Prisma.PermissionCreateInput): Promise<Permission> {
        return await this.prisma.permission.create({
            data,
        })
    }
...

and need to dynamically generate ability instance with the defined rules for different prisma models.

according to https://docs.nestjs.com/security/authorization#integrating-casl and the above cookbook:

@Injectable()
export class AbilityFactory {
    constructor(private permissionsService: PermissionsService) {}
    async createAbility(modelName: Prisma.ModelName) {
        if (modelName === 'Permission') throw new HttpException('Error', HttpStatus.CONFLICT)

        const subjects = [modelName, 'all']
        const actions = Object.keys(Action)
        type Abilities = [
            typeof actions[number],
            typeof subjects[number] | ForcedSubject<Exclude<typeof subjects[number], 'all'>>,
        ]
        // type AppAbility = Ability<Abilities>

       // get the defined rules(permissions) via prisma
        const permissions = await this.permissionsService.readPermissions({
            where: {
                subject: modelName,
            },
            select: {
                action: true,
                subject: true,
                fields: true,
                conditions: true,
                inverted: true,
                reason: true,
                role: true,
                roleId: true,
            },
        })

        return new Ability<Abilities>(permissions)
    }
}

here when I found the @casl/prisma package, I could barely understand its usage from the docs.

So my question is that, is this correct if I use the @casl/prisma package instead of the above to generate a prisma specific ability instance, and pass the ability to accessibleBy in prisma methods?

the new ability builder would look like this, where the subject type conflicts :

async createPrismaAbility() {
       // need to import all models
        type PrismaModels = Subjects<{
            Address: Address
            Comment: Comment
            Country: Country
            File: File
            ...
            User: User
        }>
        type AppAbility = PrismaAbility<[string, PrismaModels]>

        const AppAbility = PrismaAbility as AbilityClass<AppAbility>

        // return new Ability<AppAbility>(rules)

        const { can, cannot, build } = new AbilityBuilder(AppAbility)
      // get all defined rules
        const permissions = await this.permissionsService.readPermissions({})

        permissions.map((permission) => {
            const { action, subject, fields, conditions } = permission
            if (permission.inverted) {
                return cannot(action, subject, fields, conditions) // Argument of type 'string' is not assignable to parameter of type 'SubjectTypeOf<AppAbility> | SubjectTypeOf<AppAbility>[]
            }
            return can(action, subject, subject, conditions)
        })
        return build()
    }

there are still a lot to do like guard and request context though. So I am wondering if there would be a minimal example. Thank you in advance.

Courses

  • react redux, react mobx, react-native
  • angular ngrx
  • feathersjs, share permissions
  • nestjs, share permissions
  • vuejs + Laravel
  • angular + .NET Core

Svelte example

Hi, I am just getting started with Svelte and was interested in using CASL with it. Is there any plan for an example svelte component?

How to handle advanced rules with json?

I have rules json:

import { createMongoAbility } from '@casl/ability';

export default createMongoAbility([
  {
    action: 'delete',
    subject: 'Post',
    conditions: { published: true }
  }
])

How can I set a condition that checks if authorId === userId?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.