1+ import * as google from 'googleapis' ;
2+ import { authenticate } from '@google-cloud/local-auth'
3+
4+ import * as fs from 'fs' ;
5+ import { AuthClient } from './base' ;
6+
7+ export class Oauth2GoogleAuthClient implements AuthClient {
8+ private auth ! : google . Auth . OAuth2Client ;
9+
10+ private constructor ( auth : google . Auth . OAuth2Client ) {
11+ this . auth = auth ;
12+ }
13+
14+ public static async fromFile (
15+ secretFilePath : string ,
16+ credsFilePath : string ,
17+ scopes : string [ ] ,
18+ ) : Promise < Oauth2GoogleAuthClient > {
19+ const storedClient = await this . loadCredsIfExists ( credsFilePath ) ;
20+ if ( storedClient ) {
21+ return new Oauth2GoogleAuthClient ( storedClient ) ;
22+ }
23+
24+ const newClient = await authenticate ( {
25+ scopes : scopes ,
26+ keyfilePath : secretFilePath ,
27+ } ) ;
28+
29+ if ( newClient . credentials ) {
30+ await this . storeCredentials ( secretFilePath , credsFilePath , newClient ) ;
31+ }
32+ return new Oauth2GoogleAuthClient ( newClient ) ;
33+ }
34+
35+ private static async loadCredsIfExists ( credsFilePath : string ) : Promise < google . Auth . OAuth2Client | null > {
36+ try {
37+ const content = await fs . promises . readFile ( credsFilePath ) ;
38+ const credentials = JSON . parse ( content . toString ( ) ) ;
39+ return google . google . auth . fromJSON ( credentials ) as google . Auth . OAuth2Client ;
40+ } catch ( err ) {
41+ return null ;
42+ }
43+ }
44+
45+ private static async storeCredentials (
46+ secretFilePath : string ,
47+ credsFilePath : string ,
48+ client : google . Auth . OAuth2Client ,
49+ ) {
50+ const content = await fs . promises . readFile ( secretFilePath ) ;
51+ const keys = JSON . parse ( content . toString ( ) ) ;
52+ const key = keys . installed || keys . web ;
53+ const payload = JSON . stringify ( {
54+ type : 'authorized_user' ,
55+ client_id : key . client_id ,
56+ client_secret : key . client_secret ,
57+ refresh_token : client . credentials . refresh_token ,
58+ } ) ;
59+ await fs . promises . writeFile ( credsFilePath , payload ) ;
60+ }
61+
62+ public getAuthHeadersClient ( ) : google . Auth . GoogleAuth | google . Auth . OAuth2Client {
63+ return this . auth ! ;
64+ }
65+ }
0 commit comments