fastify-passport
fastify-passport copied to clipboard
How to print custom error message instead of default "Unauthorized" or "Bad request"
Prerequisites
- [X] I have written a descriptive issue title
- [X] I have searched existing issues to ensure the issue has not already been raised
Issue
Hi,
I'm trying to setup @fastify/passport with @fastify/cookie and @fastify/secure-session. I'm using the local strategy passport-local
After many hits and trials, I was able to set up everything, now only one issue, how to send a custom error message instead of "Unauthorized".
Below is my code for LocalStrategy
fastifyPassport.use("local", new LocalStrategy({
usernameField: "email",
passwordField: "password"
}, async (email, password, done) => {
if (!email || !password) {
return done(null, false, { message: "Missing email or password" });
}
await methods.FindRecord("users", { email }).then(user => {
if (!user) {
return done(null, false, { message: "User not found", status: 404 });
}
bcrypt.compare(password, user.password, (err, isValid) => {
if (err) {
return done(err);
}
if (!isValid) {
return done(null, false, { message: "Invalid password", status: 401 });
}
return done(null, user);
});
});
}));
fastifyPassport.registerUserSerializer(async (user, request) => {
return user;
})
fastifyPassport.registerUserDeserializer(async (user, request,) => {
return user
});
This is code in fastify /login route
fastify.post("/login", {
preValidation: fastifyPassport.authenticate("local", {
failureMessage: 'Invalid email or password',
successMessage: 'Logged in successfully',
authInfo: false,
})
}, async (request, reply) => {
reply.send({ message: "Logged in successfully from new response" });
})
In response i can only see "Unauthorized" instead of any other message when password/username is wrong, I can see
my custom message Logged in successfully from new response only after credentials are correnct. Any help or guidance on this?
I tried fastify-flash but that was giving me some kind of decorator error.
Thanks for reporting!
Can you provide steps to reproduce? We often need a reproducible example, e.g. some code that allows someone else to recreate your problem by just copying and pasting it. If it involves more than a couple of different file, create a new repository on GitHub and add a link to that.