Skip to content

Commit

Permalink
feat(server): add HTTP API key middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
louistiti committed Jan 18, 2022
1 parent d10a7fa commit cdf4149
Show file tree
Hide file tree
Showing 10 changed files with 53 additions and 34 deletions.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import getDownloads from '@/api/downloads/get'
import getDownloads from '@/core/http-server/api/downloads/get'

const downloadsPlugin = async (fastify, options) => {
// Get downloads to download module content
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { version } from '@@/package.json'
import log from '@/helpers/log'

const getInfo = async (fastify, options) => {
fastify.get(`/${options.apiVersion}/info`, (_request, reply) => {
fastify.get(`/${options.apiVersion}/info`, (request, reply) => {
log.title('GET /info')

const message = 'Information pulled.'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import getInfo from '@/api/info/get'
import getInfo from '@/core/http-server/api/info/get'

const infoPlugin = async (fastify, options) => {
// Get information to init client
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const corsMidd = async (_request, reply) => {
const corsMidd = async (request, reply) => {
// Allow only a specific client to request to the API (depending of the env)
if (process.env.LEON_NODE_ENV !== 'production') {
reply.header(
Expand Down
12 changes: 12 additions & 0 deletions server/src/core/http-server/plugins/key.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const keyMidd = async (request, reply) => {
const apiKey = request.headers['x-api-key']
if (!apiKey || apiKey !== process.env.LEON_HTTP_API_KEY) {
reply.statusCode = 401
reply.send({
message: 'Unauthorized, please check the HTTP API key is correct',
success: false
})
}
}

export default keyMidd
File renamed without changes.
63 changes: 35 additions & 28 deletions server/src/core/server.js → server/src/core/http-server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import Brain from '@/core/brain'
import Asr from '@/core/asr'
import Stt from '@/stt/stt'
import Tts from '@/tts/tts'
import corsMidd from '@/plugins/cors'
import otherMidd from '@/plugins/other'
import infoPlugin from '@/api/info/index'
import downloadsPlugin from '@/api/downloads/index'
import corsMidd from '@/core/http-server/plugins/cors'
import otherMidd from '@/core/http-server/plugins/other'
import keyMidd from '@/core/http-server/plugins/key'
import infoPlugin from '@/core/http-server/api/info'
import downloadsPlugin from '@/core/http-server/api/downloads'
import log from '@/helpers/log'
import date from '@/helpers/date'

Expand All @@ -27,10 +28,10 @@ let httpServer = { }
/**
* Generate packages routes
*/
const generatePackagesRoutes = () => {
const generatePackagesRoutes = (instance) => {
// Dynamically expose Leon modules over HTTP
endpoints.forEach((endpoint) => {
fastify.route({
instance.route({
method: endpoint.method,
url: endpoint.route,
async handler (request, reply) {
Expand Down Expand Up @@ -99,7 +100,7 @@ const generatePackagesRoutes = () => {
...responseData,
speeches: e.speeches,
executionTime: e.executionTime,
error: e.obj.message,
message: e.obj.message,
success: false
})
}
Expand Down Expand Up @@ -215,7 +216,7 @@ const bootstrap = async () => {

// Render the web app
fastify.register(fastifyStatic, {
root: join(__dirname, '..', '..', '..', 'app', 'dist'),
root: join(__dirname, '../../../../app/dist'),
prefix: '/'
})
fastify.get('/', (request, reply) => {
Expand All @@ -225,28 +226,34 @@ const bootstrap = async () => {
fastify.register(infoPlugin, { apiVersion })
fastify.register(downloadsPlugin, { apiVersion })

fastify.post('/core/query', async (request, reply) => {
const { query } = request.body
fastify.register((instance, opts, next) => {
instance.addHook('preHandler', keyMidd)

try {
const data = await nlu.process(query, { mute: true })
instance.post('/core/query', async (request, reply) => {
const { query } = request.body

reply.send({
...data,
success: true
})
} catch (e) {
reply.statusCode = 500
reply.send({
error: e.message,
success: false
})
try {
const data = await nlu.process(query, { mute: true })

reply.send({
...data,
success: true
})
} catch (e) {
reply.statusCode = 500
reply.send({
message: e.message,
success: false
})
}
})

if (process.env.LEON_PACKAGES_OVER_HTTP === 'true') {
generatePackagesRoutes(instance)
}
})

if (process.env.LEON_PACKAGES_OVER_HTTP === 'true') {
generatePackagesRoutes()
}
next()
})

httpServer = fastify.server

Expand All @@ -262,7 +269,7 @@ const bootstrap = async () => {
*/
server.init = async () => {
fastify.addHook('onRequest', corsMidd)
fastify.addHook('onRequest', otherMidd)
fastify.addHook('preValidation', otherMidd)

log.title('Initialization')
log.success(`The current env is ${process.env.LEON_NODE_ENV}`)
Expand All @@ -284,7 +291,7 @@ server.init = async () => {

// Train modules expressions
try {
await nlu.loadModel(join(__dirname, '../data/leon-model.nlp'))
await nlu.loadModel(join(__dirname, '../../data/leon-model.nlp'))
} catch (e) {
log[e.type](e.obj.message)
}
Expand Down
2 changes: 1 addition & 1 deletion server/src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import dotenv from 'dotenv'

import server from '@/core/server'
import server from '@/core/http-server/server'

(async () => {
dotenv.config()
Expand Down
2 changes: 1 addition & 1 deletion test/unit/server/core/server.spec.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import net from 'net'
import { EventEmitter } from 'events'

import Server from '@/core/server'
import Server from '@/core/http-server/server'

describe('server', () => {
describe('constructor()', () => {
Expand Down

0 comments on commit cdf4149

Please sign in to comment.