Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -336,5 +336,6 @@
"inside"
],
"yoda": 2
}
},
"parser": "babel-eslint"
}
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
"moment": "2.22.2"
},
"devDependencies": {
"babel-eslint": "^10.1.0",
"chai": "4.1.2",
"eslint": "^7.24.0",
"eslint-plugin-import": "^2.22.1",
"hold-it": "^1.0.1"
}
}
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ const GCL = require('./gcl');
const Edmodo = require('./edmodo');
const LMSError = require('./error');
const Canvas = require('./canvas');
const Schoology = require("./schoology");

module.exports = {
GCL, LMSError, Edmodo, Canvas
GCL, LMSError, Edmodo, Canvas, Schoology
};
259 changes: 196 additions & 63 deletions src/oauth2.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,199 @@
/// <reference path='./oauth2.d.ts' />
// / <reference path='./oauth.d.ts' />

const axios = require('axios');
const { URL, URLSearchParams } = require('url');

const LMSError = require('./error.js');

// function handleError(err) {
// if (err.response) {
// if (err.response.status === 401 && err.response.data.error_message === 'The access token expired') {
// throw new LMSError('Token expired', 'edmodo.EXPIRED', err.response.data);
// }

// if (err.response.status === 403 && err.response.data.error === 'Forbidden') {
// throw new LMSError('Unauthorized', 'edmodo.FORBIDDEN', err.response.data);
// }
// throw new LMSError('Some other api error', 'edmodo.ERROR', err.response.data);
// } else if (err.request) {
// throw new LMSError('Something wrong with request', 'edmodo.ERROR', {
// message: err.message,
// config: err.config,
// });
// } else {
// // Something happened in setting up the request that triggered an Error
// throw new LMSError('Something completely different', 'lms.ERROR', {
// message: err.message,
// config: err.config,
// });
// }
// }

exports.makeURL = function makeURL(apiURL, path, query) {
const url = new URL(apiURL);

if (path) {
url.pathname = path;
}

url.search = new URLSearchParams(query);
return url.toString();
};

exports.post = function post(host, path, query, data, headers = {}) {
return axios.post(exports.makeURL(host, path, query), data, {
headers,
responseType: 'json',
}).then(response => {
return {
status: response.status,
data: response.data,
};
});
};

exports.get = function get(host, path, query, headers) {
return axios.get(exports.makeURL(host, path, query), {
headers,
}).then(response => {
return {
status: response.status,
data: response.data,
};
}).catch(err => {
return handleError(err);
});
};
const _ = require('lodash');
const axios = require('axios').default;
const { v4: uuidV4 } = require('uuid');

class OAuth {
constructor( {
consumerKey = '',
consumerSecret = '',
apiBase = '',
authRealm = '',
signatureMethod = 'PLAINTEXT',
nonceLength = 16,
requestToken,
accessToken,
errorHandler = (() => {})
} ) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.apiBase = apiBase;
this.authRealm = authRealm;
this.signatureMethod = signatureMethod;
this.nonceLength = nonceLength;
this.requestToken = {
token: requestToken.token || '',
secret: requestToken.secret || '',
expiresAt: requestToken.expiresAt || new Date()
};
this.accessToken = {
token: accessToken.token || '',
secret: accessToken.secret || '',
expiresAt: accessToken.expiresAt || new Date()
};
this.errorHandler = errorHandler;
}

static getTimeStamp () {
return parseInt(new Date().getTime()/1000, 10);
}

static getNonce( nonceLength ) {
return uuidV4().replace(/-/g, '').slice(-16);
Copy link
Contributor

Choose a reason for hiding this comment

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

This should use the nonceLength param to decide the length

}

static makeURL( apiURL, path, query ) {
const url = new URL(apiURL);

if (path) {
url.pathname = path;
}

url.search = new URLSearchParams(query);
return url.toString();
}

static post(host, path, query, data, headers = {}) {
const url = OAuth.makeURL(host, path, query);

return axios.post(url, data, {
headers,
responseType: 'json',
});
}

static get(host, path, query, headers) {
const url = OAuth.makeURL(host, path, query);

return axios.get(url, {
headers,
responseType: 'json',
});
}

static jsonifyResponseString(responseString) {
const strSplits = responseString.split( '&' );

return _.reduce( strSplits, ( result, keyValPair ) => {
const splits = keyValPair.split( '=' );

result[ splits[0] ] = splits[1];
return result;
}, {} );
}


async getRequestTokens( apiPath ) {
const oAuthDetails = this.getOAuthDetails(false);
const requestedAt = Date.now();

try {
const response = await OAuth.get(this.apiBase, apiPath, oAuthDetails);
const jsonified = OAuth.jsonifyResponseString(response.data);
const ttl = parseInt( jsonified[ 'xoauth_token_ttl' ] ) || 3600;

return {
success: true,
response: {
token: jsonified[ 'oauth_token' ],
secret: jsonified[ 'oauth_token_secret' ],
expiresAt: new Date( requestedAt + ( ttl * 1000 ) )
}
}
} catch ( error ) {
this.errorHandler(error);
}
}

async getAccessTokens( apiPath ) {
const oAuthDetails = this.getOAuthDetails();

try {
const response = await OAuth.get(this.apiBase, apiPath, oAuthDetails);
const jsonified = OAuth.jsonifyResponseString(response.data);

this.accessToken = {
token: jsonified[ 'oauth_token' ],
secret: jsonified[ 'oauth_token_secret' ],
};

return {
success: true,
response: this.accessToken
}
} catch (error) {
this.errorHandler(error);
}
}

/**
* Makes a request, defined by the requestConfig, to the server
* Attempts to refresh the accessToken if server throws a "token expired" error and
* then re-attempts the request
*/
async makeRequest(requestConfig, retries = 0) {
try {
if (_.isEmpty(this.accessToken)) {
// this.errorHandler( {} )
return;
}

const url = OAuth.makeURL(this.apiBase, requestConfig.url, requestConfig.query || {});
const oAuthHeader = this.getOAuthHeader();

const response = await axios({
...requestConfig,
url,
headers: {
...oAuthHeader,
...requestConfig.headers
},
});
const { data, status } = response;

return { data, status };
} catch (error) {
this.errorHandler(error);
}
}

getOAuthDetails( attachAccessToken = true ) {
const timestamp = OAuth.getTimeStamp();
const nonce = OAuth.getNonce( this.nonceLength );
const token = this.accessToken.token || this.requestToken.token || '';
const secret = this.accessToken.secret || this.requestToken.secret || '';
const oAuthConfig = {
'oauth_version': '1.0',
'oauth_nonce': nonce,
'oauth_timestamp': timestamp,
'oauth_signature_method': 'PLAINTEXT'
};

if ( !_.isEmpty( this.consumerKey ) ) {
oAuthConfig[ 'oauth_consumer_key' ] = this.consumerKey;
}

if ( attachAccessToken && !_.isEmpty( token ) ) {
oAuthConfig[ 'oauth_token' ] = token;
}

if ( !_.isEmpty( this.consumerSecret ) || !_.isEmpty(secret) ) {
const secretToUse = attachAccessToken ? secret : '';
oAuthConfig[ 'oauth_signature' ] = `${this.consumerSecret}&${secretToUse}`;
}

return oAuthConfig;
}

getOAuthHeader() {
const oAuthDetails = this.getOAuthDetails();
const headerParts = _.map(oAuthDetails, (value, key) => `${key}=${value}`);

return { Authorization: `OAuth realm="${this.authRealm}", ${headerParts.join(', ')}` };
}
}

module.exports = OAuth;
Loading