Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/app/(auth)/oauth/[provider]/callback/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ const OAuthCallbackContent = () => {

const resultAudience = getAuthAudienceFromRole(result.user.role);

// LoginForm과 동일: audience 불일치 시 세션 롤백
// OAuth는 BE가 기존 계정의 role을 강제하지 않으므로 FE에서 세션 롤백이 필요
if (resultAudience !== pageAudience) {
await logout();
failOAuthCallback(getAudienceMismatchMessage(pageAudience, resultAudience), setError);
Expand Down
16 changes: 10 additions & 6 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import { cookies } from "next/headers";

import { AppShell } from "@/components/layout/AppShell";
import { safeDecodeCookieValue } from "@/lib/auth/clientStorageHint";
import { NICKNAME_STORAGE_KEY } from "@/lib/auth/nickname";
import { NICKNAME_STORAGE_KEY, sanitizeSoftUxNickname } from "@/lib/auth/nickname";
import { PROFILE_COMPLETED_STORAGE_KEY, parseProfileCompleted } from "@/lib/auth/profileCompleted";
import { PROFILE_IMAGE_STORAGE_KEY } from "@/lib/auth/profileImage";
import { ROLE_STORAGE_KEY, parseAuthRole } from "@/lib/auth/role";
import { PROFILE_IMAGE_STORAGE_KEY, sanitizeSoftUxProfileImageUrl } from "@/lib/auth/profileImage";
import { ROLE_STORAGE_KEY, parseSoftUxAuthRole } from "@/lib/auth/role";
import { REFRESH_TOKEN_COOKIE_NAME } from "@/lib/auth/token";

import "./globals.css";
Expand All @@ -29,12 +29,16 @@ const RootLayout = async ({ children }: RootLayoutProps) => {
/** SSR 시점 HttpOnly refreshToken 쿠키 존재 여부 (로그인 Soft UX·선제 refresh 힌트) */
const hasRefreshCookie = Boolean(cookieStore.get(REFRESH_TOKEN_COOKIE_NAME));
const rawProfileImage = cookieStore.get(PROFILE_IMAGE_STORAGE_KEY)?.value;
const initialProfileImage = rawProfileImage ? safeDecodeCookieValue(rawProfileImage) : null;
const initialProfileImage = sanitizeSoftUxProfileImageUrl(
rawProfileImage ? safeDecodeCookieValue(rawProfileImage) : null,
);
const rawNickname = cookieStore.get(NICKNAME_STORAGE_KEY)?.value;
const initialNickname = rawNickname ? safeDecodeCookieValue(rawNickname) : null;
const initialNickname = sanitizeSoftUxNickname(
rawNickname ? safeDecodeCookieValue(rawNickname) : null,
);
const rawRole = cookieStore.get(ROLE_STORAGE_KEY)?.value;
const decodedRole = rawRole ? safeDecodeCookieValue(rawRole) : null;
const initialRole = parseAuthRole(decodedRole);
const initialRole = parseSoftUxAuthRole(decodedRole);
const initialProfileCompleted = parseProfileCompleted(
cookieStore.get(PROFILE_COMPLETED_STORAGE_KEY)?.value,
);
Expand Down
4 changes: 2 additions & 2 deletions src/app/movers/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { cookies } from "next/headers";
import BlockMoverFromMoversBrowse from "@/components/auth/BlockMoverFromMoversBrowse";
import { LoginRequiredModalProvider } from "@/components/auth/LoginRequiredModalProvider";
import { safeDecodeCookieValue } from "@/lib/auth/clientStorageHint";
import { ROLE_STORAGE_KEY, parseAuthRole } from "@/lib/auth/role";
import { ROLE_STORAGE_KEY, parseSoftUxAuthRole } from "@/lib/auth/role";

interface MoversLayoutProps {
children: ReactNode;
Expand All @@ -14,7 +14,7 @@ const MoversLayout = async ({ children }: MoversLayoutProps) => {
const cookieStore = await cookies();
const rawRole = cookieStore.get(ROLE_STORAGE_KEY)?.value;
const decodedRole = rawRole ? safeDecodeCookieValue(rawRole) : null;
const initialRole = parseAuthRole(decodedRole);
const initialRole = parseSoftUxAuthRole(decodedRole);

return (
<LoginRequiredModalProvider>
Expand Down
35 changes: 20 additions & 15 deletions src/components/auth/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { zodResolver } from "@hookform/resolvers/zod";
import Link from "next/link";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";

import AuthHeader from "@/components/auth/AuthHeader";
Expand All @@ -12,12 +12,14 @@ import FormField from "@/components/common/FormField/FormField";
import Input from "@/components/common/Input/Input";
import PasswordInput from "@/components/common/Input/PasswordInput";
import { Text, getTextVariantClass } from "@/components/common/Text";
import Toast from "@/components/common/Toast/Toast";
import { useLoginMutation } from "@/hooks/auth/useLoginMutation";
import { getApiErrorMessage } from "@/lib/api/getApiErrorMessage";
import { resolveAuthUserImage } from "@/lib/api/profile";
import { consumePasswordChangedToast } from "@/lib/auth/passwordChangedToast";
import { clearProfileCompleted } from "@/lib/auth/profileCompleted";
import {
getAudienceMismatchMessage,
getAuthAudienceFromRole,
audienceToLoginRole,
getLoginRedirectParam,
getPostAuthRedirectPath,
getRoleHomePath,
Expand All @@ -27,7 +29,6 @@ import { APP_ROUTES } from "@/lib/constants/appRoutes";
import { loginSchema, type LoginFormValues } from "@/lib/schemas/loginSchema";
import { cn } from "@/lib/utils/cn";
import { useAuthStore } from "@/stores/useAuthStore";
import { resolveAuthUserImage } from "@/lib/api/profile";

interface LoginFormProps {
audience?: AuthAudience;
Expand All @@ -37,8 +38,8 @@ const LoginForm = ({ audience = "customer" }: LoginFormProps) => {
const { mutateAsync: login, isPending } = useLoginMutation();
const establishSession = useAuthStore((state) => state.establishSession);
const setPostAuthRedirectPath = useAuthStore((state) => state.setPostAuthRedirectPath);
const logout = useAuthStore((state) => state.logout);
const [submitError, setSubmitError] = useState<string | null>(null);
const [toastMessage, setToastMessage] = useState<string | null>(null);

const {
register,
Expand All @@ -53,27 +54,30 @@ const LoginForm = ({ audience = "customer" }: LoginFormProps) => {
},
});

useEffect(() => {
// setState는 effect 본문 동기 호출이 아니라 콜백으로 미룸 (react-hooks/set-state-in-effect)
const timerId = window.setTimeout(() => {
setToastMessage(consumePasswordChangedToast());
}, 0);
return () => {
window.clearTimeout(timerId);
};
}, []);

const signUpHref = audience === "mover" ? APP_ROUTES.MOVER_SIGN_UP : APP_ROUTES.SIGN_UP;

const onSubmit = handleSubmit(async (values) => {
setSubmitError(null);

try {
const result = await login(values);
const resultAudience = getAuthAudienceFromRole(result.user.role);

// audience 불일치: establishSession 전에 롤백 (GuestOnly 홈 이동 방지)
if (resultAudience !== audience) {
await logout();
setSubmitError(getAudienceMismatchMessage(audience, resultAudience));
return;
}
const role = audienceToLoginRole(audience);
const result = await login({ ...values, role });

// 이전 계정 Soft UX 힌트 제거 후 status로 다시 저장
clearProfileCompleted();

const nextPath = await getPostAuthRedirectPath({
audience: resultAudience,
audience,
returnPath: getLoginRedirectParam(),
fallbackPath: getRoleHomePath(result.user.role),
});
Expand All @@ -87,6 +91,7 @@ const LoginForm = ({ audience = "customer" }: LoginFormProps) => {

return (
<div className="flex w-full flex-col items-center gap-40 md:gap-48">
{toastMessage ? <Toast onClose={() => setToastMessage(null)}>{toastMessage}</Toast> : null}
<AuthHeader audience={audience} />

<div className="flex w-full flex-col items-center gap-48 md:gap-24">
Expand Down
2 changes: 1 addition & 1 deletion src/components/auth/RoleGuard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { getAccessToken } from "@/lib/auth/token";
import { useAuthStore } from "@/stores/useAuthStore";

interface RoleGuardProps {
allowedRole: Extract<AuthRole, "CUSTOMER" | "MOVER" | "ADMIN">;
allowedRole: AuthRole;
children: ReactNode;
loadingFallback?: ReactNode;
}
Expand Down
15 changes: 2 additions & 13 deletions src/components/common/Header/HeaderSideNav.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { createPortal } from "react-dom";

import { isNavLinkActive } from "@/components/common/Header/isNavLinkActive";
import { Text } from "@/components/common/Text";
import { useBodyScrollLock } from "@/hooks/useBodyScrollLock";
import { useFocusTrap } from "@/hooks/useFocusTrap";
import { CloseIcon } from "@/icons";
import { MEDIA_QUERY } from "@/lib/constants/breakpoints";
Expand Down Expand Up @@ -68,19 +69,7 @@ const HeaderSideNav = ({ id, isOpen, onClose, links, emptyMessage }: HeaderSideN
};
}, [isOpen, onClose]);

// 모바일 화면에서 주요 메뉴 열림 시 body overflow 조정
useEffect(() => {
if (!isOpen) {
return;
}

const previousOverflow = document.body.style.overflow;
document.body.style.overflow = "hidden";

return () => {
document.body.style.overflow = previousOverflow;
};
}, [isOpen]);
useBodyScrollLock(isOpen);

const handlePanelTransitionEnd = (event: TransitionEvent<HTMLElement>) => {
if (event.target !== event.currentTarget) return;
Expand Down
6 changes: 4 additions & 2 deletions src/components/common/Header/ProfileMenuTrigger.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import Toast from "@/components/common/Toast/Toast";
import { useClickOutside } from "@/hooks/useClickOutside";
import { Skeleton } from "@/components/common/Skeleton/Skeleton";
import { usePresence } from "@/hooks/usePresence";
import { sanitizeSoftUxProfileImageUrl } from "@/lib/auth/profileImage";
import type { AuthRole } from "@/lib/auth/role";
import { isPublicPath } from "@/lib/auth/redirect";
import { APP_ROUTES } from "@/lib/constants/appRoutes";
Expand Down Expand Up @@ -45,6 +46,7 @@ export default function ProfileMenuTrigger({
const pathname = usePathname();
const router = useRouter();
const logout = useAuthStore((state) => state.logout);
const safeImageUrl = sanitizeSoftUxProfileImageUrl(imageUrl);

const [isOpen, setIsOpen] = useState(false);
const [toastMessage, setToastMessage] = useState<string | null>(null);
Expand Down Expand Up @@ -173,10 +175,10 @@ export default function ProfileMenuTrigger({
>
{isAvatarPending ? (
<Skeleton className="size-24 rounded-full xl:size-36" />
) : imageUrl ? (
) : safeImageUrl ? (
<div className="rounded-100 overflow-hidden">
<Image
src={imageUrl}
src={safeImageUrl}
alt=""
width={36}
height={36}
Expand Down
20 changes: 3 additions & 17 deletions src/components/common/Modal/ModalMain.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from "react";
import { createPortal } from "react-dom";

import { useBodyScrollLock } from "@/hooks/useBodyScrollLock";
import { useCloseOnPathnameChange } from "@/hooks/useCloseOnPathnameChange";
import { useFocusTrap } from "@/hooks/useFocusTrap";
import { useIsClient } from "@/hooks/useIsClient";
Expand Down Expand Up @@ -96,23 +97,8 @@ const ModalMain = ({

useCloseOnPathnameChange(isVisible ? onClose : undefined);

useEffect(() => {
if (!isRendered) {
return;
}

const previousOverflow = document.body.style.overflow;
const previousPaddingRight = document.body.style.paddingRight;
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.style.overflow = "hidden";
if (scrollbarWidth > 0) {
document.body.style.paddingRight = `${scrollbarWidth}px`;
}
return () => {
document.body.style.overflow = previousOverflow;
document.body.style.paddingRight = previousPaddingRight;
};
}, [isRendered]);
// exit 애니메이션 동안(isRendered)에도 스크롤 잠금 유지
useBodyScrollLock(isRendered);

useFocusTrap({
containerRef: panelRef,
Expand Down
21 changes: 19 additions & 2 deletions src/components/profile/CustomerProfileEditForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ import ProfilePageHeader from "@/components/profile/ProfilePageHeader";
import { useUpdateCustomerBasicInfo } from "@/hooks/profile/useUpdateCustomerBasicInfo";
import { useUpdateCustomerProfile } from "@/hooks/profile/useUpdateCustomerProfile";
import { getApiErrorMessage } from "@/lib/api/getApiErrorMessage";
import { reauthAfterPasswordChange } from "@/lib/auth/reauthAfterPasswordChange";
import { APP_ROUTES } from "@/lib/constants/appRoutes";
import { MOVE_TYPE_OPTIONS } from "@/lib/constants/moveType";
import { REGION_OPTIONS, type RegionId } from "@/lib/constants/region";
import { buildCustomerProfileEditPayloads } from "@/lib/profile/buildCustomerProfileEditPayloads";
Expand All @@ -24,6 +26,8 @@ import {
customerProfileEditSchema,
type CustomerProfileEditFormValues,
} from "@/lib/schemas/customerProfileEditSchema";
import { hasPasswordChangePayload } from "@/lib/schemas/passwordChangeFields";
import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput";
import { ApiError } from "@/types/api";
import type { MoveType } from "@/types/move";

Expand Down Expand Up @@ -57,7 +61,7 @@ const CustomerProfileEditForm = ({
getValues,
reset,
resetField,
formState: { errors, isValid, isSubmitting, dirtyFields },
formState: { errors, isValid, isSubmitting, dirtyFields, isDirty },
} = useForm<CustomerProfileEditFormValues>({
resolver: zodResolver(customerProfileEditSchema),
mode: "onChange",
Expand Down Expand Up @@ -99,6 +103,7 @@ const CustomerProfileEditForm = ({
return;
}

const didChangePassword = hasPasswordChangePayload(basic);
let didBasicSucceed = false;

if (basic) {
Expand All @@ -119,6 +124,12 @@ const CustomerProfileEditForm = ({
try {
await updateCustomerProfile.mutateAsync(profile);
} catch (profileError) {
if (didBasicSucceed && didChangePassword) {
// refresh token 이미 폐기됨 → 머무르면 F5 시 강제 로그아웃만 발생
await reauthAfterPasswordChange(APP_ROUTES.LOGIN, { profileFailed: true });
return;
}

if (didBasicSucceed) {
setSubmitError(PROFILE_PARTIAL_SAVE_ERROR);
return;
Expand All @@ -128,6 +139,11 @@ const CustomerProfileEditForm = ({
}
}

if (didChangePassword) {
await reauthAfterPasswordChange(APP_ROUTES.LOGIN);
return;
}

const current = getValues();
reset({
...current,
Expand Down Expand Up @@ -171,6 +187,7 @@ const CustomerProfileEditForm = ({
<form
className="px-margin-mobile mx-auto flex w-full max-w-[1120px] flex-col gap-40 py-32 md:gap-48 md:px-72 md:py-40 lg:px-0 lg:pt-56 lg:pb-70"
onSubmit={onSubmit}
onKeyDown={preventEnterSubmitOnInput}
noValidate
autoComplete="off"
>
Expand Down Expand Up @@ -310,7 +327,7 @@ const CustomerProfileEditForm = ({
</Text>
) : null}

<ProfileFormActions isSubmitDisabled={!isValid || isPending} />
<ProfileFormActions isSubmitDisabled={!isValid || isPending || !isDirty} />

{toastMessage ? <Toast onClose={() => setToastMessage(null)}>{toastMessage}</Toast> : null}
</form>
Expand Down
2 changes: 2 additions & 0 deletions src/components/profile/CustomerProfileForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
createCustomerProfileSchema,
type CustomerProfileFormValues,
} from "@/lib/schemas/customerProfileSchema";
import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput";
import { ApiError } from "@/types/api";
import type { MoveType } from "@/types/move";

Expand Down Expand Up @@ -100,6 +101,7 @@ const CustomerProfileForm = ({
<form
className="px-margin-mobile mx-auto flex w-full max-w-[640px] flex-col gap-40 py-32 md:px-72 md:py-40 lg:px-0 lg:pt-56 lg:pb-70"
onSubmit={onSubmit}
onKeyDown={preventEnterSubmitOnInput}
noValidate
autoComplete="off"
>
Expand Down
Loading