-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.ts
180 lines (156 loc) · 5.41 KB
/
index.ts
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// inspired by https://github.com/parro-it/electron-google-oauth
import { BrowserWindow, remote, shell } from 'electron';
import { EventEmitter } from 'events';
import { OAuth2Client } from 'google-auth-library';
import { Credentials } from 'google-auth-library/build/src/auth/credentials';
import { stringify } from 'querystring';
import * as url from 'url';
import LoopbackRedirectServer from './LoopbackRedirectServer';
const BW: typeof BrowserWindow = process.type === 'renderer' ? remote.BrowserWindow : BrowserWindow;
export class UserClosedWindowError extends Error {
constructor() {
super('User closed the window');
}
}
/**
* Tokens updated event
*
* @event ElectronGoogleOAuth2#tokens
* @type {Credentials}
*/
export type ElectronGoogleOAuth2Options = {
successRedirectURL: string,
loopbackInterfaceRedirectionPort: number,
refocusAfterSuccess: boolean,
};
export const defaultElectronGoogleOAuth2Options: ElectronGoogleOAuth2Options = {
successRedirectURL: 'https://getstation.com/app-login-success/',
// can't be randomized
loopbackInterfaceRedirectionPort: 42813,
refocusAfterSuccess: true,
};
/**
* Handle Google Auth processes through Electron.
* This class automatically renews expired tokens.
* @fires ElectronGoogleOAuth2#tokens
*/
class ElectronGoogleOAuth2 extends EventEmitter {
public oauth2Client: OAuth2Client;
public scopes: string[];
protected server: LoopbackRedirectServer | null;
protected options: ElectronGoogleOAuth2Options;
/**
* Create a new instance of ElectronGoogleOAuth2
* @param {string} clientId - Google Client ID
* @param {string} clientSecret - Google Client Secret
* @param {string[]} scopes - Google scopes. 'profile' and 'email' will always be present
* @param {Partial<ElectronGoogleOAuth2Options>} options
*/
constructor(
clientId: string,
clientSecret: string,
scopes: string[],
options: Partial<ElectronGoogleOAuth2Options> = defaultElectronGoogleOAuth2Options,
) {
super();
// Force fetching id_token if not provided
if (!scopes.includes('profile')) scopes.push('profile');
if (!scopes.includes('email')) scopes.push('email');
this.scopes = scopes;
this.options = { ...defaultElectronGoogleOAuth2Options, ...options };
this.oauth2Client = new OAuth2Client(
clientId,
clientSecret,
`http://127.0.0.1:${this.options.loopbackInterfaceRedirectionPort}/callback`
);
this.oauth2Client.on('tokens', (tokens) => {
this.emit('tokens', tokens);
});
}
/**
* Returns authUrl generated by googleapis
* @param {boolean} forceAddSession
* @returns {string}
*/
generateAuthUrl(forceAddSession: boolean = false) {
let url = this.oauth2Client.generateAuthUrl({
access_type: 'offline', // 'online' (default) or 'offline' (gets refresh_token)
scope: this.scopes,
redirect_uri: `http://127.0.0.1:${this.options.loopbackInterfaceRedirectionPort}/callback`
});
if (forceAddSession) {
const qs = stringify({ continue: url });
url = `https://accounts.google.com/AddSession?${qs}`;
}
return url;
}
/**
* Get authorization code for underlying authUrl
* @param {boolean} forceAddSession
* @returns {Promise<string>}
*/
getAuthorizationCode(forceAddSession: boolean = false) {
const url = this.generateAuthUrl(forceAddSession);
return this.openAuthWindowAndGetAuthorizationCode(url);
}
/**
* Get authorization code for given url
* @param {string} urlParam
* @returns {Promise<string>}
*/
openAuthWindowAndGetAuthorizationCode(urlParam: string) {
return this.openAuthPageAndGetAuthorizationCode(urlParam);
}
async openAuthPageAndGetAuthorizationCode(urlParam: string) {
if (this.server) {
// if a server is already running, we close it so that we free the port
// and restart the process
await this.server.close();
this.server = null;
}
this.server = new LoopbackRedirectServer({
port: this.options.loopbackInterfaceRedirectionPort,
callbackPath: '/callback',
successRedirectURL: this.options.successRedirectURL,
});
shell.openExternal(urlParam);
const reachedCallbackURL = await this.server.waitForRedirection();
// waitForRedirection will close the server
this.server = null;
const parsed = url.parse(reachedCallbackURL, true);
if (parsed.query.error) {
throw new Error(parsed.query.error_description as string);
} else if (!parsed.query.code) {
throw new Error('Unknown');
}
if (this.options.refocusAfterSuccess) {
// refocus on the window
BW.getAllWindows().filter(w => w.isVisible()).forEach(w => w.show());
}
return parsed.query.code as string
}
/**
* Get Google tokens for given scopes
* @param {boolean} forceAddSession
* @returns {Promise<Credentials>}
*/
openAuthWindowAndGetTokens(forceAddSession: boolean = false) {
return this
.getAuthorizationCode(forceAddSession)
.then((authorizationCode) => {
return this.oauth2Client
.getToken(authorizationCode)
.then(response => {
this.oauth2Client.setCredentials(response.tokens);
return response.tokens;
});
});
}
setTokens(tokens: Credentials) {
this.oauth2Client.setCredentials(tokens);
}
}
declare interface ElectronGoogleOAuth2 {
on(event: 'tokens', listener: (tokens: Credentials) => void): this;
}
export default ElectronGoogleOAuth2