blob: 5249d68aa660faddcef8404df70df0e64268d730 [file] [log] [blame]
Copybara854996b2021-09-07 19:36:02 +00001// Copyright 2019 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5/**
6 * gapi-loader.js provides a method for loading gapi.js asynchronously.
7 *
8 * gapi.js docs:
9 * https://developers.google.com/identity/sign-in/web/reference
10 * (we load gapi.js via the chops-signin module)
11 */
12
13import * as signin from '@chopsui/chops-signin';
14
15const BUGANIZER_SCOPE = 'https://www.googleapis.com/auth/buganizer';
16// Only allow google.com profiles through currently.
17const RESTRICT_TO_DOMAIN = '@google.com';
18
19// loadGapi loads window.gapi and returns a logged in user object or null.
20// Allows overriding signinImpl for testing.
21export default function loadGapi() {
22 const signinImpl = getSigninInstance();
23 // Validate client_id exists.
24 if (!CS_env.gapi_client_id) {
25 throw new Error('Cannot find gapi.js client id');
26 }
27
28 // Prevent gapi.js from being loaded multiple times.
29 if (window.__gapiLoadPromise) {
30 return window.__gapiLoadPromise;
31 }
32
33 window.__gapiLoadPromise = new Promise(async (resolve) => {
34 signinImpl.init(CS_env.gapi_client_id, ['client'], [BUGANIZER_SCOPE]);
35 resolve(await fetchGapiEmail(signinImpl));
36 });
37
38 return window.__gapiLoadPromise;
39}
40
41// For fetching current email. May have changed since load.
42export function fetchGapiEmail() {
43 const signinImpl = getSigninInstance();
44 return new Promise((resolve) => {
45 signinImpl.getUserProfileAsync().then((profile) => {
46 resolve(
47 (
48 profile &&
49 profile.getEmail instanceof Function &&
50 profile.getEmail().endsWith(RESTRICT_TO_DOMAIN) &&
51 profile.getEmail()
52 ) || null,
53 );
54 });
55 });
56}
57
58// Provide a singleton chops-signin instance to make testing easier.
59let signinInstance;
60export function getSigninInstance(signinImpl=signin, overwrite=false) {
61 // Assign on first run.
62 if (overwrite || !signinInstance) {
63 signinInstance = signinImpl;
64 }
65 return signinInstance;
66}