wishlist-app/src/api/config/auth.ts
Benny Samir Hierl d085d4b762 allow wishlist to be not public
Signed-off-by: Benny Samir Hierl <bennysamir@posteo.de>
2022-02-12 22:26:38 +01:00

36 lines
1 KiB
TypeScript

import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'
import { notAuthorized } from './errors'
const error = notAuthorized('Unauthorized')
export default {
init: async (app: FastifyInstance) => {
if (!process.env.API_KEY) {
throw new Error('ENV API_KEY is not set!')
}
app.decorateRequest('isAuthenticated', false)
app.addHook(
'onRequest',
(request: FastifyRequest, reply: FastifyReply, done) => {
if (request.headers.authorization) {
const authHeader = request.headers.authorization.split(' ')
request.log.debug(authHeader)
if (
authHeader[0] &&
authHeader[0].trim().toLowerCase() === 'api-key' &&
authHeader[1]
) {
if (authHeader[1] === process.env.API_KEY) {
request.isAuthenticated = true
}
}
}
if (reply.context.config.protected && !request.isAuthenticated) {
done(error)
} else {
done()
}
}
)
},
}