Fix: Ensure email change request is sent.

The email change request was failing with a 400 error. This commit addresses the issue by ensuring the email change request is correctly sent when a user updates their email in the profile dashboard.
This commit is contained in:
Tola Leng
2025-05-17 17:55:59 +08:00
parent aaee189ace
commit 78be48ffd0
5 changed files with 97 additions and 88 deletions
@@ -1,5 +1,5 @@
import { useState } from "react"; import { useState, useEffect } from "react";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { User } from "@/services/userService"; import { User } from "@/services/userService";
import { UserProfileDetails } from "./UserProfileDetails"; import { UserProfileDetails } from "./UserProfileDetails";
@@ -9,11 +9,19 @@ import { UpdateProfileForm } from "./UpdateProfileForm";
interface ProfileContentProps { interface ProfileContentProps {
currentUser: User | null; currentUser: User | null;
onUserUpdated?: () => Promise<void>;
} }
export function ProfileContent({ currentUser }: ProfileContentProps) { export function ProfileContent({ currentUser, onUserUpdated }: ProfileContentProps) {
const [activeTab, setActiveTab] = useState("details"); const [activeTab, setActiveTab] = useState("details");
// When active tab changes, refresh user data if needed
useEffect(() => {
if (activeTab === "details" && onUserUpdated) {
onUserUpdated();
}
}, [activeTab, onUserUpdated]);
if (!currentUser) { if (!currentUser) {
return ( return (
<Card> <Card>
@@ -9,7 +9,7 @@ import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast"; import { useToast } from "@/hooks/use-toast";
import { authService } from "@/services/authService"; import { authService } from "@/services/authService";
import { AlertCircle } from "lucide-react"; import { AlertCircle, CheckCircle } from "lucide-react";
import { Alert, AlertDescription } from "@/components/ui/alert"; import { Alert, AlertDescription } from "@/components/ui/alert";
// Profile update form schema // Profile update form schema
@@ -35,6 +35,7 @@ export function UpdateProfileForm({ user }: UpdateProfileFormProps) {
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
const [emailChangeRequested, setEmailChangeRequested] = useState(false); const [emailChangeRequested, setEmailChangeRequested] = useState(false);
const [updateError, setUpdateError] = useState<string | null>(null); const [updateError, setUpdateError] = useState<string | null>(null);
const [updateSuccess, setUpdateSuccess] = useState<string | null>(null);
const { toast } = useToast(); const { toast } = useToast();
// Initialize the form with current user data // Initialize the form with current user data
@@ -50,6 +51,7 @@ export function UpdateProfileForm({ user }: UpdateProfileFormProps) {
async function onSubmit(data: ProfileFormValues) { async function onSubmit(data: ProfileFormValues) {
setIsSubmitting(true); setIsSubmitting(true);
setUpdateError(null); setUpdateError(null);
setUpdateSuccess(null);
setEmailChangeRequested(false); setEmailChangeRequested(false);
try { try {
@@ -62,8 +64,9 @@ export function UpdateProfileForm({ user }: UpdateProfileFormProps) {
const updateData = { const updateData = {
full_name: data.full_name, full_name: data.full_name,
username: data.username, username: data.username,
// Only include email if it's changed
email: isEmailChanged ? data.email : undefined, email: isEmailChanged ? data.email : undefined,
// Only set emailVisibility if email is being changed // Always set emailVisibility to true if email is changing
emailVisibility: isEmailChanged ? true : undefined emailVisibility: isEmailChanged ? true : undefined
}; };
@@ -78,11 +81,14 @@ export function UpdateProfileForm({ user }: UpdateProfileFormProps) {
// If email was changed, show a specific message // If email was changed, show a specific message
if (isEmailChanged) { if (isEmailChanged) {
setEmailChangeRequested(true); setEmailChangeRequested(true);
setUpdateSuccess("A verification email has been sent to your new email address. Please check your inbox to complete the change.");
toast({ toast({
title: "Email change requested", title: "Email verification sent",
description: "A verification email has been sent to your new email address. Please check your inbox and follow the instructions to complete the change.", description: "A verification email has been sent to your new email address. Please check your inbox and follow the instructions to complete the change.",
variant: "default",
}); });
} else { } else {
setUpdateSuccess("Your profile information has been updated successfully.");
toast({ toast({
title: "Profile updated", title: "Profile updated",
description: "Your profile information has been updated successfully.", description: "Your profile information has been updated successfully.",
@@ -118,6 +124,15 @@ export function UpdateProfileForm({ user }: UpdateProfileFormProps) {
</Alert> </Alert>
)} )}
{updateSuccess && (
<Alert className="bg-green-50 border-green-200 text-green-800">
<CheckCircle className="h-4 w-4 text-green-600" />
<AlertDescription>
{updateSuccess}
</AlertDescription>
</Alert>
)}
{emailChangeRequested && ( {emailChangeRequested && (
<Alert className="bg-yellow-50 border-yellow-200 text-yellow-800"> <Alert className="bg-yellow-50 border-yellow-200 text-yellow-800">
<AlertCircle className="h-4 w-4 text-yellow-600" /> <AlertCircle className="h-4 w-4 text-yellow-600" />
+40 -37
View File
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect, useCallback } from "react";
import { Header } from "@/components/dashboard/Header"; import { Header } from "@/components/dashboard/Header";
import { Sidebar } from "@/components/dashboard/Sidebar"; import { Sidebar } from "@/components/dashboard/Sidebar";
import { authService } from "@/services/authService"; import { authService } from "@/services/authService";
@@ -24,49 +24,49 @@ const Profile = () => {
const { toast } = useToast(); const { toast } = useToast();
// Fetch complete user data // Fetch complete user data
useEffect(() => { const fetchUserData = useCallback(async () => {
const fetchUserData = async () => { if (!currentUser?.id) {
if (!currentUser?.id) { console.error("No current user ID found");
console.error("No current user ID found"); setLoading(false);
setLoading(false); setError("No user found. Please login again.");
setError("No user found. Please login again."); return;
return; }
}
try { try {
console.log("Fetching user data for ID:", currentUser.id); console.log("Fetching user data for ID:", currentUser.id);
const data = await userService.getUser(currentUser.id); const data = await userService.getUser(currentUser.id);
console.log("Received user data:", data); console.log("Received user data:", data);
if (data) { if (data) {
setUserData(data); setUserData(data);
setError(null); setError(null);
} else { } else {
console.error("No user data returned"); console.error("No user data returned");
setError("Could not load user data"); setError("Could not load user data");
toast({
title: "Error",
description: "Could not load user data. Please try again later.",
variant: "destructive",
});
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
console.error("Failed to load user data:", error);
setError(errorMessage);
toast({ toast({
title: "Error", title: "Error",
description: "Failed to load user profile. Please try again later.", description: "Could not load user data. Please try again later.",
variant: "destructive", variant: "destructive",
}); });
} finally {
setLoading(false);
} }
}; } catch (error) {
const errorMessage = error instanceof Error ? error.message : "Unknown error";
fetchUserData(); console.error("Failed to load user data:", error);
setError(errorMessage);
toast({
title: "Error",
description: "Failed to load user profile. Please try again later.",
variant: "destructive",
});
} finally {
setLoading(false);
}
}, [currentUser?.id, toast]); }, [currentUser?.id, toast]);
useEffect(() => {
fetchUserData();
}, [fetchUserData]);
// Handle logout // Handle logout
const handleLogout = () => { const handleLogout = () => {
authService.logout(); authService.logout();
@@ -118,14 +118,17 @@ const Profile = () => {
<p>{error}</p> <p>{error}</p>
</div> </div>
<button <button
onClick={() => window.location.reload()} onClick={() => fetchUserData()}
className="px-4 py-2 bg-primary text-primary-foreground rounded-md" className="px-4 py-2 bg-primary text-primary-foreground rounded-md"
> >
Retry Retry
</button> </button>
</div> </div>
) : ( ) : (
<ProfileContent currentUser={userData} /> <ProfileContent
currentUser={userData}
onUserUpdated={fetchUserData}
/>
)} )}
</div> </div>
</div> </div>
+5 -2
View File
@@ -60,15 +60,18 @@ export const authService = {
return pb.authStore.isValid; return pb.authStore.isValid;
}, },
// New method to refresh user data after updates // Method to refresh user data after updates
async refreshUserData(): Promise<void> { async refreshUserData(): Promise<void> {
if (!pb.authStore.isValid || !pb.authStore.model) return; if (!pb.authStore.isValid || !pb.authStore.model) return;
try { try {
// Fetch the latest user data from the server // Fetch the latest user data from the server
const userId = (pb.authStore.model as any).id; const userId = (pb.authStore.model as any).id;
console.log("Refreshing user data for ID:", userId);
// Use the getOne method directly to refresh the auth store
await pb.collection('users').getOne(userId); await pb.collection('users').getOne(userId);
// PocketBase will automatically update the authStore console.log("User data refreshed successfully");
} catch (error) { } catch (error) {
console.error('Failed to refresh user data:', error); console.error('Failed to refresh user data:', error);
} }
+20 -40
View File
@@ -1,3 +1,4 @@
import { pb } from "@/lib/pocketbase"; import { pb } from "@/lib/pocketbase";
export interface User { export interface User {
@@ -89,7 +90,7 @@ export const userService = {
return currentUser; return currentUser;
} }
// Handle email updates separately using the request-email-change endpoint // Handle email updates separately
const hasEmailChange = cleanData.email !== undefined; const hasEmailChange = cleanData.email !== undefined;
const emailToUpdate = hasEmailChange ? cleanData.email : null; const emailToUpdate = hasEmailChange ? cleanData.email : null;
@@ -97,7 +98,11 @@ export const userService = {
if (hasEmailChange) { if (hasEmailChange) {
console.log("Email change detected, will handle separately:", emailToUpdate); console.log("Email change detected, will handle separately:", emailToUpdate);
delete cleanData.email; delete cleanData.email;
delete cleanData.emailVisibility; // Don't set this yet, it will be set after email change
// For email changes, we should always set emailVisibility
if (cleanData.emailVisibility === undefined) {
cleanData.emailVisibility = true;
}
} }
let updatedUser: User | null = null; let updatedUser: User | null = null;
@@ -106,25 +111,14 @@ export const userService = {
if (Object.keys(cleanData).length > 0) { if (Object.keys(cleanData).length > 0) {
console.log("Final update payload to PocketBase:", cleanData); console.log("Final update payload to PocketBase:", cleanData);
// Use the direct API approach for more control over the update process try {
const apiUrl = `${pb.baseUrl}/api/collections/users/records/${id}`; // Use PocketBase's update method for the regular fields
const response = await fetch(apiUrl, { updatedUser = await pb.collection('users').update(id, cleanData) as unknown as User;
method: 'PATCH', console.log("PocketBase update response for regular fields:", updatedUser);
headers: { } catch (error) {
'Content-Type': 'application/json', console.error("Error updating user regular fields:", error);
'Authorization': pb.authStore.token throw error;
},
body: JSON.stringify(cleanData)
});
if (!response.ok) {
const errorData = await response.json();
console.error("PocketBase API error:", errorData);
throw new Error(errorData.message || "Failed to update user");
} }
updatedUser = await response.json() as unknown as User;
console.log("PocketBase update response for regular fields:", updatedUser);
} else { } else {
// If no other fields to update, get the current user // If no other fields to update, get the current user
updatedUser = await this.getUser(id); updatedUser = await this.getUser(id);
@@ -134,32 +128,18 @@ export const userService = {
if (emailToUpdate) { if (emailToUpdate) {
try { try {
console.log("Processing email change request for new email:", emailToUpdate); console.log("Processing email change request for new email:", emailToUpdate);
// Use the request-email-change endpoint directly
const emailChangeUrl = `${pb.baseUrl}/api/collections/users/request-email-change`;
const emailChangeResponse = await fetch(emailChangeUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': pb.authStore.token
},
body: JSON.stringify({
newEmail: emailToUpdate
})
});
if (!emailChangeResponse.ok) { // Use the proper API endpoint for email change requests
const errorData = await emailChangeResponse.json(); const emailChangeResponse = await pb.collection('users').requestEmailChange(emailToUpdate);
console.error("Email change request failed:", errorData);
throw new Error(errorData.message || "Failed to request email change"); console.log("Email change request response:", emailChangeResponse);
} console.log("Email verification has been sent to:", emailToUpdate);
console.log("Email change request sent successfully");
// The email won't be updated immediately as verification is required // The email won't be updated immediately as verification is required
// We'll return the current user data, and email will be updated after verification // We'll return the current user data, and email will be updated after verification
} catch (error) { } catch (error) {
console.error("Failed to request email change:", error); console.error("Failed to request email change:", error);
// Continue with the function and return updated user for the fields that were updated throw new Error(`Failed to request email change: ${error instanceof Error ? error.message : "Unknown error"}`);
// We don't throw here because we want to save the other fields even if email change fails
} }
} }