Register and Login flow
Register: hash the password and save the user. Login: find the user, check the password against the hash, and if it matches, send back a JWT. Never store plain-text passwords. Use bcrypt to hash them.
import bcrypt from "bcrypt"
import jwt from "jsonwebtoken"
app.post("/register", async (req, res) => {
const { email, password } = req.body
const hash = await bcrypt.hash(password, 10)
await db.users.create({ email, password: hash })
res.status(201).json({ message: "Registered" })
})
app.post("/login", async (req, res) => {
const { email, password } = req.body
const user = await db.users.findByEmail(email)
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ error: "Invalid credentials" })
}
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: "1h" })
res.json({ token })
})