egg(38)--后台登录权限判断

/admin需要验证

  1. 用户没有登录跳转到登录页面
  2. 只有登录以后才可以访问后台管理系统
middleware/adminauth.js
const url = require('url')
module.exports = options => {
    return async function adminauth(ctx, next) {
        // 1.用户没有登录跳转到登录页面
        // 2.只有登录以后才可以访问后台管理系统
        var pathname = url.parse(ctx.request.url).pathname;
        console.log(pathname)
        if(ctx.session.userinfo){
            await next();
        }else{
            // 排除不需要做杼判断的页面    admin/verify?mt=0.7755167188853835
            if(pathname == '/admin/login' || pathname == '/admin/doLogin' || pathname == '/admin/verify'){
                await next()
            }else{
                ctx.redirect('/admin/login')
            }
        }

    };
};
config/config.default.js
  config.middleware = ['adminauth'];
  config.adminauth = {
    match:'/admin'
  }

post需要csrf

每一次传给前端的csrf都不一样

middleware/adminauth.js
ctx.state.csrf = ctx.csrf;
login.html
<form action="/admin/doLogin" method="post" id="myform">
    <input type="hidden" name="_csrf" value="<%= csrf%>" >
</form>                            

前台传给后台的数据

controller/login.js
  async doLogin() {
    console.log(this.ctx.request.body)
    await this.success('/admin/login')
  }

clipboard.png