通過使用CASL非常簡單的管理Vue.js前端伺服器應用程式用戶權限

  • 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,例如:

    1. src/components/Post.vue

    2. if(this.$can('delete',post)){

    3. axios.get(`/delete/${post.id}`, ).then(res => {...

    4. });}

    然後我們將CASL測試邏輯放在服務器上,因為服務器不應該信任來自客戶端的CRUD操作:

    1. server.js

    2. app.get("/delete/:id",(req,res)=>{

    3. letpostId=parseInt(req.params.id);

    4. letpost=posts.find(post=>post.id===postId);

    5. if(ability.can('delete',post)){

    6. posts=posts.filter(cur=>cur!==post);

    7. res.json({success:true});

    8. }else{

    9. res.json({success:false});

    10. }});

    由於CASL是同構的,ability服務器上的對象可以從abilities.js中導入,從而使我們不必複製任何代碼!

    總結

    有了這個,我們有一個非常好的方式來管理一個簡單的Vue應用程序中的用戶權限。

    我相信this.$can('delete', post)比以下更優雅:

    1. if(user.id===post.user&&post.type==='Post'){

    2. ...}

    這不僅更難以閱讀,而且還有一個隱含規則,即用戶可以刪除帖子。這個規則無疑會在我們的應用程序的其他地方使用,並且應該被抽象化。這是CASL能為我們做的。


    分享到:


    相關文章: