feat(backend): let a customer change their own name, password and email (#111)
SonarQube Analysis / sonarqube (pull_request) Failing after 12m11s
SonarQube Analysis / sonarqube (pull_request) Failing after 12m11s
Two of the three already existed on the backend and had no caller. PUT /api/customers/me updated the name; POST /api/customers/change-password already demanded the current password and enforced the eight-character minimum. Neither was reachable from the frontend, which is why the gap was easy to miss — the API looked finished. The name endpoint accepted empty values and wrote nulls, letting a customer clear fields registration refuses to let them skip. That is the same rule disagreeing with itself, so it now refuses each by name exactly as registration does. Changing a password now ends other sessions and keeps the one making the change. Reset already deleted every session for the customer, on the reasoning that a password is changed precisely when the old one may be known to someone else — change reached the opposite conclusion for no recorded reason, and a session opened with a leaked password outlived the change meant to lock it out. The current session is spared so the change does not eject the person making it. Changing the email address is new. It asks for the current password, because swapping the address a password reset goes to is how an account is taken over and a live session alone is not enough; that also matches what change-password already required. The address is normalised and validated, an address another account holds is refused with the same 409 as registration, and on success the row is marked unverified and any outstanding verification token superseded — one already sitting in the old inbox must not be able to verify the new address. Two emails then go out, to different places. Verification to the new address, and a notice to the old one naming what the address was changed to. The notice is the only thing that tells a real owner their account was taken, and one that does not say where the address went is nearly useless to someone checking whether it was them. Both sends happen after the row is written, never before, so a change that failed cannot produce mail saying it succeeded. That notice is a sixth template in #92's system, which cost a definition and a default body. The unit tests iterate every template, so its defaults were checked against its own required placeholder without writing a new test. Verified: 199 unit and 208 integration passing. The session test signs in on a second agent, changes the password on the first, and asserts the second is refused while the first still works — the property being claimed rather than the code path being executed. One of my own assertions was wrong on the way: /me answers an unauthenticated caller with 401 and an error body, not an empty one, and the frontend is what turns that into null. Refs #111 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -307,9 +307,20 @@ router.get('/me', requireCustomer, asyncRoute(async (req: Request, res: Response
|
||||
// surface without a caller rather than a path in use.
|
||||
router.put('/me', requireCustomer, asyncRoute(async (req: Request, res: Response) => {
|
||||
const { firstName, lastName } = req.body;
|
||||
// Registration demands both and refuses each by name. Accepting empty values
|
||||
// here would let a customer clear fields they could not have skipped when
|
||||
// signing up, which is the same rule disagreeing with itself.
|
||||
const first = String(firstName ?? '').trim();
|
||||
const last = String(lastName ?? '').trim();
|
||||
if (!first) {
|
||||
return res.status(400).json({ error: 'first name is required' });
|
||||
}
|
||||
if (!last) {
|
||||
return res.status(400).json({ error: 'last name is required' });
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE customers SET first_name = $1, last_name = $2 WHERE id = $3 RETURNING *`,
|
||||
[String(firstName ?? '').trim() || null, String(lastName ?? '').trim() || null, req.customerId]
|
||||
[first, last, req.customerId]
|
||||
);
|
||||
res.json(publicCustomer(rows[0]));
|
||||
}));
|
||||
@@ -326,9 +337,89 @@ router.post('/change-password', requireCustomer, asyncRoute(async (req: Request,
|
||||
}
|
||||
const newHash = await bcrypt.hash(newPassword, 12);
|
||||
await pool.query(`UPDATE customers SET password_hash = $1 WHERE id = $2`, [newHash, req.customerId]);
|
||||
|
||||
// Password reset already ends every session, on the reasoning that a password
|
||||
// is changed precisely when the old one may be known to someone else. A
|
||||
// change left the other sessions alive, which is the same reasoning reaching
|
||||
// the opposite conclusion for no recorded reason. The current session is
|
||||
// spared so the change does not eject the person making it.
|
||||
await pool.query(
|
||||
`DELETE FROM customer_sessions WHERE customer_id = $1 AND token <> $2`,
|
||||
[req.customerId, req.cookies?.rd_session ?? '']
|
||||
);
|
||||
|
||||
res.status(204).end();
|
||||
}));
|
||||
|
||||
// Changing the address a password reset goes to is how an account is taken
|
||||
// over, so this asks for the current password exactly as change-password does.
|
||||
// A live session alone is not enough.
|
||||
router.put('/me/email', requireCustomer, asyncRoute(async (req: Request, res: Response) => {
|
||||
const { currentPassword, email } = req.body;
|
||||
|
||||
const normalized = String(email ?? '').toLowerCase().trim();
|
||||
if (!normalized || !isValidEmail(normalized)) {
|
||||
return res.status(400).json({ error: 'a valid email is required' });
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(`SELECT * FROM customers WHERE id = $1`, [req.customerId]);
|
||||
const customer = rows[0];
|
||||
|
||||
if (!(await bcrypt.compare(String(currentPassword ?? ''), customer.password_hash))) {
|
||||
return res.status(401).json({ error: 'current password is incorrect' });
|
||||
}
|
||||
|
||||
if (normalized === customer.email) {
|
||||
return res.status(400).json({ error: 'that is already your email address' });
|
||||
}
|
||||
|
||||
const { rows: taken } = await pool.query(`SELECT id FROM customers WHERE email = $1`, [normalized]);
|
||||
if (taken.length) {
|
||||
return res.status(409).json({ error: 'an account with this email already exists' });
|
||||
}
|
||||
|
||||
// Captured before the update, because it is where the notice has to go.
|
||||
const previousEmail = customer.email;
|
||||
|
||||
await pool.query(
|
||||
`UPDATE customers SET email = $1, email_verified = false WHERE id = $2`,
|
||||
[normalized, req.customerId]
|
||||
);
|
||||
|
||||
// Supersede any outstanding link, so one already sitting in the old inbox
|
||||
// cannot be used to verify the new address.
|
||||
await pool.query(
|
||||
`DELETE FROM customer_tokens WHERE customer_id = $1 AND kind = 'verify_email'`,
|
||||
[req.customerId]
|
||||
);
|
||||
const verifyToken = crypto.randomBytes(24).toString('hex');
|
||||
await pool.query(
|
||||
`INSERT INTO customer_tokens (token, customer_id, kind, expires_at) VALUES ($1, $2, 'verify_email', $3)`,
|
||||
[verifyToken, req.customerId, new Date(Date.now() + 24 * 60 * 60 * 1000)]
|
||||
);
|
||||
|
||||
// Both sends happen after the row is written, never before — the same rule
|
||||
// favoriteAlerts follows, so a change that failed cannot produce mail saying
|
||||
// it succeeded.
|
||||
const verifyUrl = process.env.PUBLIC_URL + '/verify-email?token=' + verifyToken;
|
||||
const verify = renderTemplate('verification', await loadStoredTemplate('verification'), {
|
||||
greeting: greeting(customer.first_name),
|
||||
verifyUrl
|
||||
});
|
||||
sendMail(normalized, verify.subject, verify.html)
|
||||
.catch(err => console.error('verify email send failed', err));
|
||||
|
||||
const notice = renderTemplate('emailChanged', await loadStoredTemplate('emailChanged'), {
|
||||
greeting: greeting(customer.first_name),
|
||||
newEmail: normalized
|
||||
});
|
||||
sendMail(previousEmail, notice.subject, notice.html)
|
||||
.catch(err => console.error('email change notice send failed', err));
|
||||
|
||||
const { rows: updated } = await pool.query(`SELECT * FROM customers WHERE id = $1`, [req.customerId]);
|
||||
res.json(publicCustomer(updated[0]));
|
||||
}));
|
||||
|
||||
router.post('/me/consent', requireCustomer, asyncRoute(async (req: Request, res: Response) => {
|
||||
const consent = !!req.body.marketingConsent;
|
||||
await pool.query(
|
||||
|
||||
Reference in New Issue
Block a user