vue + django 的权限控制

用vue做前端页面, Django 提供api, 写了一个后台系统,结合方式是vue打包后的dist目录直接作为Django的静态目录, 这样的好处是不用配置Nginx
具体的做法不在这里写了,记一下遇到的问题,比如权限系统

如果是用Django默认的模板系统,权限系统只需要做一个中间件就行了,在请求到达试图函数之前,验证一下,但是如果是用vue, 请求的页面都是vue的路由,然后通过访问api接口来获取数据,这就相当于,你在浏览器输入的地址, 是静态文件的地址,而不是Django的urls中的地址,而Django默认的做法, 访问静态文件是不通过中间件的,可以看一下这里

还好,vue的router自带钩子函数beforeEach,可以实现同样的效果
在Django端专门写一个api用来检查权限,访问vue的地址时,在beforeEach函数中,先发一遍请求,来验证是否有权限,没有的话就拦截住,返回403页面

beforeEach函数有三个参数,to, from 和 next,  to是即将跳转的路径, from是当前导航正要离开的路经,也就是从哪来, next方法用来结束这个函数

在main.js中检查权限:

 1 router.beforeEach((to, from, next) => {
 2 
 3     if (to.meta.requireAuth) {
 4       if (store.state.username) {
 5         // 路由拦截,请求服务端,查看该用户是否有访问权限
 7         let url = store.state.path +  "api/check_permission";
 8         let data = JSON.stringify({
 9           username: store.state.username,
10           url: to.fullPath
11         });
12         console.log(this);
13         console.log(axios);
14         axios.post(url, data,).then(
15           function (response) {
16             console.log("response", response);
17             let status = response.data.status;
18             console.log("status:", status)
19             if (status == false) {
20               router.push("/console/403")
21             } else if (status == "relogin") {
22               next({
23                 path: '/console/login',
24                 query: {referrer: to.fullPath}
25               })
26             } else {
27               next();
28             }
29           }
30         )
31 
32       } else {
33         next({
34           path: '/console/login',
35           query: {referrer: to.fullPath}
36         })
37       }
38     } else {
39       next();
40     }
41   }

猜你喜欢

转载自www.cnblogs.com/zhang-can/p/9100238.html