All files / src/plugins authenticate.ts

88.88% Statements 8/9
100% Branches 2/2
100% Functions 2/2
88.88% Lines 8/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32                            7x   7x 15x 15x 4x     11x 11x             7x  
import fp from "fastify-plugin";
import type { FastifyInstance, FastifyRequest, FastifyReply } from "fastify";
import { verifyAccessToken, type AccessTokenPayload } from "../lib/jwt.js";
 
declare module "fastify" {
  interface FastifyInstance {
    authenticate: (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
  }
  interface FastifyRequest {
    user: AccessTokenPayload;
  }
}
 
async function authenticatePlugin(app: FastifyInstance) {
  app.decorateRequest("user", null as unknown as AccessTokenPayload);
 
  app.decorate("authenticate", async (request: FastifyRequest, reply: FastifyReply) => {
    const header = request.headers.authorization;
    if (!header?.startsWith("Bearer ")) {
      return reply.status(401).send({ error: "Missing or invalid authorization header" });
    }
 
    try {
      request.user = verifyAccessToken(header.slice(7));
    } catch {
      return reply.status(401).send({ error: "Invalid or expired token" });
    }
  });
}
 
export const authenticate = fp(authenticatePlugin, { name: "authenticate" });