04-proxy.js 1.4 KB
//代理RESTful API
var express = require('express');
exports = module.exports = function (settings, proxy, logger) {

    var app = this;
    var router = express.Router();
    var checkAuth = function (req) {
        var flag = true, ignore = false;
        if (settings.proxy && settings.proxy.ignoreRouters) {
            settings.proxy.ignoreRouters.map(function (ignoreR, i) {
                ignore = req.originalUrl.indexOf(ignoreR) != -1;
            });
        }
        if (ignore) {
            flag = true
        } else if (req.session && req.session.token) {
            var token = {};
            try {
                token = JSON.parse(req.session.token);
            } catch (error) {
                flag = false;
                logger.error("token 字符串不能被解析", error);
            }
            if (token && token.access_token && token.refresh_token)
                flag = true;
        } else {
            logger.debug("token 不存在");
            flag = false;
        }
        return flag;
    }

    if (settings.proxy) {
        app.use(settings.proxy.apiRouteRegexp, router);
        router.all('*', function (req, res, next) {
            if (checkAuth(req))
                proxy.web(req, res, next);
            else
                res.redirect(settings.proxy.signInUrl);
        });
    }
};

exports['@require'] = ['igloo/settings', 'igloo/restler', 'igloo/logger'];