src/main.js
import Vue from 'vue';
import abilitiesPlugin from './ability-plugin';
const defineAbilitiesFor = require('../resources/ability');
let user = { id: 1, name: 'George' };
let ability = defineAbilitiesFor(user.id);
Vue.use(abilitiesPlugin, ability);
Post 实例
我们的应用会使用分类广告的帖子。这些表述帖子的对象会从数据库中检索,然后被服务器传给前端。比如:
我们的Post实例中有两个属性是必须的:
type属性。CASL会使用 abilities.js中的subjectName回调来检查正在测试的是哪种实例。
user属性。这是发帖者。记住,用户只能更新和删除他们发布的帖子。在 main.js中我们通过defineAbilitiesFor(user.id)已经告诉了CASL当前用户是谁。CASL要做的就是检查用户的ID和user属性是否匹配。
let posts = [
{
type: 'Post',
user: 1,
content: '1 used cat, good condition'
},
{
type: 'Post',
user: 2,
content: 'Second-hand bathroom wallpaper'
}
];
这两个post对象中,ID为1的George,拥有第一个帖子的更新删除权限,但没有第二个的。
在对象中测试用户权限
帖子通过Post组件在应用中展示。先看一下代码,下面我会讲解:
src/components/Post.vue
<template>
<div>
<div>
<br /><small>posted by </small>
</div>
<button @click="del">Delete</button>
</div>
</template>
<script> import axios from 'axios';
export default {
props: ['post', 'username'],
methods: {
del() {
if (this.$can('delete', this.post)) {
...
} else {
this.$emit('err', 'Only the owner of a post can delete it!');
}
}
}
} </script>
<style lang="scss">...</style>
点击Delete按钮,捕获到点击事件,会调用del处理函数。
我们通过this.$can('delete', post)来使用CASL检查当前用户是否具有操作权限。如果有权限,就进一步操作,如果没有,就给出错误提示“只有发布者可以删除!”
服务器端测试
在真实项目里,用户在前端删除后,我们会通过 Ajax发送删除指令到接口,比如:
src/components/Post.vue
if (this.$can('delete', post)) {
axios.get(`/delete/${post.id}`, ).then(res => {
...
});
}
服务器不应信任客户端的CRUD操作,那我们把CASL测试逻辑放到服务器:
server.js
app.get("/delete/:id", (req, res) => {
let postId = parseInt(req.params.id);
let post = posts.find(post => post.id === postId);
if (ability.can('delete', post)) {
posts = posts.filter(cur => cur !== post);
res.json({ success: true });
} else {
res.json({ success: false });
}
});
内容版权声明:除非注明,否则皆为本站原创文章。
