Skip to content

Commit 402ee8d

Browse files
yachikadevShantKhatri
authored andcommitted
refactor(auth): replace any-cast authenticate fallback with typed appauthenticate decorator in cards, event, and nfc routes (#626)
* refactor(auth): replace any-cast authenticate fallback with typed app.authenticate decorator in cards, event, and nfc routes (closes #594) * Update cards.ts Signed-off-by: Yachika Sharma <shakuntalaramphalsharma@gmail.com> * Update event.ts Signed-off-by: Yachika Sharma <shakuntalaramphalsharma@gmail.com> * Update nfc.ts Signed-off-by: Yachika Sharma <shakuntalaramphalsharma@gmail.com> * Update cards.ts Signed-off-by: Yachika Sharma <shakuntalaramphalsharma@gmail.com> --------- Signed-off-by: Yachika Sharma <shakuntalaramphalsharma@gmail.com>
1 parent 9a88b0c commit 402ee8d

3 files changed

Lines changed: 19 additions & 41 deletions

File tree

apps/backend/src/routes/cards.ts

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { handleDbError } from '../utils/error.util.js';
33
import { hashIp } from '../utils/refreshToken';
44
import { createCardSchema ,updateCardSchema, addPlatformLinkSchema} from '../validations/card.validation';
55

6-
import type { CardResponse, UpdateCardBody, UpdatedCardResponse } from '../services/cardService';
6+
import type { CardResponse, UpdateCardBody,UpdatedCardResponse } from '../services/cardService';
77
import type { Card } from '@devcard/shared/src/types.js';
88
import type { CardVisibility } from '@prisma/client';
99
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
@@ -62,15 +62,9 @@ function hasErrorCode(
6262
}
6363

6464
export async function cardRoutes(app: FastifyInstance): Promise<void> {
65-
app.addHook('preHandler', async (request, reply) => {
66-
const server = request.server;
67-
if (typeof server?.authenticate === 'function') { await server.authenticate(request, reply); return }
68-
if (typeof app.authenticate === 'function') { await app.authenticate(request, reply); return }
69-
try { await request.jwtVerify() } catch (_e) { reply.status(401).send({ error: 'Unauthorized' }) }
70-
});
71-
65+
7266
// ─── List Cards ───
73-
app.get('/', async (request: FastifyRequest, reply: FastifyReply): Promise<CardResponse[] | void> => {
67+
app.get('/', {preHandler: [(req, reply) => app.authenticate(req, reply)] },async (request: FastifyRequest, reply: FastifyReply): Promise<CardResponse[] | void> => {
7468
const userId = request.user.id;
7569
try {
7670
return await cardService.listCards(app, userId)
@@ -80,7 +74,7 @@ export async function cardRoutes(app: FastifyInstance): Promise<void> {
8074
});
8175

8276
// ─── Creates Card ───
83-
app.post('/', async (request: FastifyRequest<{ Body: CreateCardBody }>, reply: FastifyReply): Promise<Card | void> => {
77+
app.post<{ Body: CreateCardBody }>('/', { preHandler: [(req, reply) => app.authenticate(req, reply)]}, async (request, reply): Promise<Card | void> => {
8478
const userId = request.user.id;
8579
const parsed = createCardSchema.safeParse(request.body);
8680

@@ -99,7 +93,7 @@ export async function cardRoutes(app: FastifyInstance): Promise<void> {
9993

10094
// ─── Update Card ───
10195

102-
app.put('/:id', async (request: FastifyRequest<{ Params: CardParams; Body: UpdateCardBody }>, reply: FastifyReply): Promise<UpdatedCardResponse> => {
96+
app.put<{ Params: CardParams; Body: UpdateCardBody }>('/:id', {preHandler: [(req, reply) => app.authenticate(req, reply)] }, async (request, reply): Promise<UpdatedCardResponse> => {
10397
const userId = request.user.id;
10498
const { id } = request.params;
10599

@@ -117,7 +111,7 @@ export async function cardRoutes(app: FastifyInstance): Promise<void> {
117111

118112
// ─── Delete Card ───
119113

120-
app.delete('/:id', async (request: FastifyRequest<{ Params: CardParams }>, reply: FastifyReply): Promise<void> => {
114+
app.delete<{ Params: CardParams }>('/:id', { preHandler: [(req, reply) => app.authenticate(req, reply)]}, async (request, reply): Promise<void> => {
121115
const userId = request.user.id;
122116
const { id } = request.params;
123117

@@ -139,7 +133,7 @@ export async function cardRoutes(app: FastifyInstance): Promise<void> {
139133
});
140134

141135
// ─── Set Default Card ───
142-
app.put('/:id/default', async (request: FastifyRequest<{ Params: CardParams }>, reply: FastifyReply): Promise<object | void> => {
136+
app.put<{ Params: CardParams }>('/:id/default', {preHandler: [(req, reply) => app.authenticate(req, reply)]}, async (request, reply): Promise<object | void> => {
143137
const userId = request.user.id;
144138
const { id } = request.params;
145139

apps/backend/src/routes/event.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ type EventWithAttendees = {
5858
}[];
5959
}
6060

61-
export async function eventRoutes(app:FastifyInstance): Promise<void> {
61+
export async function eventRoutes(app:FastifyInstance): Promise<void> {
6262
app.post<{Body: { name: string; description?: string; startDate: string; location: string; endDate: string; isPublic?: boolean; }}>('/', { preHandler: [(req, reply) => app.authenticate(req, reply)] }, async (request, reply) => {
6363
const userId = request.user.id;
6464
const parsed = createEventSchema.safeParse(request.body);
@@ -271,4 +271,4 @@ export async function eventRoutes(app:FastifyInstance): Promise<void> {
271271

272272
return response;
273273
})
274-
}
274+
}

apps/backend/src/routes/nfc.ts

Lines changed: 10 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
21
import { z } from 'zod';
32

3+
import type { FastifyInstance} from 'fastify';
4+
45
type NfcPayloadResponse = {
56
type: 'URI';
67
payload: string;
@@ -10,33 +11,16 @@ const nfcQuerySchema = z.object({
1011
card: z.string().uuid('Invalid card ID format').optional(),
1112
});
1213

13-
export async function nfcRoutes(app: FastifyInstance) {
14-
app.addHook('preHandler', async (request, reply) => {
15-
const server = request.server as any;
16-
if (typeof server?.authenticate === 'function') {
17-
await server.authenticate(request, reply);
18-
return;
19-
}
20-
if (typeof (app as any).authenticate === 'function') {
21-
await (app as any).authenticate(request, reply);
22-
return;
23-
}
24-
try {
25-
await request.jwtVerify();
26-
} catch (e) {
27-
reply.status(401).send({ error: 'Unauthorized' });
28-
}
29-
});
14+
export async function nfcRoutes(app: FastifyInstance): Promise<void> {
15+
3016

3117
// GET /api/nfc/payload — returns NDEF URI payload for user's default DevCard URL
3218
// GET /api/nfc/payload?card=<cardId> — returns payload for a specific card
33-
app.get(
34-
'/payload',
35-
async (
36-
request: FastifyRequest<{ Querystring: { card?: string } }>,
37-
reply: FastifyReply
38-
) => {
39-
const userId = (request.user as any).id;
19+
app.get<{ Querystring: { card?: string } }>(
20+
'/payload',
21+
{ preHandler: [(req, reply) => app.authenticate(req, reply)] },
22+
async (request, reply) => {
23+
const userId = request.user.id;
4024

4125
// Validate query params with Zod
4226
const parseResult = nfcQuerySchema.safeParse(request.query);
@@ -111,4 +95,4 @@ const payloadUrl = `${process.env.PUBLIC_APP_URL}/${safeUsername}${
11195
return reply.send(response);
11296
}
11397
);
114-
}
98+
}

0 commit comments

Comments
 (0)