|
1 | 1 | # Gate |
2 | 2 |
|
3 | | -> A simple gate class that can help with protecting and checking user abilities. |
| 3 | +> A simple gate class that can help with protecting and checking user capabilities. |
4 | 4 |
|
5 | | -**This package is made to run in Nodejs because checking the gate access should be done in the backend but it can be used on the client side. For example to show or hide ui elements or protect client side routes** |
| 5 | +## Install |
| 6 | + |
| 7 | +This package is made to run in your backend because checking the gate access should be done in the backend. But it can be used on the client side. For example to show or hide ui elements or protect client side routes. It is based on the gate functionality in [Laravel](https://laravel.com/docs/8.x/authorization#gates) |
| 8 | + |
| 9 | +``` |
| 10 | +npm install @stackkit/gate |
| 11 | +yarn add @stackkit/gate |
| 12 | +``` |
| 13 | + |
| 14 | +## Example |
6 | 15 |
|
7 | 16 | ### Define the gate rules |
8 | 17 | ```js |
9 | | -import { Gate } from 'gate' |
| 18 | +// userGate.js |
10 | 19 |
|
11 | | -const user = { id: 1, role: 'admin' } |
| 20 | +const { Gate } = require('gate') |
12 | 21 |
|
13 | | -export function useGate({ user }) { |
| 22 | +function gate({ user }) { |
14 | 23 | const gate = new Gate({ user }) |
15 | | - |
| 24 | + |
| 25 | + // run code before checking every other gate |
16 | 26 | gate.before(({ user }) => { |
17 | 27 | return user.role === 'god' |
18 | 28 | }) |
19 | 29 |
|
| 30 | + // define a gate |
20 | 31 | gate.define('edit-users', ({ user }) => { |
21 | 32 | return user.role === 'admin' |
22 | 33 | }) |
23 | 34 |
|
24 | 35 | gate.define('edit-post', ({ user, post }) => { |
25 | | - return post.user_id === user.id |
| 36 | + return post.created_by === user.id |
| 37 | + }) |
| 38 | + |
| 39 | + // run code after done checking every other gate |
| 40 | + gate.after(({ user }) => { |
| 41 | + return user.namespaces.length > 0 |
26 | 42 | }) |
27 | 43 |
|
28 | 44 | return gate |
29 | 45 | } |
| 46 | + |
| 47 | +module.exports = { |
| 48 | + gate |
| 49 | +} |
30 | 50 | ``` |
31 | 51 |
|
32 | | -### Use the gate rules |
| 52 | +### Using the gate rules |
33 | 53 | ```js |
34 | | -import { useGate } from 'domain/gate' |
| 54 | +// your request handler |
| 55 | + |
| 56 | +const { gate } = require('./gates/userGate') |
35 | 57 |
|
36 | | -const gate = useGate({ user }) |
| 58 | +function handleRequest(req) { |
| 59 | + const gate = useGate({ user }) |
37 | 60 |
|
38 | | -gate.allows('edit-users') |
| 61 | + if (gate.allows('edit-users')) { |
| 62 | + console.log('user is allowed to edit users') |
| 63 | + } |
39 | 64 |
|
40 | | -const post = db.get('post') |
41 | | -gate.check('edit-post', { post }) |
| 65 | + const post = prisma.findFirst({ where: { id: req.params.id } }) |
| 66 | + if(gate.check('edit-post', { post })) { |
| 67 | + console.log('user is allowed to edit the given post') |
| 68 | + } |
| 69 | +} |
42 | 70 | ``` |
0 commit comments