AdonisJS框架的用户策略特征(支持可以并且可以不是用户模型的方法)
Adonis User Policy (Authorization).
This is a trait wich addscan
andcanNot
methods to User Model (or other class)
adonis install @mikield/adonis-user-policy
start/app.js
const providers = [
...,
'@mikield/adonis-true-traits'
]
User
model class with a PolicyTrait
class
'use strict'
const Model = use('Model')
const PolicyTrait = use('@mikield/adonis-user-policy')
class User extends Model {
...
}
module.exports = mix(User).with(PolicyTrait)
user.can('createPosts')
— then, for example:User.js
under app\Policies
folder.
'use strcit'
class User {
static createPosts(user) {
return !user.roles.contains('create-post') //We can check a user role for example
}
}
module.exports = Post
User
model.
'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)
Post.js
under app\Policies
folder.
'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
Post
model.
'use strict'
const Model = use('Model')
class Post extends Model {
//Post policy
static get policy(){
return 'App/Policies/Post'
}
}
module.exports = Post
can
or canNot
function.Post
model.
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')) {
...
}
})
Post
model.
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)){
...
}
})
Post
instance (existing Post object).
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
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