/
authenticate.js
209 lines (195 loc) · 8.12 KB
/
authenticate.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
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
'use strict'
const qs = require('querystring');
const path = require('path');
const fs = require('fs-extra');
const http = require('http');
const opn = require('opn');
const url = require('url');
const constants = require('../constants.js');
const smartsheetClient = require('smartsheet');
let smartsheet = smartsheetClient.createClient({
accessToken: ''
});
function authorizeURL(params) {
const authUrl = 'https://app.smartsheet.com/b/authorize';
return `${authUrl}?${qs.stringify(params)}`;
}
/**
* Saves access token to disk
*
* @param token
* @returns {Promise}
*/
function storeToken(token) {
return fs.ensureDir(constants.APP_DIR)
.then(() => {
const userAuthInfo = JSON.stringify(token);
const newFile = path.join(constants.APP_DIR, constants.TOKEN_FILE)
fs.writeFile(newFile, userAuthInfo, 'utf8', (err) => {
if (err) { return err; }
});
})
.catch((err) => {
console.error(err)
});
}
/**
* Get and store smartsheet access token taking user through oauth flow
*
* @param string authUrl
* @returns {Promise}
*/
function getNewToken(authUrl) {
return new Promise((resolve, reject) => {
// get Smartsheet access token through OAuth
// spin up local http server to receive auth code callback from Smartsheet
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const queryAsObject = parsedUrl.query;
const authCode = queryAsObject.code;
// generate the hash required by Smartsheet
const generated_hash = require('crypto')
.createHash('sha256')
.update(constants.CLIENT_SECRET + "|" + authCode, 'utf8')
.digest('hex');
const options = {
queryParameters: {
client_id: constants.CLIENT_ID,
code: authCode,
hash: generated_hash,
}
};
smartsheet.tokens.getAccessToken(options, (error, result) => {
if (error) {
reject(error);
return;
}
// store the retrieved token to the local token.json file
storeToken(result).then(() => {
resolve();
}, (error) => {
reject(error);
});
// instantiate new smartsheet client for making API calls with the new token
const newSmartsheet = smartsheetClient.createClient({
accessToken: result.access_token
});
resolve(newSmartsheet);
});
// send response to browser to let user know auth is successful
res.writeHead(302, {
'Location': 'https://smartsheet-samples.github.io/sscli.html',
});
res.end();
req.connection.end(); // close the socket
req.connection.destroy(); // close it really
server.close(); // close the server
}).listen(constants.REDIRECT_PORT); // callback server listens on the redirect_port in constants
// opens browser to the authorizationURL (auth consent form in Smartsheet)
opn(authUrl);
console.log(`A web page should opened to allow 'Smartsheet-CLI' to:`);
console.log(` 'Access your Smartsheet Account`);
console.log(`These permissions are necessary for pulling data from and pushing data to your Smartsheet Account.`);
});
}
module.exports = {
deleteToken : () => {
return new Promise((resolve, reject) => {
fs.removeSync(path.join(constants.APP_DIR, constants.TOKEN_FILE));
resolve();
})
},
manual: (access_token) => {
return new Promise((resolve, reject) => {
// make a call to smartsheet to test the validity of the token
smartsheet = smartsheetClient.createClient({
accessToken: access_token
});
smartsheet.users.getCurrentUser()
.then(function(userProfile) {
// if token seems valid, save it to the token_file
const token = {access_token: access_token};
storeToken(token)
.then(() => {
resolve(smartsheet);
}, (error) => {
reject(error);
});
})
.catch(function(error) {
console.error(error);
process.exit(1);
});
});
},
oAuth: () => {
return new Promise((resolve, reject) => {
// set file path for the token.json file
const tokenFile = path.join(constants.APP_DIR, constants.TOKEN_FILE);
const params = {
response_type: 'code',
client_id: constants.CLIENT_ID,
redirect_url: constants.REDIRECT_URL + ":" + constants.REDIRECT_PORT,
scope: constants.SCOPE
};
// build authorization URL with params values
const authUrl = authorizeURL(params);
// Check if we have previously stored a token.
fs.readFile(tokenFile, 'utf8', (err, token) => {
if (err !== null || token === '') {
// if there is no tokenFile getNewToken
getNewToken(authUrl).then((smartsheetClient) => {
resolve(smartsheetClient);
}, (err) => {
reject(err);
});
} else {
// use the token from the token.json file to create smartsheet client
let parsedToken = JSON.parse(token);
smartsheet = smartsheetClient.createClient({
accessToken: parsedToken.access_token
});
// check if token needs to be refreshed and then refresh auth token
smartsheet.users.getCurrentUser()
.then(function(userProfile) {
resolve(smartsheet);
})
.catch(function(error) {
// check for smartsheet errorCode 1003 (Your Access Token has expired)
if (error.errorCode === 1003) {
// refresh the token
const generated_hash = require('crypto')
.createHash('sha256')
.update(constants.CLIENT_SECRET + "|" + parsedToken.refresh_token)
.digest('hex');
const options = {
queryParameters: {
client_id: constants.CLIENT_ID,
refresh_token: parsedToken.refresh_token,
hash: generated_hash
}
};
console.log(options);
smartsheet.tokens.refreshAccessToken(options, storeToken)
.then((token) => {
storeToken(token).then(() => {
resolve();
}, (error) => {
reject(error);
});
const newSmartsheet = smartsheetClient.createClient({
accessToken: token.access_token
});
resolve(newSmartsheet);
})
.catch((error) => {
reject(error);
});
}
console.log(error);
});
}
});
});
}
}