From 03e05b5154a337f3c3da46c5c5c73b94aa52dc7b Mon Sep 17 00:00:00 2001
From: Julian Lam <julian@nodebb.org>
Date: Wed, 22 Mar 2023 17:08:37 -0400
Subject: [PATCH] fix: #9397, trash the active session on account lockout, if
 there is one

---
 src/controllers/authentication.js | 21 ++++++++++++++-------
 1 file changed, 14 insertions(+), 7 deletions(-)

diff --git a/src/controllers/authentication.js b/src/controllers/authentication.js
index 47a06ffe42..21b067f58e 100644
--- a/src/controllers/authentication.js
+++ b/src/controllers/authentication.js
@@ -397,6 +397,9 @@ authenticationController.onSuccessfulLogin = async function (req, uid) {
 	}
 };
 
+const destroyAsync = util.promisify((req, callback) => req.session.destroy(callback));
+const logoutAsync = util.promisify((req, callback) => req.logout(callback));
+
 authenticationController.localLogin = async function (req, username, password, next) {
 	if (!username) {
 		return next(new Error('[[error:invalid-username]]'));
@@ -431,9 +434,17 @@ authenticationController.localLogin = async function (req, username, password, n
 			return next(new Error('[[error:local-login-disabled]]'));
 		}
 
-		const passwordMatch = await user.isPasswordCorrect(uid, password, req.ip);
-		if (!passwordMatch) {
-			return next(new Error('[[error:invalid-login-credentials]]'));
+		try {
+			const passwordMatch = await user.isPasswordCorrect(uid, password, req.ip);
+			if (!passwordMatch) {
+				return next(new Error('[[error:invalid-login-credentials]]'));
+			}
+		} catch (e) {
+			if (req.loggedIn) {
+				await logoutAsync(req);
+				await destroyAsync(req);
+			}
+			throw e;
 		}
 
 		next(null, userData, '[[success:authentication-successful]]');
@@ -442,9 +453,6 @@ authenticationController.localLogin = async function (req, username, password, n
 	}
 };
 
-const destroyAsync = util.promisify((req, callback) => req.session.destroy(callback));
-const logoutAsync = util.promisify((req, callback) => req.logout(callback));
-
 authenticationController.logout = async function (req, res, next) {
 	if (!req.loggedIn || !req.sessionID) {
 		res.clearCookie(nconf.get('sessionKey'), meta.configs.cookie.get());
@@ -456,7 +464,6 @@ authenticationController.logout = async function (req, res, next) {
 	try {
 		await user.auth.revokeSession(sessionID, uid);
 		await logoutAsync(req);
-
 		await destroyAsync(req);
 		res.clearCookie(nconf.get('sessionKey'), meta.configs.cookie.get());