How can i create a simple reset password using next auth Credential provider with mongo db i have user schema like this
const userSchema = new mongoose.Schema<UserSchemaType>(
{
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
img: { type: String, required: true },
isAdmin: { type: Boolean, required: true, default: false },
},
{
timestamps: true,
}
);
my next auth look like this
providers: [
CredentialsProvider({
async authorize(credentials) {
await db.connect();
const user = await User.findOne({
email: credentials.email,
});
if (user && bcryptjs.compareSync(credentials.password, user.password)) {
return {
_id: user._id,
name: user.name,
email: user.email,
image: user.img,
isAdmin: user.isAdmin,
};
}
throw new Error('Invalid email or password');
},
}),
],
});
is there a simple example for implementing reset password with the next auth
I do not think that next-auth provides any special functionality for this. You have to implement a general flow. User should have Forgot Password button and you send the request to next.js api backend. "pages/api/forgot.js"
import jwt from "jsonwebtoken";
handler.post(async (req, res) => {
try {
await db.connectDb();
const { email } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ message: "Email does not exist." });
}
// create token with jwt
const user_token =jwt.sign(user._id, process.env.RESET_TOKEN_SECRET, {
expiresIn: "1h",
});
// you should create "pages/reset/[token].js" dynamic page
const url = `${process.env.BASE_URL}/reset/${user_id}`;
// you need to implement sedning email maybe using `nodemailer`
// create this function for your case
sendEmail(email, url, "Reset your password.");
// you should disconnect the db here
res.json({
message: "An email has been sent to you to reset your password.",
});
} catch (error) {
res.status(500).json({ message: error.message });
}
});
"pages/reset/[token].js" page you will have a form that has 2 inputs. "password" and "confirm Password". Once user clicks on reset button, you sent the password and decrypted token (we created the token with user_id) to another backend api: "pages/api/reset.js". this backend will take user_id and password, query the db and change the password
handler.put(async (req, res) => {
try {
await db.connectDb();
const { user_id, password } = req.body;
const user = await User.findById(user_id);
if (!user) {
return res.status(400).json({ message: "Account does not exist." });
}
const hashedPassword = await bcrypt.hash(password, 12);
await user.updateOne({
password: hashedPassword,
});
res.status(200).json({ email: user.email });
// you should disconnect the db
} catch (error) {
res.status(500).json({ message: error.message });
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With