https://github.com/stackkit/gate
A simple gate class that can help with protecting and checking user abilities.
https://github.com/stackkit/gate
Last synced: 5 months ago
JSON representation
A simple gate class that can help with protecting and checking user abilities.
- Host: GitHub
- URL: https://github.com/stackkit/gate
- Owner: stackkit
- Created: 2020-07-26T13:31:23.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2024-03-15T20:59:43.000Z (over 2 years ago)
- Last Synced: 2025-09-24T19:31:15.278Z (9 months ago)
- Language: JavaScript
- Size: 168 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Gate
> A simple gate class that can help with protecting and checking user capabilities.
## Install
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)
```
npm install @stackkit/gate
yarn add @stackkit/gate
```
## Example
### Define the gate rules
```js
// userGate.js
const { Gate } = require('gate')
function gate({ user }) {
const gate = new Gate({ user })
// run code before checking every other gate
gate.before(({ user }) => {
return user.role === 'god'
})
// define a gate
gate.define('edit-users', ({ user }) => {
return user.role === 'admin'
})
gate.define('edit-post', ({ user, post }) => {
return post.created_by === user.id
})
// run code after done checking every other gate
gate.after(({ user }) => {
return user.namespaces.length > 0
})
return gate
}
module.exports = {
gate
}
```
### Using the gate rules
```js
// your request handler
const { gate } = require('./gates/userGate')
function handleRequest(req) {
const gate = useGate({ user })
if (gate.allows('edit-users')) {
console.log('user is allowed to edit users')
}
const post = prisma.findFirst({ where: { id: req.params.id } })
if(gate.check('edit-post', { post })) {
console.log('user is allowed to edit the given post')
}
}
```