| 5 | import { oauth2Client } from './index'; |
| 6 | |
| 7 | export async function authenticate(scopes: string[]) { |
| 8 | return new Promise((resolve, reject) => { |
| 9 | // grab the url that will be used for authorization |
| 10 | const authorizeUrl = oauth2Client.generateAuthUrl({ |
| 11 | access_type: 'offline', |
| 12 | scope: scopes.join(' '), |
| 13 | }); |
| 14 | const server = http |
| 15 | .createServer(async (req, res) => { |
| 16 | try { |
| 17 | if (req.url && req.url.indexOf('/oauth2callback') > -1) { |
| 18 | const qs = new url.URL(req.url, 'http://localhost:3000') |
| 19 | .searchParams; |
| 20 | res.end('Authentication successful! Please return to the console.'); |
| 21 | (server as any).destroy(); |
| 22 | const code = qs.get('code'); |
| 23 | if (!code) { |
| 24 | return reject('missing code'); |
| 25 | } |
| 26 | const { tokens } = await oauth2Client.getToken(code); |
| 27 | oauth2Client.credentials = tokens; // eslint-disable-line require-atomic-updates |
| 28 | resolve(oauth2Client); |
| 29 | } |
| 30 | } catch (e) { |
| 31 | reject(e); |
| 32 | } |
| 33 | }) |
| 34 | .listen(3000, () => { |
| 35 | // open the browser to the authorize url to start the workflow |
| 36 | opn(authorizeUrl, { wait: false }).then((cp) => cp.unref()); |
| 37 | }); |
| 38 | destroyer(server); |
| 39 | }); |
| 40 | } |