How to create password back-up system on Node.js
Source: Dev.to
Introduction
Passwords are often forgotten, and forcing users to reset them via email each time can be frustrating. Magic links provide a secure and seamless way to back up passwords. This tutorial shows how to implement a password backup system in Node.js using the auth-verify library.
Installation
npm install auth-verify express
- auth-verify – handles magic‑link generation and verification.
- express – creates the server and routes.
Server Initialization
const express = require('express');
const app = express();
const AuthVerify = require('auth-verify');
const auth = new AuthVerify({
mlSecret: 'super_secret_key', // secret for signing magic links
mlExpiry: '5m', // link expiration time
appUrl: 'http://localhost:3000', // base URL of the app
storeTokens: 'memory' // where to store tokens ('memory' or 'redis')
});
// Configure the magic‑link email sender
auth.magic.sender({
service: 'gmail',
sender: 'yourapp@gmail.com',
pass: 'your_gmail_app_password'
});
Sending a Magic Link
When a user forgets their password, send a magic link to their email address:
app.post('/send-magic-link', async (req, res) => {
const { email } = req.body;
try {
const result = await auth.magic.send(email, {
subject: 'Your Reset Password Link ✨',
html: `
Click below to sign in:
[Login Now]({{link}})` // {{link}} is replaced with a URL like
// http://localhost:3000/auth/verify?token=GENERATED_TOKEN
});
res.json({ success: true, message: 'Magic link sent!', result });
} catch (err) {
console.error(err);
res.status(500).json({ success: false, message: 'Failed to send magic link' });
}
});
Verifying the Magic Link
When the user clicks the link, verify the token and present a password‑reset form:
app.get('/auth/verify', async (req, res) => {
const { token } = req.query; // token extracted from the URL
try {
await auth.magic.verify(token);
res.send(`
Set new password
`);
} catch (err) {
res.status(400).json({ success: false, message: err.message });
}
});
Resetting the Password
Handle the form submission and update the user’s password (implementation depends on your user store):
app.post('/reset-password', (req, res) => {
const { newpassword } = req.body; // new password supplied by the user
// TODO: Save `newpassword` for the corresponding user in your database
res.json({ success: true, message: 'Password has been updated.' });
});
Conclusion
Using auth-verify and magic links, users can reset their passwords without needing to remember the old one. This approach offers a user‑friendly and secure password backup system for Node.js applications.