-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoath.js
153 lines (127 loc) · 5.15 KB
/
oath.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
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
// Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
/**
* This is used by several samples to easily provide an oauth2 workflow.
*/
const { google } = require('googleapis');
const http = require('http');
const url = require('url');
const opn = require('opn');
const destroyer = require('server-destroy');
const fs = require('fs');
const path = require('path');
const keyPath = path.join(__dirname, 'client_secret.json');
const keyPathAsPackage = path.join(__dirname, '../../') + 'client_secret.json';
const TOKEN_PATH = 'token.json';
let keys = {}
if (fs.existsSync(keyPath) ) {
const keyFile = require(keyPath);
keys = keyFile.installed || keyFile.web;
keys.redirect_uris = ['http://localhost:3000/oauth2callback']
}else if (fs.existsSync(keyPathAsPackage)) {
const keyFile = require(keyPathAsPackage);
keys = keyFile.installed || keyFile.web;
keys.redirect_uris = ['http://localhost:3000/oauth2callback']
}
const invalidRedirectUri = `The provided keyfile does not define a valid
redirect URI. There must be at least one redirect URI defined, and this sample
assumes it redirects to 'http://localhost:3000/oauth2callback'. Please edit
your keyfile, and add a 'redirect_uris' section. For example:
"redirect_uris": [
"http://localhost:3000/oauth2callback"
]
`;
class Client {
constructor(options) {
this._options = options || { scopes: [] };
// validate the redirectUri. This is a frequent cause of confusion.
if (!keys.redirect_uris || keys.redirect_uris.length === 0) {
throw new Error(invalidRedirectUri);
}
const redirectUri = keys.redirect_uris[keys.redirect_uris.length - 1];
const parts = new url.URL(redirectUri);
if (
redirectUri.length === 0 ||
parts.port !== '3000' ||
parts.hostname !== 'localhost' ||
parts.pathname !== '/oauth2callback'
) {
throw new Error(invalidRedirectUri);
}
// create an oAuth client to authorize the API call
this.oAuth2Client = new google.auth.OAuth2(
keys.client_id,
keys.client_secret,
redirectUri
);
}
// Open an http server to accept the oauth callback. In this
// simple example, the only request to our webserver is to
// /oauth2callback?code=<code>
getAccessToken(resolve, reject, scopes) {
// grab the url that will be used for authorization
this.authorizeUrl = this.oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes.join(' '),
});
const server = http
.createServer(async (req, res) => {
try {
if (req.url.indexOf('/oauth2callback') > -1) {
const qs = new url.URL(req.url, 'http://localhost:3000')
.searchParams;
res.end(
'Authentication successful! Please return to the console.'
);
server.destroy();
const { tokens } = await this.oAuth2Client.getToken(qs.get('code'));
this.oAuth2Client.setCredentials(tokens)
fs.writeFile(TOKEN_PATH, JSON.stringify(tokens), (err) => {
if (err) {
console.error(err);
}
console.log('Token stored to', TOKEN_PATH);
});
resolve(this.oAuth2Client);
}
} catch (e) {
reject(e);
}
})
.listen(3000, () => {
// open the browser to the authorize url to start the workflow
opn(this.authorizeUrl, { wait: false }).then(cp => cp.unref());
});
destroyer(server);
}
async authenticate(scopes,needRefreshToken = true) {
return new Promise((resolve, reject) => {
fs.readFile(TOKEN_PATH, (err, token) => {
if (err || needRefreshToken) {
this.getAccessToken(resolve, reject, scopes)
}
else {
try{
this.oAuth2Client.setCredentials(JSON.parse(token));
resolve(this.oAuth2Client);
}catch(err){
this.getAccessToken(resolve, reject, scopes)
reject(err)
}
}
});
});
}
}
module.exports = new Client();