1 import express from 'express'; 2 import bcrypt from 'bcrypt'; 3 import { db } from './db.js'; 4 import { mailer } from './mailer.js'; 5 6 const router = express.Router(); 7 8 router.post('/password/forgot', async (req, res) => { 9 const user = await db.user.findUnique({ where: { email: req.body.email } }); 10 11 if (!user) { 12 return res.status(404).json({ error: 'No account uses this email' }); 13 } 14 15 const token = Math.random().toString(36).slice(2); 16 17 await db.user.update({ 18 where: { id: user.id }, 19 data: { resetToken: token, resetExpiresAt: new Date(Date.now() + 60 * 60 * 1000) }, 20 }); 21 22 await mailer.send(user.email, 'Reset your password', `https://shop.example.com/reset?email=${encodeURIComponent(user.email)}&token=${token}`); 23 24 res.json({ message: 'Check your inbox for a reset link' }); 25 }); 26 27 router.post('/password/reset', async (req, res) => { 28 const { email, token, password } = req.body; 29 30 if (typeof password !== 'string' || password.length < 12) { 31 return res.status(422).json({ error: 'Use at least 12 characters' }); 32 } 33 34 const user = await db.user.findFirst({ 35 where: { email, resetExpiresAt: { gt: new Date() } }, 36 }); 37 38 if (!user || user.resetToken !== token) { 39 return res.status(400).json({ error: 'This link is not valid or has expired' }); 40 } 41 42 await db.user.update({ 43 where: { id: user.id }, 44 data: { passwordHash: await bcrypt.hash(password, 12) }, 45 }); 46 47 res.json({ message: 'Your password has been changed' }); 48 }); 49 50 export default router;