· 8 years ago · Feb 04, 2017, 11:34 PM
1'use strict';
2
3import Promise from 'bluebird';
4import getUrlParameter from 'getUrlParameter';
5
6const getCurrentUrl = Symbol('getCurrentUrl');
7const isOauthResponseAvailable = Symbol('isOauthResponseAvailable');
8const getOauthResponse = Symbol('getOauthResponse');
9const observeUrlChanges = Symbol('observeUrlChanges');
10
11
12class TwitterAuthorization {
13 constructor() {
14 this.windowHandler = null;
15 this.windowName = 'twitterAuthorize';
16 this.authorizationUrl = '/twitter/authorize';
17 this.windowOptions = 'width=548,height=325';
18 this.oAuthResponsePromiseResolveFunction = null;
19 this.oAuthResponsePromiseRejectFunction = null;
20
21 this.oAuthResponsePromise = new Promise((resolve, reject) => {
22 this.oAuthResponsePromiseResolveFunction = resolve;
23 this.oAuthResponsePromiseRejectFunction = reject;
24 });
25 }
26
27 authorize() {
28 this.windowHandler = window.open(this.authorizationUrl, this.windowName, this.windowOptions);
29 this[observeUrlChanges]();
30
31 return this.oAuthResponsePromise;
32 }
33
34 [observeUrlChanges]() {
35 if (this[isOauthResponseAvailable]()) {
36 this.oAuthResponsePromiseResolveFunction(this[getOauthResponse]());
37 this.windowHandler.close();
38 }
39
40 if (!this.windowHandler || this.windowHandler.closed) {
41 this.oAuthResponsePromiseRejectFunction();
42
43 return;
44 }
45
46 setTimeout(this[observeUrlChanges].bind(this), 1000);
47 }
48
49 [getCurrentUrl]() {
50 if (!this.windowHandler || !this.windowHandler.location) {
51 return '';
52 }
53
54 try {
55 return this.windowHandler.location.href || '';
56 } catch (error) {
57 return '';
58 }
59 }
60
61 [isOauthResponseAvailable]() {
62 const currentUrl = this[getCurrentUrl]();
63
64 return currentUrl.indexOf('oauth_verifier') !== -1;
65 }
66
67 [getOauthResponse]() {
68 const currentUrl = this[getCurrentUrl]();
69
70 return {
71 token: getUrlParameter(currentUrl, 'oauth_token'),
72 verifier: getUrlParameter(currentUrl, 'oauth_verifier'),
73 };
74 }
75}
76
77module.exports = TwitterAuthorization;