UNPKG

2.87 kBPlain TextView Raw
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 */
13import { ConsoleLogger as Logger } from '../Logger';
14import { browserOrNode } from '../JS';
15import { NonRetryableError } from '../Util';
16
17const logger = new Logger('CognitoCredentials');
18
19const waitForInit = new Promise((res, rej) => {
20 if (!browserOrNode().isBrowser) {
21 logger.debug('not in the browser, directly resolved');
22 return res();
23 }
24 const fb = window['FB'];
25 if (fb) {
26 logger.debug('FB SDK already loaded');
27 return res();
28 } else {
29 setTimeout(() => {
30 return res();
31 }, 2000);
32 }
33});
34
35export class FacebookOAuth {
36 public initialized = false;
37
38 constructor() {
39 this.refreshFacebookToken = this.refreshFacebookToken.bind(this);
40 this._refreshFacebookTokenImpl = this._refreshFacebookTokenImpl.bind(this);
41 }
42
43 public async refreshFacebookToken() {
44 if (!this.initialized) {
45 logger.debug('need to wait for the Facebook SDK loaded');
46 await waitForInit;
47 this.initialized = true;
48 logger.debug('finish waiting');
49 }
50
51 return this._refreshFacebookTokenImpl();
52 }
53
54 private _refreshFacebookTokenImpl() {
55 let fb = null;
56 if (browserOrNode().isBrowser) fb = window['FB'];
57 if (!fb) {
58 const errorMessage = 'no fb sdk available';
59 logger.debug(errorMessage);
60 return Promise.reject(new NonRetryableError(errorMessage));
61 }
62
63 return new Promise((res, rej) => {
64 fb.getLoginStatus(
65 fbResponse => {
66 if (!fbResponse || !fbResponse.authResponse) {
67 const errorMessage =
68 'no response from facebook when refreshing the jwt token';
69 logger.debug(errorMessage);
70 // There is no definitive indication for a network error in
71 // fbResponse, so we are treating it as an invalid token.
72 rej(new NonRetryableError(errorMessage));
73 } else {
74 const response = fbResponse.authResponse;
75 const { accessToken, expiresIn } = response;
76 const date = new Date();
77 const expires_at = expiresIn * 1000 + date.getTime();
78 if (!accessToken) {
79 const errorMessage = 'the jwtToken is undefined';
80 logger.debug(errorMessage);
81 rej(new NonRetryableError(errorMessage));
82 }
83 res({
84 token: accessToken,
85 expires_at,
86 });
87 }
88 },
89 { scope: 'public_profile,email' }
90 );
91 });
92 }
93}
94
95/**
96 * @deprecated use named import
97 */
98export default FacebookOAuth;