Adonis User Policy (Authorization).
This is a trait wich addscan
andcanNot
methods to User Model (or other class π)
π Homepage
adonis install @mikield/adonis-user-policy
This package relies on https://github.com/mikield/adonis-true-traits which is included when installing the user policy package. You need to register its provider in start/app.js
const providers = [
...,
'@mikield/adonis-true-traits'
]
'use strict'
const Model = use('Model')
const PolicyTrait = use('@mikield/adonis-user-policy')
class User extends Model {
...
}
module.exports = mix(User).with(PolicyTrait)
If you want to create user related policy checks, for example user.can('createPosts')
β then, for example:
'use strcit'
class User {
static createPosts(user) {
return !user.roles.contains('create-post') //We can check a user role for example
}
}
module.exports = Post
'use strict'
const Model = use('Model')
const PolicyTrait = use('@mikield/adonis-user-policy')
class User extends Model {
//User policy
static get policy(){
return 'App/Policies/User'
}
}
module.exports = mix(User).with(PolicyTrait)
'use strcit'
class Post {
static add(user, post) { //In this case the post will be a class and not a instance
return !user.banned //User can create a Post if it is not banned
}
static edit(user, post){ //In this case the post will be a instance and not a class
return post.owner.id === user.id //Only the owner of the post can edit the post
}
}
module.exports = Post
'use strict'
const Model = use('Model')
class Post extends Model {
//Post policy
static get policy(){
return 'App/Policies/Post'
}
}
module.exports = Post
const User = use('App/Models/User')
Route.get('/test-user-policy', async () => {
const user = await User.find(1)
if(user.can('createPost')) {
...
}
if(user.canNot('createPost')) {
...
}
})
const User = use('App/Models/User')
const Post = use('App/Models/Post')
Route.get('/test-user-policy', async () => {
const user = await User.find(1)
if(user.can('add', Post)){
...
}
if(user.canNot('add', Post)){
...
}
})
const User = use('App/Models/User')
const Post = use('App/Models/Post')
Route.get('/test-user-policy', async () => {
const user = await User.find(1)
const post = await Post.find(1)
if(user.can('edit', post)) {
...
}
if(user.canNot('edit', post)) {
...
}
})
π€ Vladyslav Gaysyuk
- Website: https://mikield.rocks
- Twitter: @AdmiralMiki
- Github: @mikield
- LinkedIn: @mikield
Contributions, issues and feature requests are welcome!
Feel free to check issues page. You can also take a look at the contributing guide.
Give a βοΈ if this project helped you!
Copyright Β© 2020 Vladyslav Gaysyuk.
This project is MIT licensed.
This README was generated with β€οΈ by readme-md-generator