diff --git a/src/client.py b/src/client.py index a637d13f..e6b75f2e 100644 --- a/src/client.py +++ b/src/client.py @@ -113,10 +113,12 @@ def createClientBlueprint(wireguardConfigurations: dict[WireguardConfiguration], return ResponseObject(False, "Please provide a valid Email") token = dashboardClients.GenerateClientPasswordResetToken(u.get('ClientID')) + if not token: + return ResponseObject(False, "A reset token was recently sent. Please wait 2 minutes before requesting another.") status, msg = emailSender.send( email, "[WGDashboard | Client] Reset Password", - f"Hi {email}, \n\nIt looks like you're trying to reset your password at {date} \n\nEnter this 6 digits code on the Forgot Password to continue:\n\n{token}\n\nThis code will expire in 30 minutes for your security. If you didn’t request a password reset, you can safely ignore this email—your current password will remain unchanged.\n\nIf you need help, feel free to contact support.\n\nBest regards,\n\nWGDashboard" + f"Hi {email}, \n\nIt looks like you're trying to reset your password at {date} \n\nEnter this reset token on the Forgot Password page to continue:\n\n{token}\n\nThis token will expire in 30 minutes for your security. If you didn’t request a password reset, you can safely ignore this email—your current password will remain unchanged.\n\nIf you need help, feel free to contact support.\n\nBest regards,\n\nWGDashboard" ) return ResponseObject(status, msg) @@ -150,11 +152,9 @@ def createClientBlueprint(wireguardConfigurations: dict[WireguardConfiguration], return ResponseObject(False, "Please provide a valid Email") if not dashboardClients.ValidateClientPasswordResetToken(u.get('ClientID'), token): - return ResponseObject(False, "Verification code is either invalid or expired") + return ResponseObject(False, "Reset token is either invalid or expired") - status, msg = dashboardClients.ResetClientPassword(u.get('ClientID'), password, confirmPassword) - - dashboardClients.RevokeClientPasswordResetToken(u.get('ClientID'), token) + status, msg = dashboardClients.ResetClientPassword(u.get('ClientID'), password, confirmPassword, token) return ResponseObject(status, msg) diff --git a/src/modules/DashboardClients.py b/src/modules/DashboardClients.py index 54ba4802..a66fd927 100644 --- a/src/modules/DashboardClients.py +++ b/src/modules/DashboardClients.py @@ -1,6 +1,6 @@ import datetime import hashlib -import random +import secrets import uuid import bcrypt @@ -305,7 +305,9 @@ class DashboardClients: def GetClientAssignedPeers(self, ClientID): return self.DashboardClientsPeerAssignment.GetAssignedPeers(ClientID) - def ResetClientPassword(self, ClientID, NewPassword, ConfirmNewPassword) -> tuple[bool, str] | tuple[bool, None]: + def ResetClientPassword( + self, ClientID, NewPassword, ConfirmNewPassword, ResetToken + ) -> tuple[bool, str] | tuple[bool, None]: c = self.GetClient(ClientID) if c is None: return False, "Client does not exist" @@ -316,18 +318,36 @@ class DashboardClients: pwStrength, msg = ValidatePasswordStrength(NewPassword) if not pwStrength: return pwStrength, msg + + if not isinstance(ResetToken, str) or not ResetToken or len(ResetToken) > 128: + return False, "Reset token is either invalid or expired" + + tokenDigest = hashlib.sha256(ResetToken.encode("utf-8")).hexdigest() + now = datetime.datetime.now() try: with self.engine.begin() as conn: + tokenClaimed = conn.execute( + self.dashboardClientsPasswordResetLinkTable.update().values({ + "ExpiryDate": now + }).where( + db.and_( + self.dashboardClientsPasswordResetLinkTable.c.ClientID == ClientID, + self.dashboardClientsPasswordResetLinkTable.c.ResetToken == tokenDigest, + self.dashboardClientsPasswordResetLinkTable.c.ExpiryDate > now + ) + ) + ) + if tokenClaimed.rowcount != 1: + return False, "Reset token is either invalid or expired" + conn.execute( self.dashboardClientsTable.update().values({ - "TotpKeyVerified": None, - "TotpKey": pyotp.random_base32(), "Password": bcrypt.hashpw(NewPassword.encode('utf-8'), bcrypt.gensalt()).decode("utf-8"), }).where( self.dashboardClientsTable.c.ClientID == ClientID ) ) - self.logger.log(Message=f"User {ClientID} reset password and TOTP") + self.logger.log(Message=f"User {ClientID} reset password") except Exception as e: self.logger.log(Status="false", Message=f"User {ClientID} reset password failed, reason: {str(e)}") return False, "Reset password failed." @@ -420,11 +440,24 @@ class DashboardClients: if c is None: return False - newToken = str(random.randint(0, 999999)).zfill(6) + newToken = secrets.token_urlsafe(32) + tokenDigest = hashlib.sha256(newToken.encode("utf-8")).hexdigest() + now = datetime.datetime.now() with self.engine.begin() as conn: + recentToken = conn.execute( + self.dashboardClientsPasswordResetLinkTable.select().where( + db.and_( + self.dashboardClientsPasswordResetLinkTable.c.ClientID == ClientID, + self.dashboardClientsPasswordResetLinkTable.c.CreatedDate > now - datetime.timedelta(minutes=2) + ) + ).limit(1) + ).first() + if recentToken: + return False + conn.execute( self.dashboardClientsPasswordResetLinkTable.update().values({ - "ExpiryDate": datetime.datetime.now() + "ExpiryDate": now }).where( db.and_( @@ -435,10 +468,10 @@ class DashboardClients: ) conn.execute( self.dashboardClientsPasswordResetLinkTable.insert().values({ - "ResetToken": newToken, + "ResetToken": tokenDigest, "ClientID": ClientID, - "CreatedDate": datetime.datetime.now(), - "ExpiryDate": datetime.datetime.now() + datetime.timedelta(minutes=30) + "CreatedDate": now, + "ExpiryDate": now + datetime.timedelta(minutes=30) }) ) @@ -446,13 +479,14 @@ class DashboardClients: def ValidateClientPasswordResetToken(self, ClientID, Token): c = self.GetClient(ClientID) - if c is None: + if c is None or not isinstance(Token, str) or not Token or len(Token) > 128: return False + tokenDigest = hashlib.sha256(Token.encode("utf-8")).hexdigest() with self.engine.connect() as conn: t = conn.execute( self.dashboardClientsPasswordResetLinkTable.select().where( db.and_(self.dashboardClientsPasswordResetLinkTable.c.ClientID == ClientID, - self.dashboardClientsPasswordResetLinkTable.c.ResetToken == Token, + self.dashboardClientsPasswordResetLinkTable.c.ResetToken == tokenDigest, self.dashboardClientsPasswordResetLinkTable.c.ExpiryDate > datetime.datetime.now()) ) @@ -460,13 +494,16 @@ class DashboardClients: return t is not None def RevokeClientPasswordResetToken(self, ClientID, Token): + if not isinstance(Token, str) or len(Token) > 128: + return False + tokenDigest = hashlib.sha256(Token.encode("utf-8")).hexdigest() with self.engine.begin() as conn: conn.execute( self.dashboardClientsPasswordResetLinkTable.update().values({ "ExpiryDate": datetime.datetime.now() }).where( db.and_(self.dashboardClientsPasswordResetLinkTable.c.ClientID == ClientID, - self.dashboardClientsPasswordResetLinkTable.c.ResetToken == Token) + self.dashboardClientsPasswordResetLinkTable.c.ResetToken == tokenDigest) ) ) return True diff --git a/src/static/client/src/views/forgotPassword.vue b/src/static/client/src/views/forgotPassword.vue index cef7689f..a834ba41 100644 --- a/src/static/client/src/views/forgotPassword.vue +++ b/src/static/client/src/views/forgotPassword.vue @@ -29,12 +29,8 @@ const requestToken = async (e) => { } const code = ref("") -const parseCode = () => { - code.value = code.value.replace(/\D/i, "") - code.value = code.value.slice(0, 6) -} const codeReady = computed(() => { - return /^[0-9]{6}$/.test(code.value) + return code.value.trim().length > 0 }) const codeValidated = ref(false) const validateCode = async (e) => { @@ -42,13 +38,13 @@ const validateCode = async (e) => { loading.value = true let codeValidation = await axiosPost("/api/resetPassword/validateResetToken", { Email: email.value, - Token: code.value + Token: code.value.trim() }) loading.value = false if (codeValidation.status){ codeValidated.value = true }else{ - store.newNotification("Your verification code is either invalid or expired", "danger") + store.newNotification("Your reset token is either invalid or expired", "danger") } } @@ -63,7 +59,7 @@ const resetPassword = async (e) => { loading.value = true; let reset = await axiosPost("/api/resetPassword", { Email: email.value, - Token: code.value, + Token: code.value.trim(), Password: password.value, ConfirmPassword: confirmPassword.value }) @@ -71,6 +67,8 @@ const resetPassword = async (e) => { store.newNotification("Password reset! Now you can sign in with your new password", "success") await router.push('/signin') + }else{ + store.newNotification(reset.message || "Password reset failed", "danger") } } @@ -98,7 +96,7 @@ const resetPassword = async (e) => { autocomplete="email" autofocus class="form-control rounded-3 border-0" id="email" placeholder="email"> -