oauth2.js
2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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;