forked from ef2k/meteor-ddp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
meteor-ddp-oauth.js
269 lines (234 loc) · 9.52 KB
/
meteor-ddp-oauth.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
Random = {};
//from https://github.com/meteor/meteor/blob/master/packages/random/random.js
(function () {
// see http://baagoe.org/en/wiki/Better_random_numbers_for_javascript
// for a full discussion and Alea implementation.
Random._Alea = function () {
function Mash() {
var n = 0xefc8249d;
var mash = function (data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
mash.version = 'Mash 0.9';
return mash;
}
return (function (args) {
var s0 = 0;
var s1 = 0;
var s2 = 0;
var c = 1;
if (args.length == 0) {
args = [+new Date];
}
var mash = Mash();
s0 = mash(' ');
s1 = mash(' ');
s2 = mash(' ');
for (var i = 0; i < args.length; i++) {
s0 -= mash(args[i]);
if (s0 < 0) {
s0 += 1;
}
s1 -= mash(args[i]);
if (s1 < 0) {
s1 += 1;
}
s2 -= mash(args[i]);
if (s2 < 0) {
s2 += 1;
}
}
mash = null;
var random = function () {
var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
s0 = s1;
s1 = s2;
return s2 = t - (c = t | 0);
};
random.uint32 = function () {
return random() * 0x100000000; // 2^32
};
random.fract53 = function () {
return random() +
(random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
random.version = 'Alea 0.9';
random.args = args;
return random;
}(Array.prototype.slice.call(arguments)));
};
// instantiate RNG. Heuristically collect entropy from various sources
// client sources
var height = (typeof window !== 'undefined' && window.innerHeight) ||
(typeof document !== 'undefined'
&& document.documentElement
&& document.documentElement.clientHeight) ||
(typeof document !== 'undefined'
&& document.body
&& document.body.clientHeight) ||
1;
var width = (typeof window !== 'undefined' && window.innerWidth) ||
(typeof document !== 'undefined'
&& document.documentElement
&& document.documentElement.clientWidth) ||
(typeof document !== 'undefined'
&& document.body
&& document.body.clientWidth) ||
1;
var agent = (typeof navigator !== 'undefined' && navigator.userAgent) || "";
// server sources
var pid = (typeof process !== 'undefined' && process.pid) || 1;
// XXX On the server, use the crypto module (OpenSSL) instead of this PRNG.
// (Make Random.fraction be generated from Random.hexString instead of the
// other way around, and generate Random.hexString from crypto.randomBytes.)
Random.fraction = new Random._Alea([
new Date(), height, width, agent, pid, Math.random()]);
Random.choice = function (arrayOrString) {
var index = Math.floor(Random.fraction() * arrayOrString.length);
if (typeof arrayOrString === "string")
return arrayOrString.substr(index, 1);
else
return arrayOrString[index];
};
var UNMISTAKABLE_CHARS = "23456789ABCDEFGHJKLMNPQRSTWXYZabcdefghijkmnopqrstuvwxyz";
Random.id = function () {
var digits = [];
// Length of 17 preserves around 96 bits of entropy, which is the
// amount of state in our PRNG
for (var i = 0; i < 17; i++) {
digits[i] = Random.choice(UNMISTAKABLE_CHARS);
}
return digits.join("");
};
})();
Oauth = {};
//from https://github.com/meteor/meteor/blob/master/packages/oauth/oauth_client.js
(function () { // Open a popup window pointing to a OAuth handshake page
//
// @param credentialToken {String} The OAuth credentialToken generated by the client
// @param url {String} url to page
// @param credentialRequestCompleteCallback {Function} Callback function to call on
// completion. Takes one argument, credentialToken on success, or Error on
// error.
// @param dimensions {optional Object(width, height)} The dimensions of
// the popup. If not passed defaults to something sane
Oauth.initiateLogin = function (credentialToken, url, credentialRequestCompleteCallback, dimensions) {
// default dimensions that worked well for facebook and google
var popup = openCenteredPopup(
url,
(dimensions && dimensions.width) || 650,
(dimensions && dimensions.height) || 331);
var checkPopupOpen = setInterval(function () {
try {
// Fix for #328 - added a second test criteria (popup.closed === undefined)
// to humour this Android quirk:
// http://code.google.com/p/android/issues/detail?id=21061
var popupClosed = popup.closed || popup.closed === undefined;
} catch (e) {
// For some unknown reason, IE9 (and others?) sometimes (when
// the popup closes too quickly?) throws "SCRIPT16386: No such
// interface supported" when trying to read 'popup.closed'. Try
// again in 100ms.
return;
}
if (popupClosed) {
clearInterval(checkPopupOpen);
credentialRequestCompleteCallback(credentialToken);
}
}, 100);
};
var openCenteredPopup = function (url, width, height) {
var screenX = typeof window.screenX !== 'undefined'
? window.screenX : window.screenLeft;
var screenY = typeof window.screenY !== 'undefined'
? window.screenY : window.screenTop;
var outerWidth = typeof window.outerWidth !== 'undefined'
? window.outerWidth : document.body.clientWidth;
var outerHeight = typeof window.outerHeight !== 'undefined'
? window.outerHeight : (document.body.clientHeight - 22);
// XXX what is the 22?
// Use `outerWidth - width` and `outerHeight - height` for help in
// positioning the popup centered relative to the current window
var left = screenX + (outerWidth - width) / 2;
var top = screenY + (outerHeight - height) / 2;
var features = ('width=' + width + ',height=' + height +
',left=' + left + ',top=' + top);
var newwindow = window.open(url, 'Login', features);
if (newwindow.focus)
newwindow.focus();
return newwindow;
};
}).call(this);
//@param {function(string):string} oauthLoginUrl Given the credentialToken as a parameter and
//should return the oauthLoginUrl
MeteorDdp.prototype.loginWithOauth = function (oauthLoginUrl) {
var self = this;
self.oauthLoginUrl = oauthLoginUrl;
//if there is a login token try to resume the session
var loginToken = localStorage.getItem(self._loginTokenKey);
if (loginToken)
return self._resumeSession(loginToken);
else
return self.oauthPrompt();
};
MeteorDdp.prototype._loginTokenKey = "Meteor.loginToken";
MeteorDdp.prototype.oauthPrompt = function (timeoutInSeconds) {
//default timeout to 60 seconds
timeoutInSeconds = timeoutInSeconds ? timeoutInSeconds : 60;
var def = $.Deferred(),
credentialToken = Random.id(),
self = this,
attempts,
error;
//we cannot trust the credentialRequestCompleteCallback callback because if
//the window gets redirected the window reference will become null and the callback will be triggered
//even though this could be before the user authenticated
//so let's try every second until the timeout to login and then consider the login failed
var tryLoginInterval = setInterval(function () {
attempts++;
//after the login popup closes attempt to login
self.call("login", [
{ oauth: { credentialToken: credentialToken }}
])
.done(function (data) {
//if we were successful logging in with the credential token then store it
localStorage.setItem(self._loginTokenKey, data.token);
def.resolve();
clearInterval(tryLoginInterval);
})
.fail(function (data) {
error = data;
});
if (attempts > timeoutInSeconds) {
def.reject(error);
clearInterval(tryLoginInterval);
}
}, 1000);
Oauth.initiateLogin(credentialToken, self.oauthLoginUrl(credentialToken), function () {
}, {width: 900, height: 450});
return def.promise();
};
MeteorDdp.prototype.logout = function () {
localStorage.removeItem(this._loginTokenKey);
return this.call("logout");
};
MeteorDdp.prototype._resumeSession = function (loginToken) {
var self = this;
return self.call("login", [
{ resume: loginToken }
])
.fail(function () {
return self.oauthPrompt();
});
};