Improve auth flows
This commit is contained in:
@@ -226,10 +226,11 @@ function AppointmentsPage() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!authLoading && !user) {
|
||||
router.push("/login");
|
||||
const target = preselectedPetId ? `/appointments?petId=${encodeURIComponent(preselectedPetId)}` : "/appointments";
|
||||
router.push(`/login?next=${encodeURIComponent(target)}`);
|
||||
}
|
||||
|
||||
}, [authLoading, user, router]);
|
||||
}, [authLoading, user, router, preselectedPetId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
|
||||
@@ -1076,6 +1076,13 @@ body {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-bottom: 0.25rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.profile-avatar-image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.profile-name {
|
||||
@@ -1105,6 +1112,37 @@ body {
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
.profile-update-form {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.profile-update-title {
|
||||
margin: 0.25rem 0 0;
|
||||
font-size: 1.1rem;
|
||||
color: #222;
|
||||
}
|
||||
|
||||
.profile-avatar-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.profile-avatar-upload-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0.65rem 1rem;
|
||||
border-radius: 8px;
|
||||
background: #fff3e0;
|
||||
color: #a65c00;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.profile-field-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
|
||||
export default function LoginPage() {
|
||||
function resolveNextPath(candidate) {
|
||||
if (!candidate || !candidate.startsWith("/")) {
|
||||
return "/";
|
||||
}
|
||||
if (candidate.startsWith("//") || candidate.startsWith("/login") || candidate.startsWith("/register")) {
|
||||
return "/";
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function LoginPage() {
|
||||
const {login} = useAuth();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
@@ -21,7 +33,7 @@ export default function LoginPage() {
|
||||
|
||||
try {
|
||||
await login(username, password);
|
||||
router.push("/");
|
||||
router.push(resolveNextPath(searchParams.get("next")));
|
||||
}
|
||||
|
||||
catch (err) {
|
||||
@@ -68,9 +80,13 @@ export default function LoginPage() {
|
||||
|
||||
<p className="auth-switch">
|
||||
Don't have an account?{" "}
|
||||
<Link href="/register" className="auth-switch-link">Register here</Link>
|
||||
<Link href={searchParams.get("next") ? `/register?next=${encodeURIComponent(searchParams.get("next"))}` : "/register"} className="auth-switch-link">Register here</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default dynamic(() => Promise.resolve(LoginPage), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useAuth } from "@/context/AuthContext";
|
||||
const API_BASE = "";
|
||||
|
||||
export default function ProfilePage() {
|
||||
const {user, token, loading, logout} = useAuth();
|
||||
const {user, token, loading, logout, refreshUser} = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
const [pets, setPets] = useState([]);
|
||||
@@ -19,14 +19,27 @@ export default function ProfilePage() {
|
||||
const [breed, setBreed] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [petError, setPetError] = useState(null);
|
||||
const [profileForm, setProfileForm] = useState({ fullName: "", email: "", phone: "" });
|
||||
const [profileSubmitting, setProfileSubmitting] = useState(false);
|
||||
const [profileError, setProfileError] = useState(null);
|
||||
const [profileSuccess, setProfileSuccess] = useState(null);
|
||||
const [avatarSubmitting, setAvatarSubmitting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && !user) {
|
||||
router.replace("/login");
|
||||
router.replace(`/login?next=${encodeURIComponent("/profile")}`);
|
||||
}
|
||||
|
||||
}, [user, loading, router]);
|
||||
|
||||
useEffect(() => {
|
||||
setProfileForm({
|
||||
fullName: user?.fullName || "",
|
||||
email: user?.email || "",
|
||||
phone: user?.phone || "",
|
||||
});
|
||||
}, [user]);
|
||||
|
||||
const loadPets = useCallback(() => {
|
||||
if (!token) return;
|
||||
setLoadingPets(true);
|
||||
@@ -50,6 +63,105 @@ export default function ProfilePage() {
|
||||
router.push("/");
|
||||
}
|
||||
|
||||
async function handleProfileSubmit(e) {
|
||||
e.preventDefault();
|
||||
setProfileSubmitting(true);
|
||||
setProfileError(null);
|
||||
setProfileSuccess(null);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/v1/auth/me`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(profileForm),
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
throw new Error(data?.message || `Request failed (${res.status})`);
|
||||
}
|
||||
|
||||
await refreshUser();
|
||||
setProfileSuccess("Profile updated successfully.");
|
||||
}
|
||||
|
||||
catch (err) {
|
||||
setProfileError(err.message);
|
||||
}
|
||||
|
||||
finally {
|
||||
setProfileSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAvatarUpload(file) {
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append("avatar", file);
|
||||
setAvatarSubmitting(true);
|
||||
setProfileError(null);
|
||||
setProfileSuccess(null);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/v1/auth/me/avatar`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
throw new Error(data?.message || "Failed to upload avatar");
|
||||
}
|
||||
|
||||
await refreshUser();
|
||||
setProfileSuccess(data?.message || "Avatar updated successfully.");
|
||||
}
|
||||
|
||||
catch (err) {
|
||||
setProfileError(err.message);
|
||||
}
|
||||
|
||||
finally {
|
||||
setAvatarSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleAvatarDelete() {
|
||||
setAvatarSubmitting(true);
|
||||
setProfileError(null);
|
||||
setProfileSuccess(null);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/v1/auth/me/avatar`, {
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
throw new Error(data?.message || "Failed to delete avatar");
|
||||
}
|
||||
|
||||
await refreshUser();
|
||||
setProfileSuccess(data?.message || "Avatar removed successfully.");
|
||||
}
|
||||
|
||||
catch (err) {
|
||||
setProfileError(err.message);
|
||||
}
|
||||
|
||||
finally {
|
||||
setAvatarSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
function openAddForm() {
|
||||
setEditingPet(null);
|
||||
setPetName("");
|
||||
@@ -170,7 +282,11 @@ export default function ProfilePage() {
|
||||
<main className="profile-page-layout">
|
||||
<div className="profile-card">
|
||||
<div className="profile-avatar-circle">
|
||||
{(user.fullName || user.username).charAt(0).toUpperCase()}
|
||||
{user.avatarUrl ? (
|
||||
<img src={user.avatarUrl} alt={user.fullName || user.username} className="profile-avatar-image" />
|
||||
) : (
|
||||
(user.fullName || user.username).charAt(0).toUpperCase()
|
||||
)}
|
||||
</div>
|
||||
|
||||
<h1 className="profile-name">{user.fullName || user.username}</h1>
|
||||
@@ -185,7 +301,65 @@ export default function ProfilePage() {
|
||||
))}
|
||||
</dl>
|
||||
|
||||
<button className="auth-submit-btn profile-logout-btn" onClick={handleLogout}>
|
||||
<form className="profile-update-form" onSubmit={handleProfileSubmit}>
|
||||
<h2 className="profile-update-title">Update Profile</h2>
|
||||
{profileError && <div className="appt-error">{profileError}</div>}
|
||||
{profileSuccess && <div className="appt-success">{profileSuccess}</div>}
|
||||
<label className="appt-label">
|
||||
Full Name
|
||||
<input
|
||||
className="appt-input"
|
||||
type="text"
|
||||
value={profileForm.fullName}
|
||||
onChange={(e) => setProfileForm((current) => ({ ...current, fullName: e.target.value }))}
|
||||
maxLength={100}
|
||||
/>
|
||||
</label>
|
||||
<label className="appt-label">
|
||||
Email
|
||||
<input
|
||||
className="appt-input"
|
||||
type="email"
|
||||
value={profileForm.email}
|
||||
onChange={(e) => setProfileForm((current) => ({ ...current, email: e.target.value }))}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="appt-label">
|
||||
Phone
|
||||
<input
|
||||
className="appt-input"
|
||||
type="text"
|
||||
value={profileForm.phone}
|
||||
onChange={(e) => setProfileForm((current) => ({ ...current, phone: e.target.value }))}
|
||||
maxLength={20}
|
||||
/>
|
||||
</label>
|
||||
<div className="profile-avatar-actions">
|
||||
<label className="profile-avatar-upload-btn">
|
||||
<input
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif"
|
||||
className="profile-pet-upload-input"
|
||||
onChange={(e) => {
|
||||
handleAvatarUpload(e.target.files?.[0] || null);
|
||||
e.target.value = "";
|
||||
}}
|
||||
/>
|
||||
{avatarSubmitting ? "Working..." : user.avatarUrl ? "Change Avatar" : "Upload Avatar"}
|
||||
</label>
|
||||
{user.avatarUrl && (
|
||||
<button type="button" className="profile-pet-delete-btn" onClick={handleAvatarDelete} disabled={avatarSubmitting}>
|
||||
Remove Avatar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button type="submit" className="appt-submit-btn" disabled={profileSubmitting || avatarSubmitting}>
|
||||
{profileSubmitting ? "Saving..." : "Save Profile"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<button type="button" className="auth-submit-btn profile-logout-btn" onClick={handleLogout}>
|
||||
Log Out
|
||||
</button>
|
||||
</div>
|
||||
@@ -194,7 +368,7 @@ export default function ProfilePage() {
|
||||
<div className="profile-pets-section">
|
||||
<div className="profile-pets-header">
|
||||
<h2 className="profile-pets-title">My Pets</h2>
|
||||
<button className="profile-pets-add-btn" onClick={openAddForm}>+ Add Pet</button>
|
||||
<button type="button" className="profile-pets-add-btn" onClick={openAddForm}>+ Add Pet</button>
|
||||
</div>
|
||||
|
||||
{showForm && (
|
||||
@@ -285,11 +459,11 @@ export default function ProfilePage() {
|
||||
{pet.breed && <span className="profile-pet-card-detail">{pet.breed}</span>}
|
||||
</div>
|
||||
<div className="profile-pet-card-actions">
|
||||
<button className="profile-pet-edit-btn" onClick={() => openEditForm(pet)}>Edit</button>
|
||||
<button className="profile-pet-delete-btn" onClick={() => handleDeletePet(pet.customerPetId)}>Remove</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" className="profile-pet-edit-btn" onClick={() => openEditForm(pet)}>Edit</button>
|
||||
<button type="button" className="profile-pet-delete-btn" onClick={() => handleDeletePet(pet.customerPetId)}>Remove</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
|
||||
export default function RegisterPage() {
|
||||
function resolveNextPath(candidate) {
|
||||
if (!candidate || !candidate.startsWith("/")) {
|
||||
return "/";
|
||||
}
|
||||
if (candidate.startsWith("//") || candidate.startsWith("/login") || candidate.startsWith("/register")) {
|
||||
return "/";
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function RegisterPage() {
|
||||
const {register} = useAuth();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
const [form, setForm] = useState({
|
||||
fullName: "",
|
||||
@@ -41,7 +53,7 @@ export default function RegisterPage() {
|
||||
phone: form.phone,
|
||||
password: form.password,
|
||||
});
|
||||
router.push("/");
|
||||
router.push(resolveNextPath(searchParams.get("next")));
|
||||
}
|
||||
|
||||
catch (err) {
|
||||
@@ -144,9 +156,13 @@ export default function RegisterPage() {
|
||||
|
||||
<p className="auth-switch">
|
||||
Already have an account?{" "}
|
||||
<Link href="/login" className="auth-switch-link">Log in here</Link>
|
||||
<Link href={searchParams.get("next") ? `/login?next=${encodeURIComponent(searchParams.get("next"))}` : "/login"} className="auth-switch-link">Log in here</Link>
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
export default dynamic(() => Promise.resolve(RegisterPage), {
|
||||
ssr: false,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user