| 11 | * @returns The access token. |
| 12 | */ |
| 13 | export async function getAccessToken(client_email?: string, private_key?: string, customPath?: string) { |
| 14 | if (!client_email && !private_key) { |
| 15 | const filePath = "service_account.json"; |
| 16 | const filePathFromHome = path.join(os.homedir(), ".gis", "service_account.json"); |
| 17 | const isFile = fs.existsSync(filePath); |
| 18 | const isFileFromHome = fs.existsSync(filePathFromHome); |
| 19 | const isCustomFile = !!customPath && fs.existsSync(customPath); |
| 20 | |
| 21 | if (!isFile && !isFileFromHome && !isCustomFile) { |
| 22 | console.error(`❌ ${filePath} not found, please follow the instructions in README.md`); |
| 23 | console.error(""); |
| 24 | process.exit(1); |
| 25 | } |
| 26 | |
| 27 | const key = JSON.parse( |
| 28 | fs.readFileSync(!!customPath && isCustomFile ? customPath : isFile ? filePath : filePathFromHome, "utf8") |
| 29 | ); |
| 30 | client_email = key.client_email; |
| 31 | private_key = key.private_key; |
| 32 | } else { |
| 33 | if (!client_email) { |
| 34 | console.error("❌ Missing client_email in service account credentials."); |
| 35 | console.error(""); |
| 36 | process.exit(1); |
| 37 | } |
| 38 | |
| 39 | if (!private_key) { |
| 40 | console.error("❌ Missing private_key in service account credentials."); |
| 41 | console.error(""); |
| 42 | process.exit(1); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | const jwtClient = new google.auth.JWT( |
| 47 | client_email, |
| 48 | undefined, |
| 49 | private_key, |
| 50 | ["https://www.googleapis.com/auth/webmasters.readonly", "https://www.googleapis.com/auth/indexing"], |
| 51 | undefined |
| 52 | ); |
| 53 | |
| 54 | const tokens = await jwtClient.authorize(); |
| 55 | return tokens.access_token; |
| 56 | } |