|
| 1 | +import { EventEmitter } from 'eventemitter3'; |
| 2 | +import { singleton } from './decorators'; |
| 3 | + |
| 4 | +export interface IGapiOAuthInitArgs { |
| 5 | + /** |
| 6 | + * The API Key to use. |
| 7 | + */ |
| 8 | + apiKey?: string; |
| 9 | + /** |
| 10 | + * An array of discovery doc URLs or discovery doc JSON objects. |
| 11 | + */ |
| 12 | + discoveryDocs?: string[]; |
| 13 | + /** |
| 14 | + * The app's client ID, found and created in the Google Developers Console. |
| 15 | + */ |
| 16 | + clientId?: string; |
| 17 | + /** |
| 18 | + * The scopes to request, as a space-delimited string. |
| 19 | + */ |
| 20 | + scope?: string; |
| 21 | +} |
| 22 | + |
| 23 | +@singleton |
| 24 | +export class OAuth extends EventEmitter { |
| 25 | + |
| 26 | + constructor(private args: IGapiOAuthInitArgs = {}) { |
| 27 | + super(); |
| 28 | + console.log('OAuth instantiated'); |
| 29 | + // Loads the client library and the auth2 library together for efficiency. |
| 30 | + // Loading the auth2 library is optional here since `gapi.client.init` function will load |
| 31 | + // it if not already loaded. Loading it upfront can save one network request. |
| 32 | + gapi.load('client:auth2', () => this.initClient()); |
| 33 | + } |
| 34 | + |
| 35 | + isSignedIn(): boolean { |
| 36 | + return gapi.auth2.getAuthInstance().isSignedIn.get(); |
| 37 | + } |
| 38 | + |
| 39 | + signIn() { |
| 40 | + gapi.auth2.getAuthInstance().signIn(); |
| 41 | + } |
| 42 | + |
| 43 | + signOut() { |
| 44 | + gapi.auth2.getAuthInstance().signOut(); |
| 45 | + } |
| 46 | + |
| 47 | + private async initClient() { |
| 48 | + // Initialize the client with API key and People API, and initialize OAuth with an |
| 49 | + // OAuth 2.0 client ID and scopes (space delimited string) to request access. |
| 50 | + try { |
| 51 | + await gapi.client.init(this.args); |
| 52 | + // Listen for sign-in state changes. |
| 53 | + gapi.auth2.getAuthInstance().isSignedIn.listen((val) => { |
| 54 | + this.updateSigninStatus(val); |
| 55 | + }); |
| 56 | + // Handle the initial sign-in state. |
| 57 | + this.updateSigninStatus(this.isSignedIn()); |
| 58 | + } catch (e) { |
| 59 | + console.error(e); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + private updateSigninStatus(isSignedIn) { |
| 64 | + this.emit('gapi.auth2.isSignedIn', isSignedIn); |
| 65 | + if (!isSignedIn) { |
| 66 | + this.signIn(); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
0 commit comments