2022-01-06 12:19:21 -08:00
|
|
|
const strava = require('../shared/strava.js');
|
2022-01-04 00:39:45 -08:00
|
|
|
|
2022-01-03 08:38:07 -08:00
|
|
|
module.exports = async function (context, req) {
|
2022-01-04 00:39:45 -08:00
|
|
|
context.log('JavaScript HTTP trigger function processed a request.');
|
2022-01-06 12:19:21 -08:00
|
|
|
// strava example:
|
|
|
|
// https://www.strava.com/oauth/authorize?client_id=76033&response_type=code&redirect_uri=https://ohmyposh.dev/api/auth&approval_prompt=force&scope=read,activity:read&state=strava
|
2022-01-10 08:39:41 -08:00
|
|
|
const code = (req.query.code || req.query._code || (req.body && req.body.code));
|
|
|
|
const segment = (req.query.state || (req.body && req.body.state));
|
|
|
|
let tokens = {
|
|
|
|
access_token: '',
|
|
|
|
refresh_token: '',
|
|
|
|
expires_in: '',
|
|
|
|
};
|
2022-01-04 00:40:31 -08:00
|
|
|
try {
|
2022-01-06 12:19:21 -08:00
|
|
|
if (!code || !segment) {
|
2022-01-09 04:53:14 -08:00
|
|
|
context.log(`Issue processing request: missing code (${code}) or segment (${segment})`);
|
2022-01-10 08:39:41 -08:00
|
|
|
redirect(context, segment, tokens, 'missing code or segment');
|
2022-01-04 00:40:31 -08:00
|
|
|
return;
|
|
|
|
}
|
2022-01-03 08:38:07 -08:00
|
|
|
|
2022-01-06 12:19:21 -08:00
|
|
|
switch (segment) {
|
|
|
|
case "strava":
|
2022-01-10 08:39:41 -08:00
|
|
|
tokens = await strava.getStravaToken(code);
|
2022-01-06 12:19:21 -08:00
|
|
|
break;
|
|
|
|
default:
|
2022-01-09 04:53:14 -08:00
|
|
|
context.log(`Unknown segment: ${segment}`);
|
2022-01-10 08:39:41 -08:00
|
|
|
redirect(context, segment, tokens, `Unknown segment: ${segment}`);
|
2022-01-06 12:19:21 -08:00
|
|
|
return;
|
2022-01-04 00:40:31 -08:00
|
|
|
}
|
|
|
|
|
2022-01-10 08:39:41 -08:00
|
|
|
redirect(context, segment, tokens, '');
|
2022-01-04 00:40:31 -08:00
|
|
|
} catch (error) {
|
2022-01-10 08:39:41 -08:00
|
|
|
context.log(`Error: ${error.stack}`);
|
2022-01-10 12:17:57 -08:00
|
|
|
let buff = Buffer.from(error.stack);
|
2022-01-10 08:39:41 -08:00
|
|
|
let message = buff.toString('base64');
|
|
|
|
redirect(context, segment, tokens, message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function redirect(context, segment, tokens, error) {
|
|
|
|
const url = `${process.env['DOCS_LOCATION']}/docs/auth?segment=${segment}&access_token=${tokens.access_token}&refresh_token=${tokens.refresh_token}&expires_in=${tokens.expires_in}&error=${error}`;
|
|
|
|
context.res = {
|
|
|
|
status: 302,
|
|
|
|
headers: {
|
|
|
|
Location: url
|
|
|
|
},
|
|
|
|
body: {}
|
2022-01-04 00:40:31 -08:00
|
|
|
}
|
2022-01-10 08:39:41 -08:00
|
|
|
context.done();
|
2022-01-03 08:38:07 -08:00
|
|
|
}
|