5 ohauth.qsString = function(obj) {
6 return Object.keys(obj).sort().map(function(key) {
7 return encodeURIComponent(key) + '=' +
8 encodeURIComponent(obj[key]);
14 ohauth.stringQs = function(str) {
15 return str.split('&').reduce(function(obj, pair){
16 var parts = pair.split('=');
17 obj[parts[0]] = (null === parts[1]) ?
18 '' : decodeURIComponent(parts[1]);
23 ohauth.rawxhr = function(method, url, data, headers, callback) {
24 var xhr = new XMLHttpRequest(), twoHundred = /^20\d$/;
25 xhr.onreadystatechange = function() {
26 if (4 == xhr.readyState && 0 !== xhr.status) {
27 if (twoHundred.test(xhr.status)) callback(null, xhr);
28 else return callback(xhr, null);
31 xhr.onerror = function(e) { return callback(e, null); };
32 xhr.open(method, url, true);
33 for (var h in headers) xhr.setRequestHeader(h, headers[h]);
37 ohauth.xhr = function(method, url, auth, data, options, callback) {
38 var headers = (options && options.header) || {
39 'Content-Type': 'application/x-www-form-urlencoded'
41 headers.Authorization = 'OAuth ' + ohauth.authHeader(auth);
42 ohauth.rawxhr(method, url, auth, data, headers, callback);
45 ohauth.nonce = function() {
46 for (var o = ''; o.length < 6;) {
47 o += '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'[Math.floor(Math.random() * 61)];
52 ohauth.authHeader = function(obj) {
53 return Object.keys(obj).sort().map(function(key) {
54 return encodeURIComponent(key) + '="' + encodeURIComponent(obj[key]) + '"';
58 ohauth.timestamp = function() { return ~~((+new Date()) / 1000); };
60 ohauth.percentEncode = function(s) {
61 return encodeURIComponent(s)
62 .replace(/\!/g, '%21').replace(/\'/g, '%27')
63 .replace(/\*/g, '%2A').replace(/\(/g, '%28').replace(/\)/g, '%29');
66 ohauth.baseString = function(method, url, params) {
67 if (params.oauth_signature) delete params.oauth_signature;
70 ohauth.percentEncode(url),
71 ohauth.percentEncode(ohauth.qsString(params))].join('&');
74 ohauth.signature = function(oauth_secret, token_secret, baseString) {
75 return ohauth.sha.b64_hmac_sha1(
76 ohauth.percentEncode(oauth_secret) + '&' +
77 ohauth.percentEncode(token_secret),
81 context.ohauth = ohauth;
83 // export for npm/browserify compatibility
84 if (typeof module !== 'undefined') module.exports = ohauth;