1
/*
2
 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
5
 * the License. A copy of the License is located at
6
 *
7
 *     http://aws.amazon.com/apache2.0/
8
 *
9
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
11
 * and limitations under the License.
12
 */
13 1
import { ConsoleLogger as Logger } from '../Logger';
14 1
import { browserOrNode } from '../JS';
15 1
import { NonRetryableError } from '../Util';
16

17 1
const logger = new Logger('CognitoCredentials');
18

19 1
const waitForInit = new Promise((res, rej) => {
20 1
	if (!browserOrNode().isBrowser) {
21 0
		logger.debug('not in the browser, directly resolved');
22 0
		return res();
23
	}
24
	const ga =
25 1
		window['gapi'] && window['gapi'].auth2 ? window['gapi'].auth2 : null;
26 1
	if (ga) {
27 0
		logger.debug('google api already loaded');
28 0
		return res();
29
	} else {
30 1
		setTimeout(() => {
31 0
			return res();
32
		}, 2000);
33
	}
34
});
35

36 1
export class GoogleOAuth {
37 1
	public initialized = false;
38

39
	constructor() {
40 1
		this.refreshGoogleToken = this.refreshGoogleToken.bind(this);
41 1
		this._refreshGoogleTokenImpl = this._refreshGoogleTokenImpl.bind(this);
42
	}
43

44 1
	public async refreshGoogleToken() {
45 1
		if (!this.initialized) {
46 0
			logger.debug('need to wait for the Google SDK loaded');
47 0
			await waitForInit;
48 0
			this.initialized = true;
49 0
			logger.debug('finish waiting');
50
		}
51

52 1
		return this._refreshGoogleTokenImpl();
53
	}
54

55 1
	private _refreshGoogleTokenImpl() {
56 0
		let ga = null;
57 1
		if (browserOrNode().isBrowser)
58 1
			ga = window['gapi'] && window['gapi'].auth2 ? window['gapi'].auth2 : null;
59 1
		if (!ga) {
60 0
			logger.debug('no gapi auth2 available');
61 0
			return Promise.reject('no gapi auth2 available');
62
		}
63

64 0
		return new Promise((res, rej) => {
65 0
			ga.getAuthInstance()
66
				.then(googleAuth => {
67 1
					if (!googleAuth) {
68 0
						logger.debug('google Auth undefined');
69 0
						rej(new NonRetryableError('google Auth undefined'));
70
					}
71

72 0
					const googleUser = googleAuth.currentUser.get();
73
					// refresh the token
74 1
					if (googleUser.isSignedIn()) {
75 0
						logger.debug('refreshing the google access token');
76 0
						googleUser
77
							.reloadAuthResponse()
78
							.then(authResponse => {
79 0
								const { id_token, expires_at } = authResponse;
80 0
								res({ token: id_token, expires_at });
81
							})
82
							.catch(err => {
83 1
								if (err && err.error === 'network_error') {
84
									// Not using NonRetryableError so handler will be retried
85 0
									rej('Network error reloading google auth response');
86
								} else {
87 0
									rej(
88
										new NonRetryableError(
89
											'Failed to reload google auth response'
90
										)
91
									);
92
								}
93
							});
94
					} else {
95 0
						rej(new NonRetryableError('User is not signed in with Google'));
96
					}
97
				})
98
				.catch(err => {
99 0
					logger.debug('Failed to refresh google token', err);
100 0
					rej(new NonRetryableError('Failed to refresh google token'));
101
				});
102
		});
103
	}
104 1
}
105

106
/**
107
 * @deprecated use named import
108
 */
109 1
export default GoogleOAuth;

Read our documentation on viewing source code .

Loading