// 開另外一個路由,當使用者授權後會依照YOUR_REDIRECT_URL路由發請求到後端,要在這裡接 if (req.url.startsWith('/oauth2callback')) { // Handle the OAuth 2.0 server response let q = url.parse(req.url, true).query;
if (q.error) { // An error response e.g. error=access_denied console.log('Error:' + q.error); } else { // q.code 就是 authorization code // 再透過他取得access token let { tokens } = await oauth2Client.getToken(q.code); // 把token存到oauth2Client oauth2Client.setCredentials(tokens);
userCredential = tokens; // 這裡透過oauth2Client取得使用者相關資料,這裡是取得drive的資料 const drive = google.drive('v3'); drive.files.list({ auth: oauth2Client, pageSize: 10, fields: 'nextPageToken, files(id, name)', }, (err1, res1) => { if (err1) returnconsole.log('The API returned an error: ' + err1); const files = res1.data.files; if (files.length) { console.log('Files:'); files.map((file) => { console.log(`${file.name} (${file.id})`); }); } else { console.log('No files found.'); } }); } } // 這邊是撤銷token 用在登出時 if (req.url == '/revoke') { // Build the string for the POST request let postData = "token=" + userCredential.access_token;
// Options for POST request to Google's OAuth 2.0 server to revoke a token let postOptions = { host: 'oauth2.googleapis.com', port: '443', path: '/revoke', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } };
// Set up the request const postReq = https.request(postOptions, function (res) { res.setEncoding('utf8'); res.on('data', d => { console.log('Response: ' + d); }); });