oauth2.js 2.29 KB
const { google } = require("googleapis");
var http = require('http');
var opn = require('opn');
var destroyer = require('destroyer');
var url = require('url');
var enableDestroy = require('server-destroy');
const oauth2Client = new google.auth.OAuth2(
    "394965702516-q817fn2gj8r8sqoudhp29k1rd71ku42j.apps.googleusercontent.com",
    "xgo5tcTwsmg2alNumeY1Drj_",
    "http://localhost:3031/api/oauth2callback"
);

const scopes = [
    'https://www.googleapis.com/auth/youtube',
    'https://www.googleapis.com/auth/youtube.force-ssl',
    'https://www.googleapis.com/auth/youtube.readonly',
    'https://www.googleapis.com/auth/youtubepartner'
];

let refreshToken = '';

async function authenticate() {

    return new Promise((resolve, reject) => {

        if (refreshToken !== "") {
            oauth2Client.setCredentials({
                refresh_token: refreshToken
            });

            oauth2Client.getAccessToken((err, ttoken) => {
                if (err) {
                    reject(e);
                }
                resolve(oauth2Client);
            });
        } else {
            const authorizeUrl = oauth2Client.generateAuthUrl({
                access_type: 'offline',
                scope: scopes.join(' '),
            });
            const server = http.createServer(async (req, res) => {
                try {
                    if (req.url.indexOf('/api/oauth2callback') > -1) {
                        const qs = new url.URL(req.url, 'http://localhost:3031').searchParams;
                        res.end('Completed');
                        enableDestroy(server);
                        server.destroy();

                        const {
                            tokens
                        } = await oauth2Client.getToken(qs.get('code'));
                        
                        refreshToken = tokens.refresh_token;
                        oauth2Client.credentials = tokens;

                        resolve(oauth2Client);
                    }
                } catch (e) {
                    reject(e);
                }
            }).listen(3031, () => {

                opn(authorizeUrl, {
                    wait: false
                }).then(cp => cp.unref());
            });

            destroyer(server);
        }
    });
}

module.exports.refreshClient=authenticate;