fix(auth): redirect to login after password change

This commit is contained in:
ShivaniKhaire 2026-11-30 11:55:21 +05:30
parent e153668f06
commit 2945f43d38
5 changed files with 122 additions and 23 deletions

View File

@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import {
KeyboardAvoidingView,
Platform,
@ -8,17 +8,25 @@ import {
Alert,
} from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";
import { router } from "expo-router";
import { moderateScale, verticalScale } from "react-native-size-matters";
import SettingsHeader from "@/features/settings/components/SettingsHeader";
import PasswordInput from "@/components/forms/PasswordInput";
import PrimaryButton from "@/components/buttons/PrimaryButton";
import FieldLabel from "@/components/forms/FieldLabel";
import { changePassword } from "@/features/auth/api/auth.api";
import { resetNavigationToLogin } from "@/features/auth/utils/navigation";
import { useAuthStore } from "@/store/auth.store";
import { Colors } from "@/theme";
import { apiClient } from "@/api";
export default function ChangePasswordScreen() {
const isAuthenticated = useAuthStore((state) => Boolean(state.accessToken));
const logout = useAuthStore((state) => state.logout);
const [hasHydrated, setHasHydrated] = useState(() =>
useAuthStore.persist.hasHydrated(),
);
const isCompletingReloginRef = useRef(false);
const [currentPassword, setCurrentPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
@ -28,7 +36,25 @@ export default function ChangePasswordScreen() {
const [confirmError, setConfirmError] = useState("");
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (hasHydrated) return;
return useAuthStore.persist.onFinishHydration(() => {
setHasHydrated(true);
});
}, [hasHydrated]);
useEffect(() => {
if (hasHydrated && !isAuthenticated && !isCompletingReloginRef.current) {
resetNavigationToLogin();
}
}, [hasHydrated, isAuthenticated]);
if (hasHydrated && !isAuthenticated && !isCompletingReloginRef.current) {
return null;
}
const handleUpdatePassword = async () => {
if (isLoading || isCompletingReloginRef.current) return;
let hasError = false;
setCurrentError("");
setNewError("");
@ -71,19 +97,38 @@ export default function ChangePasswordScreen() {
setIsLoading(true);
try {
await apiClient.post("/auth/change-password", {
await changePassword({
old_password: currentPassword,
new_password: newPassword,
});
const msg = "Password updated successfully!";
// Force full session termination immediately so the user must
// re-authenticate with the new password before reopening the app.
isCompletingReloginRef.current = true;
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
logout();
let hasRedirected = false;
const redirectToLogin = () => {
if (hasRedirected) return;
hasRedirected = true;
resetNavigationToLogin();
};
const msg =
"Password updated successfully! Please log in with your new password.";
if (Platform.OS === "web") {
window.alert(msg);
router.back();
redirectToLogin();
} else {
Alert.alert("Success", msg, [
{ text: "OK", onPress: () => router.back() },
]);
Alert.alert(
"Password Updated",
msg,
[{ text: "Log In", onPress: redirectToLogin }],
{ cancelable: false, onDismiss: redirectToLogin },
);
}
} catch (err: any) {
const errMsg =

View File

@ -2,6 +2,7 @@ import apiClient from "@/api/client";
import { API_ENDPOINTS } from "@/api/endpoints";
import type {
AuthTokenResponse,
ChangePasswordRequest,
ForgotPasswordRequest,
LoginRequest,
RegisterRequest,
@ -57,6 +58,19 @@ export async function resetPassword(
return response.data;
}
/**
* Updates the authenticated user's password via the auth change-password endpoint.
*/
export async function changePassword(
payload: ChangePasswordRequest,
): Promise<StatusMessageResponse> {
const response = await apiClient.post<StatusMessageResponse>(
API_ENDPOINTS.AUTH.CHANGE_PASSWORD,
payload,
);
return response.data;
}
export interface ProfileUpdatePayload {
full_name?: string | null;
email?: string | null;

View File

@ -1,7 +1,7 @@
import React, { useState } from "react";
import React, { useCallback, useState } from "react";
import { Pressable, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { useFocusEffect, useRouter } from "expo-router";
import {
moderateScale,
scale,
@ -16,8 +16,15 @@ import EnvironmentSelectorModal from "@/components/EnvironmentSelectorModal";
export default function LoginHeader() {
const router = useRouter();
const [modalVisible, setModalVisible] = useState(false);
const [canGoBack, setCanGoBack] = useState(false);
const activeConfig = useEnvironmentStore((state) => state.getActiveConfig());
useFocusEffect(
useCallback(() => {
setCanGoBack(router.canGoBack());
}, [router]),
);
const badgeColor =
activeConfig.key === "prod"
? "#10B981"
@ -28,18 +35,26 @@ export default function LoginHeader() {
return (
<View style={styles.container}>
<View style={styles.topRow}>
<Pressable
accessibilityRole="button"
accessibilityLabel="Go Back"
hitSlop={10}
onPress={() => router.back()}
style={styles.backButton}
>
<Ionicons
name="arrow-back"
size={moderateScale(24)}
/>
</Pressable>
{canGoBack ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Go Back"
hitSlop={10}
onPress={() => {
if (router.canGoBack()) {
router.back();
}
}}
style={styles.backButton}
>
<Ionicons
name="arrow-back"
size={moderateScale(24)}
/>
</Pressable>
) : (
<View style={styles.backButton} />
)}
{ENABLE_ENV_SWITCHER && (
<TouchableOpacity

View File

@ -0,0 +1,20 @@
import { router, type Href } from "expo-router";
/**
* Collapses pushed stack screens before replacing the current route so
* back navigation cannot return to prior screens in the stack.
*/
export function resetNavigationToRoute(href: Href): void {
if (router.canDismiss()) {
router.dismissAll();
}
router.replace(href);
}
/**
* Clears the navigation stack and replaces the active route with the login screen.
*/
export function resetNavigationToLogin(): void {
resetNavigationToRoute("/login");
}

View File

@ -92,6 +92,11 @@ export interface ResetPasswordRequest {
new_password: string;
}
export interface ChangePasswordRequest {
old_password: string;
new_password: string;
}
export interface StatusMessageResponse {
status: string;
message: string;