1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
// this module is inspired by xoauth.py
// http://code.google.com/p/google-mail-xoauth-tools/
var crypto = require("crypto");
module.exports.XOAuthGenerator = XOAuthGenerator;
function XOAuthGenerator(options){
this.options = options || {};
}
XOAuthGenerator.prototype.generate = function(callback){
return generateXOAuthStr(this.options, callback);
};
function escapeAndJoin(arr){
return arr.map(encodeURIComponent).join("&");
}
function hmacSha1(str, key){
var hmac = crypto.createHmac("sha1", key);
hmac.update(str);
return hmac.digest("base64");
}
function initOAuthParams(options){
return {
oauth_consumer_key: options.consumerKey || "anonymous",
oauth_nonce: options.nonce || "" + Date.now() + Math.round(Math.random()*1000000),
oauth_signature_method: "HMAC-SHA1",
oauth_version: "1.0",
oauth_timestamp: options.timestamp || "" + Math.round(Date.now()/1000)
};
}
function generateOAuthBaseStr(method, requestUrl, params){
var reqArr = [method, requestUrl].concat(Object.keys(params).sort().map(function(key){
return key + "=" + encodeURIComponent(params[key]);
}).join("&"));
return escapeAndJoin(reqArr);
}
function generateXOAuthStr(options, callback){
options = options || {};
var params = initOAuthParams(options),
requestUrl = options.requestUrl || "https://mail.google.com/mail/b/" + (options.user || "") + "/smtp/",
baseStr, signatureKey, paramsStr, returnStr;
if(options.token){
params.oauth_token = options.token;
}
baseStr = generateOAuthBaseStr(options.method || "GET", requestUrl, params);
signatureKey = escapeAndJoin([options.consumerSecret || "anonymous", options.tokenSecret]);
params.oauth_signature = hmacSha1(baseStr, signatureKey);
paramsStr = Object.keys(params).sort().map(function(key){
return key+"=\""+encodeURIComponent(params[key])+"\"";
}).join(",");
returnStr = [options.method || "GET", requestUrl, paramsStr].join(" ");
if(typeof callback == "function"){
callback(null, new Buffer(returnStr, "utf-8").toString("base64"));
}else{
return new Buffer(returnStr, "utf-8").toString("base64");
}
}
|