Skip to content

Commit 3242d06

Browse files
committed
Update readme
1 parent 5a1b4c2 commit 3242d06

File tree

1 file changed

+41
-13
lines changed

1 file changed

+41
-13
lines changed

README.md

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,70 @@
11
# Gate
22

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.
44
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
615

716
### Define the gate rules
817
```js
9-
import { Gate } from 'gate'
18+
// userGate.js
1019

11-
const user = { id: 1, role: 'admin' }
20+
const { Gate } = require('gate')
1221

13-
export function useGate({ user }) {
22+
function gate({ user }) {
1423
const gate = new Gate({ user })
15-
24+
25+
// run code before checking every other gate
1626
gate.before(({ user }) => {
1727
return user.role === 'god'
1828
})
1929

30+
// define a gate
2031
gate.define('edit-users', ({ user }) => {
2132
return user.role === 'admin'
2233
})
2334

2435
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
2642
})
2743

2844
return gate
2945
}
46+
47+
module.exports = {
48+
gate
49+
}
3050
```
3151

32-
### Use the gate rules
52+
### Using the gate rules
3353
```js
34-
import { useGate } from 'domain/gate'
54+
// your request handler
55+
56+
const { gate } = require('./gates/userGate')
3557

36-
const gate = useGate({ user })
58+
function handleRequest(req) {
59+
const gate = useGate({ user })
3760

38-
gate.allows('edit-users')
61+
if (gate.allows('edit-users')) {
62+
console.log('user is allowed to edit users')
63+
}
3964

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+
}
4270
```

0 commit comments

Comments
 (0)