|
| 1 | +/** |
| 2 | + * Copyright (c) 2015 IBM Cloudant, Inc. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file |
| 5 | + * except in compliance with the License. You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software distributed under the |
| 10 | + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, |
| 11 | + * either express or implied. See the License for the specific language governing permissions |
| 12 | + * and limitations under the License. |
| 13 | + */ |
| 14 | + |
| 15 | +// this the the 'cookieauth' request handler. |
| 16 | +// Instead of passing the authentication credentials using HTTP Basic Auth with every request |
| 17 | +// we exchange the credentials for a cookie which we remember and pass back with each |
| 18 | +// subsequent request. |
| 19 | +var async = require('async'); |
| 20 | +var debug = require('debug')('cloudant'); |
| 21 | +var stream = require('stream'); |
| 22 | +var u = require('url'); |
| 23 | +var nullcallback = function() {}; |
| 24 | + |
| 25 | +module.exports = function(options) { |
| 26 | + var requestDefaults = options.requestDefaults || {}; |
| 27 | + var request = require('request').defaults(requestDefaults); |
| 28 | + var jar = request.jar(); |
| 29 | + var cookieRefresh = null; |
| 30 | + |
| 31 | + // make a request using cookie authentication |
| 32 | + // 1) if we have a cookie or have no credentials, just try the request |
| 33 | + // 2) otherwise, get session cookie |
| 34 | + // 3) then try the request |
| 35 | + var cookieRequest = function (req, callback) { |
| 36 | + |
| 37 | + // deal with absence of callback |
| 38 | + if (typeof callback !== 'function') { |
| 39 | + callback = nullcallback; |
| 40 | + } |
| 41 | + |
| 42 | + // parse the url to extract credentials and calculate |
| 43 | + // stuburl - the cloudant url without credentials or auth |
| 44 | + // auth - whether there are credentials or not |
| 45 | + // credentials - object containing username & password |
| 46 | + var url = req.uri || req.url; |
| 47 | + var parsed = u.parse(url); |
| 48 | + var auth = parsed.auth; |
| 49 | + var credentials = null; |
| 50 | + delete parsed.auth; |
| 51 | + delete parsed.href; |
| 52 | + url = u.format(parsed); |
| 53 | + if (auth) { |
| 54 | + var bits = auth.split(':'); |
| 55 | + credentials = { |
| 56 | + username: bits[0], |
| 57 | + password: bits[1] |
| 58 | + }; |
| 59 | + } |
| 60 | + req.url = url; |
| 61 | + delete req.uri; |
| 62 | + delete parsed.path; |
| 63 | + delete parsed.pathname; |
| 64 | + var stuburl = u.format(parsed).replace(/\/$/,''); |
| 65 | + |
| 66 | + // to maintain streaming compatiblity, always return a PassThrough stream |
| 67 | + var s = new stream.PassThrough(); |
| 68 | + |
| 69 | + // run these three things in series |
| 70 | + async.series([ |
| 71 | + |
| 72 | + // call the request being asked for |
| 73 | + function(done) { |
| 74 | + |
| 75 | + // do we have cookie for this domain name? |
| 76 | + var cookies = jar.getCookies(stuburl); |
| 77 | + var statusCode = 500; |
| 78 | + |
| 79 | + // if we have a cookie for this domain, then we can try the required API call straight away |
| 80 | + if (!auth || cookies.length > 0) { |
| 81 | + debug('we have cookies (or no credentials) so attempting API call straight away'); |
| 82 | + req.jar = jar; |
| 83 | + request(req, function(e, h, b) { |
| 84 | + // if we have no credentials or we suceeded |
| 85 | + if (!auth || (statusCode >= 200 && statusCode < 400)) { |
| 86 | + // returning an err of true stops the async sequence |
| 87 | + // we're good because we didn't get a 4** or 5** |
| 88 | + done(true, [e,h,b]); |
| 89 | + } else { |
| 90 | + |
| 91 | + // continue with the async chain |
| 92 | + done(null, [e,h,b]); |
| 93 | + } |
| 94 | + }).on('response', function(r) { |
| 95 | + statusCode = r && r.statusCode || 500; |
| 96 | + }).on('data', function(chunk) { |
| 97 | + // only write to the output stream on success |
| 98 | + if (statusCode < 400) { |
| 99 | + s.write(chunk); |
| 100 | + } |
| 101 | + }); |
| 102 | + |
| 103 | + } else { |
| 104 | + debug('we have no cookies - need to authenticate first'); |
| 105 | + // we have no cookies so we need to authenticate first |
| 106 | + // i.e. do nothing here |
| 107 | + done(null, null); |
| 108 | + } |
| 109 | + |
| 110 | + }, |
| 111 | + |
| 112 | + // call POST /_session to get a cookie |
| 113 | + function(done) { |
| 114 | + debug('need to authenticate - calling POST /_session'); |
| 115 | + var r = { |
| 116 | + url: stuburl + '/_session', |
| 117 | + method: 'post', |
| 118 | + form: { |
| 119 | + name: credentials.username, |
| 120 | + password: credentials.password |
| 121 | + }, |
| 122 | + jar: jar |
| 123 | + }; |
| 124 | + request(r, function(e, h, b) { |
| 125 | + var statusCode = h && h.statusCode || 500; |
| 126 | + // if we sucessfully authenticate |
| 127 | + if (statusCode >= 200 && statusCode < 400) { |
| 128 | + // continue to the next stage of the async chain |
| 129 | + debug('authentication successful'); |
| 130 | + |
| 131 | + // if we don't already have a timer set to refresh the cookie every hour, |
| 132 | + // set one up |
| 133 | + if (!cookieRefresh) { |
| 134 | + debug('setting up recurring cookie refresh request'); |
| 135 | + cookieRefresh = setInterval(function() { |
| 136 | + debug('refreshing cookie'); |
| 137 | + request({method: 'get', url: stuburl + '/_session', jar: jar}); |
| 138 | + }, 1000 * 60 * 60); |
| 139 | + // prevent setInterval from requiring the event loop to be active |
| 140 | + cookieRefresh.unref(); |
| 141 | + } |
| 142 | + |
| 143 | + done(null, [e,h,b]); |
| 144 | + } else { |
| 145 | + // failed to authenticate - no point proceeding any further |
| 146 | + debug('authentication failed'); |
| 147 | + done(true, [e,h,b]); |
| 148 | + } |
| 149 | + }); |
| 150 | + }, |
| 151 | + |
| 152 | + // call the request being asked for with cookie authentication |
| 153 | + function(done) { |
| 154 | + debug('attempting API call with cookie'); |
| 155 | + var statusCode = 500; |
| 156 | + req.jar = jar; |
| 157 | + request(req, function(e, h, b) { |
| 158 | + done(null, [e,h,b]); |
| 159 | + }).on('response', function(r) { |
| 160 | + statusCode = r && r.statusCode || 500; |
| 161 | + }).on('data', function(chunk) { |
| 162 | + if (statusCode < 400) { |
| 163 | + s.write(chunk); |
| 164 | + } |
| 165 | + }); |
| 166 | + } |
| 167 | + ], function(err, data) { |
| 168 | + // callback with the last call we made |
| 169 | + if (data && data.length > 0) { |
| 170 | + var reply = data[data.length - 1]; |
| 171 | + // error, headers, body |
| 172 | + callback(reply[0], reply[1], reply[2]); |
| 173 | + } else { |
| 174 | + callback(err, { statusCode: 500 }, null); |
| 175 | + } |
| 176 | + }); |
| 177 | + |
| 178 | + // return the pass-through stream |
| 179 | + return s; |
| 180 | + }; |
| 181 | + |
| 182 | + |
| 183 | + return cookieRequest; |
| 184 | +}; |
| 185 | + |
0 commit comments