importaxiosfrom'axios';
exportdefault{
props:['post','username'],
methods:{
del(){
if(this.$can('delete',this.post)){
...
}else{
this.$emit('err','Only the owner of a post can delete it!');
}
}
}
}
當用戶單擊“ 刪除”按鈕時,將捕獲點擊並del調用處理程序方法。
然後我們使用CASL來檢查當前用戶是否有權通過此操作this.$can('delete', post)。如果他們有權限,我們可以採取一些行動。如果沒有,則會顯示錯誤消息“只有帖子的所有者才能刪除它!”。
服務器端測試
在實際的應用程序中,在用戶刪除前端的帖子後,我們會使用AJAX將刪除指令發送給API,例如:
src/components/Post.vue
if(this.$can('delete',post)){
axios.get(`/delete/${post.id}`, ).then(res => {...
});}
然後我們將CASL測試邏輯放在服務器上,因為服務器不應該信任來自客戶端的CRUD操作:
server.js
app.get("/delete/:id",(req,res)=>{
letpostId=parseInt(req.params.id);
letpost=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});
}});
由於CASL是同構的,ability服務器上的對象可以從abilities.js中導入,從而使我們不必複製任何代碼!
總結
有了這個,我們有一個非常好的方式來管理一個簡單的Vue應用程序中的用戶權限。
我相信this.$can('delete', post)比以下更優雅:
if(user.id===post.user&&post.type==='Post'){
...}
這不僅更難以閱讀,而且還有一個隱含規則,即用戶可以刪除帖子。這個規則無疑會在我們的應用程序的其他地方使用,並且應該被抽象化。這是CASL能為我們做的。
閱讀更多 空空教你玩黑客 的文章