示例#1
0
文件: session.js 项目: rainjs/rainjs
Session.prototype.handle = function (request, response, next) {
    var self = this;

    if (request.globalSession || !this._needsSession(request)) {
        next();
        return;
    }

    request.sessionStore = this._store;
    request.sessionId = request.signedCookies[this._key];

    var pause = utils.pause(request);

    this._ensureSession(request).then(function () {
        next();
        pause.resume();
    }, function (error) {
        next(error);
        pause.resume();
    });

    response.on('header', function () {
        self._setCookie(request, response);
    });

    this._decorateEnd(request, response);
};
示例#2
0
        function rewrite(req, res, next) {
            var location = {pathname: parse(req).pathname},
                hasListener = _rewritePaths[pathKey] && _rewritePaths[pathKey][location.pathname],
                requestId = _filterRequestCounter++,
                timeoutId;

            // ignore most HTTP methods and files that we're not watching
            if (("GET" !== req.method && "HEAD" !== req.method) || !hasListener) {
                next();
                return;
            }

            // pause the request and wait for listeners to possibly respond
            var pause = utils.pause(req);

            function resume(doNext) {
                // delete the callback after it's used or we hit the timeout.
                // if this path is requested again, a new callback is generated.
                delete _requests[pathKey][requestId];

                // pass request to next middleware
                if (doNext) {
                    next();
                }

                pause.resume();
            }

            // map request pathname to response callback
            _requests[pathKey][requestId] = function (resData) {
                // clear timeout immediately when this callback is called
                clearTimeout(timeoutId);

                // response data is optional
                if (resData.body) {
                    // HTTP headers
                    var type    = mime.lookup(location.pathname),
                        charset = mime.charsets.lookup(type);

                    res.setHeader("Content-Type", type + (charset ? "; charset=" + charset : ""));

                    // TODO (jasonsanjose): off-by-1 error here, why?
                    // Chrome seems to handle the request without issues when Content-Length is not specified
                    //res.setHeader("Content-Length", Buffer.byteLength(resData.body /* TODO encoding? */));

                    // response body
                    res.end(resData.body);
                }

                // resume the HTTP ServerResponse, pass to next middleware if
                // no response data was passed
                resume(!resData.body);
            };

            location.hostname = address.address;
            location.port = address.port;
            location.root = path;

            var request = {
                headers:    req.headers,
                location:   location,
                id:         requestId
            };

            // dispatch request event
            _domainManager.emitEvent("staticServer", "requestFilter", [request]);

            // set a timeout if custom responses are not returned
            timeoutId = setTimeout(function () { resume(true); }, _filterRequestTimeout);
        }
示例#3
0
Session.prototype.handle = function (request, response, next) {
    var self = instance;

    // self-awareness
    if (request.session) {
        return next();
    }

    // Retrieve the session only for views and server-side controllers.
    if (request.rainRoute && SESSION_ROUTES.indexOf(request.rainRoute.routeName) === -1) {
        return next();
    }

    request.sessionStore = self._store;

    // Set-cookie.
    response.on('header', function () {
        if (!request.session) {
            return;
        }

        var cookie = request.session.cookie,
            proto = (request.headers['x-forwarded-proto'] || '').toLowerCase(),
            tls = request.connection.encrypted || (self._trustProxy && 'https' == proto),
            secured = cookie.secure && tls;

        // Browser-session cookies only set-cookie once.
        if (cookie.expires === null && !request.sessionIsNew) {
            return;
        }

        // Only send secure cookies via https.
        if (cookie.secure && !secured) {
            return;
        }

        var val = cookie.serialize(self._key, request.sessionId);
        response.setHeader('Set-Cookie', val);
    });

    // Proxy end() to commit the session.
    var end = response.end;
    response.end = function (data, encoding) {
        response.end = end;

        if (!request.session) {
            return response.end(data, encoding);
        }

        self._store.save(request.session, function () {
            response.end(data, encoding);
        });
    };

    // Generate the session.
    function generate(next) {
        self._store.createNewSession(request, next);
    }

    // Get the sessionId from the cookie.
    request.sessionId = request.signedCookies[self._key];

    // Generate a session if the browser doesn't send a sessionId.
    if (!request.sessionId) {
        generate(next);
        return;
    }

    // Generate the session object.
    var pause = utils.pause(request);
    self._store.get(request, function (err, sess) {
        // Proxy to resume() events.
        var _next = next;
        next = function (err) {
            _next(err);
            pause.resume();
        };

        if (err) {
            next(err);
        } else {
            next();
        }
    });
};
示例#4
0
app.use(function(req, res, next) {
    var send = require('send'),
        utils = require('connect/lib/utils'),
        parse = utils.parseUrl,
        url = require('url');

    options = {};
    var found = false;
    //if  url contains static_extensions it will be static request
    for (ex in configuration.static_extensions) {
        if (req.url.indexOf(configuration.static_extensions[ex]) != -1) {
            found = true;
            break;
        }
    }
    //extension not found
    if (!found) {
        //overriding headers
        for(i in configuration.override_headers){
            req.headers[i]=configuration.override_headers[i];
        }
        //concatenating headers
        for(i in configuration.concat_headers){
            req.headers[i]+=configuration.concat_headers[i];
        }
        console.log("[-- rest service: " + req.url + " --]");
        //doing a rest service call to proxy server
        proxy.proxyRequest(req, res, configuration.serverProxy);
    } else {
        // extension found
        // logic to static request
        if ('GET' != req.method && 'HEAD' != req.method) return next();
        var originalUrl = url.parse(req.originalUrl);
        var path = parse(req).pathname;
        var pause = utils.pause(req);

        if (path == '/' && originalUrl.pathname[originalUrl.pathname.length - 1] != '/') {
            return directory();
        }

        function resume() {
            next();
            pause.resume();
        }

        function directory() {
            if (!redirect) return resume();
            var target;
            originalUrl.pathname += '/';
            target = url.format(originalUrl);
            res.statusCode = 303;
            res.setHeader('Location', target);
            res.end('Redirecting to ' + utils.escape(target));
        }

        function error(err) {
            if (404 == err.status) {
                return resume();
            }
            next(err);
        }

        send(req, path)
            .maxage(options.maxAge || 0)
            .root(configuration.static_dir)
            .index(options.index || 'index.html')
            .hidden(options.hidden)
            .on('error', error)
            .on('directory', directory)
            .pipe(res);
    }
}).listen(configuration.static_content_port);