slouch/scripts/request-wrapper.js
Jeffrey Layanto f23c3b26ca Fix cookie authentication in node and browser (#108)
* Pass slouch in when instantiating EnhancedRequest

This is to allow EnhanceRequest to access slouch._requestWrapper.setCookie

* Update locally stored cookie when response has set-cookie header

* Delete unused this._cookie

* Fix cookie-authentication in browser

* Fix test

Request header now always include withCredentials: true

* Fix test

EnhancedRequest constructor now requires instance of Slouch

* Typo

* Fix test

* Remove TODO comment and clean up redundant code

* Revert change to user.js

* Fix user test spec

* Fix user test spec

* Fix browser coverage test fail

* FIx beautify test fail

* Fix failed jshint test
2019-03-21 19:55:59 -07:00

35 lines
1.1 KiB
JavaScript

'use strict';
var request = require('request');
// A construct used to associate a cookie with a request. We include the cookie at this layer so
// that we have a single place to modify later when we migrate to using fetch instead of request.
//
// TODO: when EnhancedRequest is used in quelle then we should be able to move the logic from
// RequestWrapper into EnhancedRequest and remove RequestWrapper.
var RequestWrapper = function () {};
RequestWrapper.prototype._setCookieHeader = function (opts) {
if ((!opts.headers || !opts.headers.cookie) && this._cookie) {
if (!opts.headers) {
opts.headers = {};
}
opts.headers.cookie = this._cookie;
}
opts.withCredentials = true; // Needed for cookie-authentication to work in browser
return opts;
};
RequestWrapper.prototype.requestFactory = function () {
var self = this;
return function (opts) {
arguments[0] = self._setCookieHeader(opts);
return request.apply(request, arguments);
};
};
RequestWrapper.prototype.setCookie = function (cookie) {
this._cookie = cookie;
};
module.exports = RequestWrapper;