Add authentication to speech svc endpoint

This commit is contained in:
Hongbo Wu 2022-08-18 19:16:40 +08:00
parent 401633eda6
commit 576318fcbe
2 changed files with 24 additions and 8 deletions

View file

@ -7,6 +7,7 @@ import { synthesizeTextToSpeech } from '../../utils/textToSpeech'
import { Speech, SpeechState } from '../../entity/speech'
import { UserPersonalization } from '../../entity/user_personalization'
import { buildLogger } from '../../utils/logger'
import { getClaimsByToken } from '../../utils/auth'
const logger = buildLogger('app.dispatch')
@ -16,6 +17,16 @@ export function speechServiceRouter() {
router.options('/', cors<express.Request>({ ...corsConfig, maxAge: 600 }))
// eslint-disable-next-line @typescript-eslint/no-misused-promises
router.post('/', async (req, res) => {
logger.info('Speech svc request', {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
body: req.body,
})
const token = req.query.token as string
if (!(await getClaimsByToken(token))) {
logger.info('Unauthorized request', { token })
return res.status(200).send('UNAUTHORIZED')
}
const { userId, pageId } = req.body as {
userId: string
pageId: string

View file

@ -9,9 +9,12 @@ import { buildLogger } from './logger'
import { nanoid } from 'nanoid'
import { google } from '@google-cloud/tasks/build/protos/protos'
import { IntegrationType } from '../entity/integration'
import { promisify } from 'util'
import * as jwt from 'jsonwebtoken'
import View = google.cloud.tasks.v2.Task.View
const logger = buildLogger('app.dispatch')
const signToken = promisify(jwt.sign)
// Instantiates a client.
const client = new CloudTasksClient()
@ -334,24 +337,26 @@ export const enqueueTextToSpeech = async (
userId,
pageId,
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const token = await signToken({ uid: userId }, env.server.jwtSecret, {
expiresIn: '1h',
})
const taskHandlerUrl = `${env.queue.textToSpeechTaskHandlerUrl}?token=${token}`
// If there is no Google Cloud Project Id exposed, it means that we are in local environment
if (env.dev.isLocal || !GOOGLE_CLOUD_PROJECT) {
// Calling the handler function directly.
setTimeout(() => {
axios
.post(env.queue.textToSpeechTaskHandlerUrl, payload)
.catch((error) => {
logger.error(error)
})
axios.post(taskHandlerUrl, payload).catch((error) => {
logger.error(error)
})
}, 0)
return ''
}
const createdTasks = await createHttpTaskWithToken({
project: GOOGLE_CLOUD_PROJECT,
payload,
taskHandlerUrl: env.queue.textToSpeechTaskHandlerUrl,
taskHandlerUrl,
})
if (!createdTasks || !createdTasks[0].name) {