Phân quyền React App với CASL
Phân quyền React App với CASL
1. Giới thiệu
Một số Framework hỗ trợ:
- @casl/vue cho Vue
- @casl/react cho React
- @casl/angular cho Angular 2+
- @casl/aurelia cho Aurelia
2. Cấu hình cho Reactjs
Đọc thêm README.MD nếu chưa thoả mãn https://github.com/stalniy/casl/tree/master/packages/casl-react
Đây cũng có project mẫu cho react: https://github.com/stalniy/casl-react-example
a. Cài đặt packages
1 | npm install @casl/react @casl/ability |
b. Code
Đầu tiên ta cần định nghĩa 2 files là file cấu hình ability.js
và file component Can.js
. Đặt files ở đâu thì tham khảo How to structure React project bởi anh Dan Abramov :).
Can.js
1 | import { createCanBoundTo } from "@casl/react" |
Đây là component để kiểm tra user hiện tại có quyền và hiển thị những thứ mình muốn ra hay không
Ví dụ:
1 | import Can from './Can'; |
ability.js
1 | import { Ability } from "@casl/ability"; |
Trong này chúng ta cần input vào array rules mà user hiện tại có quyền gì cho ability.
1 | ability.update([{"actions":"can","subject":["Shutdown"]}]) |
c. Tích hợp vào project
Như cách giải thích các yêu cầu ở trên thì chúng ta có thể hardcode permissions cho từng role hoặc lấy từ server sau khi login
* Cách 1:
Định nghĩa một function và return và array rules
1 | function defineRulesFor(user) { |
* Cách 2:
Có thể lấy data remote sau khi login và truyền vào ability
1 | import React, { Component } from 'react' |
d. Cách dùng View More:
1 | <Can I="create" a="Post"> |