Skip to content

Commit

Permalink
Merge pull request #4 from watson-developer-cloud/cors-workaround
Browse files Browse the repository at this point in the history
Implement CORS issue workaround for new voices
  • Loading branch information
lpatino10 authored Jan 28, 2020
2 parents a636d45 + 6a5dd8b commit c57b49c
Show file tree
Hide file tree
Showing 6 changed files with 144 additions and 307 deletions.
149 changes: 26 additions & 123 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,117 +1,17 @@
const TextToSpeechV1 = require('ibm-watson/text-to-speech/v1.js');
const {
BearerTokenAuthenticator,
CloudPakForDataAuthenticator,
Cp4dTokenManager,
IamAuthenticator,
IamTokenManager,
} = require('ibm-watson/auth');
const path = require('path');
const express = require('express');
const vcapServices = require('vcap_services');
const app = express();
require('./config/express')(app);

let url = process.env.TEXT_TO_SPEECH_URL;
let authUrl = process.env.TEXT_TO_SPEECH_AUTH_URL;

// Supply the API key for IAM authentication.
let apikey = process.env.TEXT_TO_SPEECH_APIKEY;

// Supply the bearer token + URL for an instance on CPD (see the README for more details).
let bearerToken = process.env.TEXT_TO_SPEECH_BEARER_TOKEN;

// Supply the username + password + URL as an alternative for an instance on CPD.
let username = process.env.TEXT_TO_SPEECH_USERNAME;
let password = process.env.TEXT_TO_SPEECH_PASSWORD;

// On Cloud Foundry, we'll have a VCAP_SERVICES environment variable with credentials.
let vcapCredentials = vcapServices.getCredentials('text_to_speech');

// Create appropriate token manager and client.
// Create Text to Speech client.
let client;
let tokenManager;
if (vcapCredentials || apikey) {
// Choose credentials from VCAP if they exist.
apikey = (vcapCredentials && vcapCredentials.apikey) || apikey;
url = (vcapCredentials && vcapCredentials.url) || url;

try {
tokenManager = new IamTokenManager({ apikey });
client = new TextToSpeechV1({
serviceUrl: url,
authenticator: new IamAuthenticator({ apikey }),
});
} catch (err) {
console.error('Error creating IAM token manager and client: ', err);
}
} else if (username && password && url) {
try {
tokenManager = new Cp4dTokenManager({ username, password, url: authUrl });
client = new TextToSpeechV1({
serviceUrl: url,
disableSslVerification: true,
authenticator: new CloudPakForDataAuthenticator({
username,
password,
url: authUrl,
disableSslVerification: true,
}),
});
} catch (err) {
console.error('Error creating CP4D token manager: ', err);
}
} else if (bearerToken) {
client = new TextToSpeechV1({
serviceUrl: url,
disableSslVerification: true,
authenticator: new BearerTokenAuthenticator({ bearerToken }),
});
try {
client = new TextToSpeechV1({});
} catch (err) {
console.error('Error creating service client: ', err);
}

const getToken = async () => {
let tokenResponse = {};

try {
if (tokenManager) {
const token = await tokenManager.getToken();
tokenResponse = {
...tokenResponse,
accessToken: token,
url,
};
} else if (bearerToken && url) {
tokenResponse = {
...tokenResponse,
accessToken: bearerToken,
url,
};
} else {
tokenResponse = {
...tokenResponse,
error: {
title: 'No valid credentials found',
description:
'Could not find valid credentials for the Text to Speech service.',
statusCode: 401,
},
};
}
} catch (err) {
tokenResponse = {
...tokenResponse,
error: {
title: 'Authentication error',
description:
'There was a problem authenticating with the Text to Speech service.',
statusCode: 400,
},
};
}

return tokenResponse;
};

app.get('/', (_, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
Expand All @@ -120,34 +20,37 @@ app.get('/health', (_, res) => {
res.json({ status: 'UP' });
});

app.get('/api/auth', async (_, res, next) => {
const token = await getToken();

if (token.error) {
console.error(token.error);
next(token.error);
} else {
return res.json(token);
}
});

app.get('/api/voices', async (_, res, next) => {
try {
const { result } = await client.listVoices();
return res.json(result);
} catch (error) {
console.error(error);
} catch (err) {
console.error(err);
if (!client) {
error.statusCode = 401;
error.description =
err.statusCode = 401;
err.description =
'Could not find valid credentials for the Text to Speech service.';
error.title = 'Invalid credentials';
err.title = 'Invalid credentials';
}
next(error);
next(err);
}
});

app.pos;
app.get('/api/synthesize', async (req, res, next) => {
try {
const { result } = await client.synthesize(req.query);
result.pipe(res);
} catch (err) {
console.error(err);
if (!client) {
err.statusCode = 401;
err.description =
'Could not find valid credentials for the Text to Speech service.';
err.title = 'Invalid credentials';
}
next(err);
}
});

// error-handler settings for all other routes
require('./config/error-handler')(app);
Expand Down
Loading

0 comments on commit c57b49c

Please sign in to comment.