· 6 years ago · Jun 08, 2019, 12:12 PM
1// authorization code and tokens
2authorizationCode: string;
3oAuthToken: string;
4oAuthVerifier: string;
5
6// popup related
7private windowHandle: Window; // reference to the window object we will create
8private intervalId: any = null; // For setting interval time between we check for authorization code or token
9private loopCount = 600; // the count until which the check will be done, or after window be closed automatically.
10private intervalLength = 100; // the gap in which the check will be done for code.
11
12doAuthorization(url: string, socialMediaProvider: string, isRegisterAction: boolean) {
13/* isRegisterAction flag i am using to check if the process is for registration or Login */
14/* socialMediaProvider is for name of social media , it is optional*/
15
16 let loopCount = this.loopCount;
17
18 /* Create the window object by passing url and optional window title */
19 this.windowHandle = this.createOauthWindow(authorizationUrl, 'OAuth login');
20
21 /* Now start the timer for which the window will stay, and after time over window will be closed */
22 this.intervalId = window.setInterval(() => {
23 if (loopCount-- < 0) {
24 window.clearInterval(this.intervalId);
25 this.windowHandle.close();
26 } else {
27 let href: string; // For referencing window url
28 try {
29 href = this.windowHandle.location.href; // set window location to href string
30 } catch (e) {
31 // console.log('Error:', e); // Handle any errors here
32 }
33 if (href != null) {
34
35 // Method for getting query parameters from query string
36 const getQueryString = function(field: any, url: string) {
37 const windowLocationUrl = url ? url : href;
38 const reg = new RegExp('[?&]' + field + '=([^&#]*)', 'i');
39 const string = reg.exec(windowLocationUrl);
40 return string ? string[1] : null;
41 };
42 /* As i was getting code and oauth-token i added for same, you can replace with your expected variables */
43 if (href.match('code')) {
44 // for google , fb, github, linkedin
45 window.clearInterval(this.intervalId);
46 this.authorizationCode = getQueryString('code', href);
47 this.windowHandle.close();
48 if (isRegisterAction) {
49 /* call signup method */
50 } else {
51 /* call login method */
52 }
53 } else if (href.match('oauth_token')) {
54 // for twitter
55 window.clearInterval(this.intervalId);
56 this.oAuthToken = getQueryString('oauth_token', href);
57 this.oAuthVerifier = getQueryString('oauth_verifier', href);
58 this.windowHandle.close();
59 if (isRegisterAction) {
60 /* call signup */
61 } else {
62 /* call login */
63 }
64 }
65 }
66 }
67 }, this.intervalLength);
68 }
69
70 createOauthWindow(url: string, name = 'Authorization', width = 500, height = 600, left = 0, top = 0) {
71 if (url == null) {
72 return null;
73 }
74 const options = `width=${width},height=${height},left=${left},top=${top}`;
75 return window.open(url, name, options);
76 }