80.权限重构
- 本系列文章为
laracasts.com
的系列视频教程——Let's Build A Forum with Laravel and TDD 的学习笔记。若喜欢该系列视频,可去该网站订阅后下载该系列视频, 支持正版 ;- 视频源码地址:github.com/laracasts/Lets-Build-a-...;
- 本项目为一个 forum(论坛)项目,与本站的第二本实战教程 《Laravel 教程 - Web 开发实战进阶》 类似,可互相参照。
本节说明
- 对应视频教程第 80 小节:Refactoring Authorization
本节内容
我们认为Best Reply
按钮的权限只有话题的创建者才拥有,但是Best Reply
按钮显示在Reply
组件中。所以本节我们对页面的权限做些重构,以便更方便地进行功能的开发。首先我们新建控制权限的辅助方法:
forum\resources\assets\js\authorizations.js
let user = window.App.user;
module.exports = {
updateReply (reply) {
return reply.user_id === user.id;
}
};
然后我们使用它:
forum\resources\assets\js\bootstrap.js
.
.
window.Vue = require('vue');
let authorizations = require('./authorizations');
Vue.prototype.authorize = function (...params) {
if (! window.App.signedIn) return false;
if (typeof params[0] === 'string') {
return authorizations[params[0]](params[1]);
}
return params[0](window.App.user);
};
Vue.prototype.signedIn = window.App.signedIn;
.
.
由于signedIn
在多个地方用到,所以在这里我们将其注册为全局变量。
注:在
app.blade.php
和NewReply.vue
两个文件中,使用的是signIn
,要修改为signedIn
。
然后我们就可以修改权限控制的地方:
forum\resources\assets\js\components\Reply.vue
<template>
.
.
<div class="panel-footer level">
<div v-if="authorize('updateReply',reply)">
<button class="btn btn-xs mr-1" @click="editReply">Edit</button>
<button class="btn btn-xs btn-danger mr-1" @click="destroy">Delete</button>
</div>
<button class="btn btn-xs btn-default ml-a" @click="markBestReply" v-show="! isBest">Best Reply</button>
</div>
</div>
</template>
<script>
.
.
data() {
return {
editing: false,
id: this.data.id,
body: this.data.body,
isBest: false,
reply: this.data
};
},
.
.
computed: {
ago() {
return moment(this.data.created_at).fromNow() + '...';
}
},
.
.
</script>
去掉NewReply.vue
的computed
,因为我们已经全局注册了signedIn
。我们在下一节继续开发最佳回复的功能。