Skip to content

Commit

Permalink
updated server to use forge api modules
Browse files Browse the repository at this point in the history
  • Loading branch information
pan261 committed Nov 4, 2021
1 parent de316f5 commit 2cecd17
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 123 deletions.
5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,9 @@
"license": "ISC",
"dependencies": {
"axios": "^0.24.0",
"body-parser": "^1.19.0",
"cookie-session": "^1.4.0",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"forge-apis": "^0.8.6",
"puppeteer": "^10.4.0",
"querystring": "^0.2.1"
"forge-apis": "^0.8.6"
}
}
55 changes: 0 additions & 55 deletions puppeteer.js

This file was deleted.

132 changes: 68 additions & 64 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
const path = require('path');
const express = require('express');
const cookieSession = require('cookie-session');
const querystring = require('querystring');
const axios = require('axios');
const bodyParser = require('body-parser');
require('dotenv').config();

const PORT = process.env.PORT || 3000;
const ForgeSDK = require('forge-apis');

/*
Resources used:
Expand All @@ -20,69 +17,76 @@ const PORT = process.env.PORT || 3000;
FORGE_CALLBACK_URL (should be 'http://localhost:3000/callback/') should be the same in the .env
and in the Forge API project console.
Usage: node server.js or npm start
Usage: node test.js or npm start
Navigate to http://localhost:3000/auth/ to get started
Browser should then go through the Autodesk Auth screen and display Auth token.
*/

if (process.env.FORGE_CLIENT_ID == null || process.env.FORGE_CLIENT_SECRET == null) {
console.error('Missing FORGE_CLIENT_ID or FORGE_CLIENT_SECRET env. variables.');
return;

/*
Function to start the server
TODO: return both the oAuth2ThreeLegged and credentials objects, these will be needed for other API wrappers
*/
function createServer() {
const app = express();
const PORT = process.env.PORT || 3000;
const scopes = ['bucket:create', 'bucket:read', 'data:read', 'data:create', 'data:write'];
const oAuth2ThreeLegged = new ForgeSDK.AuthClientThreeLegged(
process.env.FORGE_CLIENT_ID,
process.env.FORGE_CLIENT_SECRET,
process.env.FORGE_CALLBACK_URL,
scopes,
true
);

if (process.env.FORGE_CLIENT_ID == null || process.env.FORGE_CLIENT_SECRET == null) {
console.error('Missing FORGE_CLIENT_ID or FORGE_CLIENT_SECRET env. variables.');
return;
}

app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieSession({
name: 'forge_session',
keys: ['forge_secure_key'],
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days, same as refresh token
}));

// Endpoint to begin authentication process
app.get('/auth', function (req, res) {
res.redirect(oAuth2ThreeLegged.generateAuthUrl());
});

// Endpoint Forge redirects to after consent screen
app.get('/callback', function (req, res) {
oAuth2ThreeLegged.getToken(req.query.code).then(function (credentials) {
console.log(credentials)
res.send('Generated token: ' + credentials.access_token);
}, function(err){
console.error(err);
res.send('Failed to authenticate');
});
});

app.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});

const server = app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); });

return server;
}

const scopes = ['bucket:create', 'bucket:read', 'data:read', 'data:create', 'data:write'];

let app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieSession({
name: 'forge_session',
keys: ['forge_secure_key'],
maxAge: 14 * 24 * 60 * 60 * 1000 // 14 days, same as refresh token
}));

app.get('/auth', function (req, res) {
var redirect_uri = 'https://developer.api.autodesk.com/authentication/v1/authorize?'
+ 'response_type=code'
+ '&client_id=' + process.env.FORGE_CLIENT_ID
+ '&redirect_uri=' + process.env.FORGE_CALLBACK_URL
+ '&scope=' + scopes.join(' ');
console.log(redirect_uri);
res.redirect(redirect_uri);
});

app.get('/callback', function (req, res) {
axios({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: querystring.stringify({
client_id: process.env.FORGE_CLIENT_ID,
client_secret: process.env.FORGE_CLIENT_SECRET,
grant_type: 'authorization_code',
code: req.query.code,
redirect_uri: process.env.FORGE_CALLBACK_URL
})
})
.then(function (response) {
// Success
access_token = response.data.access_token;
console.log(response);
res.send('<p>Authentication success! Here is your token:</p>' + access_token);
})
.catch(function (error) {
// Failed
console.log(error);
res.send('Failed to authenticate');
});
});

app.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});

app.use(bodyParser.json());

app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`); });
/*
Function to shutdown the server
*/
function shutdownServer(server) {
server.close(() => {
console.log('Closing connections');
return;
});
}


module.exports.create = createServer;
module.exports.shutdown = shutdownServer;
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const authServer = require('./server');

/*
Look at this for fetching new auth tokens in a loop:
https://nodejs.org/en/docs/guides/timers-in-node/
*/

function intervalFunc() {
console.log('Running every 15 sec');
}

(async () => {
let server = await authServer.create();
})();

/*
Testing setInterval function, will likely need to use this for refreshing auth tokens
*/
setInterval(intervalFunc, 15000);

1 comment on commit 2cecd17

@pan261
Copy link
Contributor Author

@pan261 pan261 commented on 2cecd17 Nov 4, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use node test.js to run the server

Please sign in to comment.