From b45a88d6dba5731156209ef447e5fd4846bb8eb1 Mon Sep 17 00:00:00 2001 From: Oliver Eyton-Williams Date: Fri, 12 Jul 2024 18:03:30 +0200 Subject: [PATCH] refactor(api): use reject user-agents early (#55491) --- api/src/routes/user.test.ts | 11 +++++++++++ api/src/routes/user.ts | 28 +++++++++++++++------------- 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/api/src/routes/user.test.ts b/api/src/routes/user.test.ts index e2fae8cd6f7..d0c71e34cf0 100644 --- a/api/src/routes/user.test.ts +++ b/api/src/routes/user.test.ts @@ -1227,6 +1227,17 @@ Thanks and regards, }); describe('GET', () => { + test('returns 400 status code if the user agent is blocked', async () => { + const response = await superGet( + '/api/users/get-public-profile?username=public-user' + ).set('User-Agent', 'curl'); + + expect(response.text).toBe( + 'This endpoint is no longer available outside of the freeCodeCamp ecosystem' + ); + expect(response.statusCode).toBe(400); + }); + test('returns 400 status code if the username param is missing', async () => { const res = await superGet('/api/users/get-public-profile'); // TODO(Post-MVP): return something more informative diff --git a/api/src/routes/user.ts b/api/src/routes/user.ts index c0475d0d6ff..7f94f6e9352 100644 --- a/api/src/routes/user.ts +++ b/api/src/routes/user.ts @@ -653,21 +653,23 @@ export const userPublicGetRoutes: FastifyPluginCallbackTypebox = ( fastify.get( '/api/users/get-public-profile', { - schema: schemas.getPublicProfile + schema: schemas.getPublicProfile, + onRequest: (req, reply, done) => { + const userAgent = req.headers['user-agent']; + + if ( + userAgent && + blockedUserAgentParts.some(ua => userAgent.toLowerCase().includes(ua)) + ) { + void reply.code(400); + void reply.send( + 'This endpoint is no longer available outside of the freeCodeCamp ecosystem' + ); + } + done(); + } }, async (req, reply) => { - const userAgent = req.headers['user-agent']; - - if ( - userAgent && - blockedUserAgentParts.some(ua => userAgent.toLowerCase().includes(ua)) - ) { - void reply.code(400); - return reply.send( - 'This endpoint is no longer available outside of the freeCodeCamp ecosystem' - ); - } - // TODO(Post-MVP): look for duplicates unless we can make username unique in the db. const user = await fastify.prisma.user.findFirst({ where: { username: req.query.username }