// 登录校验
var co = require('co');
var debug = require('debug')('@gopalroy/test-drive');
var biz = require('@gopalroy/biz-core');

module.exports = {
    checkToken : function(req, res, next){
        co(function*(){
            if(!req.incar) req.incar = {};
            debug("%s %s", req.method, req.originalUrl);
            req.incar.loginStaff = yield biz.Staff.FromTokenG(req.cookies.token);
            next();
        }).catch(function(ex){
            debug(ex.stack);
            res.status(401).send(ex.stack);
        });
    },

    requireSystemAdmin: function(req, res, next){
        if(req.incar && req.incar.loginStaff
            && !req.incar.loginStaff.isDisabled()
            && req.incar.loginStaff.isSystemAdmin()){
            next();
        }
        else{
            res.status(403).send("权限不足");
        }
    },

    requireStaffOrSystemAdmin: function(req, res, next){
        if(req.incar && req.incar.loginStaff
            && !req.incar.loginStaff.isDisabled()
            && (req.incar.loginStaff.isSystemAdmin() || req.incar.loginStaff.s4_id == req.params.tdriveId)){
            next();
        }
        else{
            res.status(403).send("权限不足");
        }
    }
};
