如何在 Node.js 上创建密码备份系统

发布: (2026年1月14日 GMT+8 02:01)
3 min read
原文: Dev.to

Source: Dev.to

介绍

密码经常会被忘记,每次都强制用户通过电子邮件重置会让人感到沮丧。魔法链接提供了一种安全且流畅的密码备份方式。本教程展示了如何在 Node.js 中使用 auth-verify 库实现密码备份系统。

安装

npm install auth-verify express
  • auth-verify – 处理魔法链接的生成和验证。
  • express – 创建服务器和路由。

服务器初始化

const express = require('express');
const app = express();

const AuthVerify = require('auth-verify');
const auth = new AuthVerify({
  mlSecret: 'super_secret_key',   // 用于签名魔法链接的密钥
  mlExpiry: '5m',                // 链接过期时间
  appUrl: 'http://localhost:3000', // 应用的基础 URL
  storeTokens: 'memory'          // 存储令牌的位置('memory' 或 'redis')
});

// 配置魔法链接的邮件发送者
auth.magic.sender({
  service: 'gmail',
  sender: 'yourapp@gmail.com',
  pass: 'your_gmail_app_password'
});

发送魔法链接

当用户忘记密码时,向其邮箱发送魔法链接:

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' });
  }
});

验证魔法链接

用户点击链接后,验证令牌并展示密码重置表单:

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 });
  }
});

重置密码

处理表单提交并更新用户的密码(实现方式取决于你的用户存储):

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.' });
});

结论

使用 auth-verify 和魔法链接,用户可以在不记住旧密码的情况下重置密码。这种方式为 Node.js 应用提供了友好且安全的密码备份系统。

Back to Blog

相关文章

阅读更多 »