forked from parro-it/electron-google-oauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (72 loc) · 2.5 KB
/
index.js
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
75
76
77
78
79
80
81
82
83
84
85
86
const {stringify} = require('querystring');
const google = require('googleapis');
const co = require('co');
const fetch = require('node-fetch');
// eslint-disable-next-line import/no-extraneous-dependencies
//const {BrowserWindow} = require('electron');
const electron = require('electron')
var BrowserWindow = electron.BrowserWindow;
const OAuth2 = google.auth.OAuth2;
/* eslint-disable camelcase */
function getAuthenticationUrl(scopes, clientId, clientSecret, redirectUri = 'urn:ietf:wg:oauth:2.0:oob') {
const oauth2Client = new OAuth2(
clientId,
clientSecret,
redirectUri
);
const url = oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: scopes // If you only need one scope you can pass it as string
});
return url;
}
function authorizeApp(url, browserWindowParams) {
return new Promise((resolve, reject) => {
const win = new BrowserWindow(browserWindowParams || {'use-content-size': true});
win.loadURL(url);
win.on('closed', () => {
reject(new Error('User closed the window'));
});
win.on('page-title-updated', () => {
setImmediate(() => {
const title = win.getTitle();
if (title.startsWith('Denied')) {
reject(new Error(title.split(/[ =]/)[2]));
win.removeAllListeners('closed');
win.close();
} else if (title.startsWith('Success')) {
resolve(title.split(/[ =]/)[2]);
win.removeAllListeners('closed');
win.close();
}
});
});
});
}
module.exports = function electronGoogleOauth(browserWindowParams, httpAgent) {
function getAuthorizationCode(scopes, clientId, clientSecret, redirectUri = 'urn:ietf:wg:oauth:2.0:oob') {
const url = getAuthenticationUrl(scopes, clientId, clientSecret, redirectUri);
return authorizeApp(url, browserWindowParams);
}
const getAccessToken = co.wrap(function * (scopes, clientId, clientSecret, redirectUri = 'urn:ietf:wg:oauth:2.0:oob') {
const authorizationCode = yield getAuthorizationCode(scopes, clientId, clientSecret, redirectUri);
const data = stringify({
code: authorizationCode,
client_id: clientId,
client_secret: clientSecret,
grant_type: 'authorization_code',
redirect_uri: redirectUri
});
const res = yield fetch('https://accounts.google.com/o/oauth2/token', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data,
agent: httpAgent
});
return yield res.json();
});
return {getAuthorizationCode, getAccessToken};
};