admin管理员组

文章数量:1125958

I'm implementing a Fastify authentication system using @fastify/passport with a LocalStrategy. Below is the auth plugin that handles user serialization, deserialization, and the local strategy configuration.

import fp from "fastify-plugin";
import fastifyPassport from "@fastify/passport";
import LocalStrategy from "passport-local";
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import { User } from "./types";
export default fp(async function auth(fastify: FastifyInstance) {
  const { store, httpErrors } = fastify;
  fastifyPassport.registerUserSerializer(async (user: { id: number }, request) => {
    if (!user?.id) return httpErrors.notFound("User ID is missing");
    return user.id;
  });
  fastifyPassport.registerUserDeserializer(async (id: number, request) => {
    try {
      const user: User[] = await store("users").where({ id }).limit(1);
      if (!user || user?.length < 1) return null;
      ....
      return sessionUser
    } catch (error) {
      console.error("Deserialization error", error);
      return null;
    }
  });

  async function handleUserRecovery(req: FastifyRequest, email: string, password: string) {
    try {
      const user: User[] = await store("users").where({ email }).limit(1);
      if (!user || user?.length < 1) return false;
      ...
      return sessionUser;
    } catch (err) {
      console.error("Error fetching user:", err);
      return false;
    }
  }
  fastifyPassport.use(
    "local",
    new LocalStrategy(
      {
        passReqToCallback: true,
        usernameField: "email",
      },
      handleUserRecovery
    )
  );

  await fastify.register(fastifyPassport.initialize());
  await fastify.register(fastifyPassport.secureSession());
}, {
  dependencies: ["fastify-env", "fastify-session", "fastify-store", "fastify-sensible"],
});

The issue arises when I try to access a protected route like the following:

fastify.route({
  method: "GET",
  url: "/protected",
  preValidation: fastifyPassport.authenticate("local", { authInfo: false }),
  handler: async (req: FastifyRequest<{ Body: { email: string; password: string } }>, res: FastifyReply) => {
    return res.send({ msg: "ok" });
  },
});

When calling this route, I always receive the following error:

Attempted to send payload of invalid type 'object'. Expected a string or Buffer.

Moreover, in the server logs, I notice two incoming requests being logged, as if the request is being processed twice. Here is the detailed log output:

responseTime: 73.25737500190735
[01:00:23.679] ERROR (33597): server closing with error
err: {
  "type": "FastifyError",
  "message": "Attempted to send payload of invalid type 'object'. Expected a string or Buffer.",
  "stack": FastifyError: Attempted to send payload of invalid type 'object'. Expected a string or Buffer.
}

I expected the route to authenticate users based on email and password, and return a response like { msg: "ok" }. Instead, I get an error saying:

Attempted to send payload of invalid type 'object'. Expected a string or Buffer.

In the logs. I also noticed that the request seems to be processed twice, which is unexpected.

本文标签: