From 6f54702e2d9dea44e690ad7e72b068cf8cebf8be Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 01:41:30 +0900 Subject: [PATCH 01/11] =?UTF-8?q?fix:=20localStorage=20=EC=A0=80=EC=9E=A5?= =?UTF-8?q?=20=EC=A0=9C=EA=B1=B0,=20cookie=20=EC=A0=95=EB=B3=B4=20?= =?UTF-8?q?=EB=B6=88=EB=9F=AC=EC=98=AC=20=EB=95=8C=20=ED=95=B4=EB=8B=B9=20?= =?UTF-8?q?=EA=B0=92=20=EC=95=88=EC=A0=84=ED=95=9C=EC=A7=80=20=EA=B2=80?= =?UTF-8?q?=EC=A6=9D=20=ED=9B=84=20=EB=B0=98=EC=98=81=ED=95=98=EB=8F=84?= =?UTF-8?q?=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/layout.tsx | 16 +++++--- src/app/movers/layout.tsx | 4 +- .../common/Header/ProfileMenuTrigger.tsx | 3 +- src/lib/auth/clientStorageHint.ts | 22 +++++----- src/lib/auth/nickname.ts | 23 ++++++++--- src/lib/auth/profileCompleted.ts | 2 +- src/lib/auth/profileImage.ts | 40 ++++++++++++++++--- src/lib/auth/role.ts | 18 +++++++-- src/lib/utils/moverProfileImage.ts | 6 +-- src/stores/useAuthStore.ts | 4 +- 10 files changed, 97 insertions(+), 41 deletions(-) diff --git a/src/app/layout.tsx b/src/app/layout.tsx index e34f8fed..3c126ca5 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -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"; @@ -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, ); diff --git a/src/app/movers/layout.tsx b/src/app/movers/layout.tsx index beff3a64..70d2268e 100644 --- a/src/app/movers/layout.tsx +++ b/src/app/movers/layout.tsx @@ -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; @@ -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 ( diff --git a/src/components/common/Header/ProfileMenuTrigger.tsx b/src/components/common/Header/ProfileMenuTrigger.tsx index 6a049321..b729d39f 100644 --- a/src/components/common/Header/ProfileMenuTrigger.tsx +++ b/src/components/common/Header/ProfileMenuTrigger.tsx @@ -14,6 +14,7 @@ import type { AuthRole } from "@/lib/auth/role"; import { isPublicPath } from "@/lib/auth/redirect"; import { APP_ROUTES } from "@/lib/constants/appRoutes"; import { cn } from "@/lib/utils/cn"; +import { resolveMoverProfileImageSrc } from "@/lib/utils/moverProfileImage"; import { DROPDOWN_EXIT_DURATION_MS, dropdownMotionClassName } from "@/lib/utils/uiMotion"; import { useAuthStore } from "@/stores/useAuthStore"; @@ -176,7 +177,7 @@ export default function ProfileMenuTrigger({ ) : imageUrl ? (
{ export const setClientStorageHint = (key: ClientStorageHintKey, value: string): void => { if (typeof window === "undefined") return; - try { - localStorage.setItem(key, value); - } catch { - // QuotaExceeded / SecurityError 등 — cookie 힌트는 계속 반영 - } - const secureFlag = window.location.protocol === "https:" ? "; Secure" : ""; document.cookie = `${key}=${encodeURIComponent(value)}; Path=/; SameSite=Lax; Max-Age=${ONE_YEAR_SECONDS}${secureFlag}`; }; @@ -40,17 +34,21 @@ export const setClientStorageHint = (key: ClientStorageHintKey, value: string): export const getClientStorageHint = (key: ClientStorageHintKey): string | null => { if (typeof window === "undefined") return null; - try { - return localStorage.getItem(key); - } catch { - // SecurityError 등 — 힌트 없음으로 처리 - return null; + const prefix = `${key}=`; + const parts = document.cookie.split("; "); + + for (const part of parts) { + if (!part.startsWith(prefix)) continue; + return safeDecodeCookieValue(part.slice(prefix.length)); } + + return null; }; export const clearClientStorageHint = (key: ClientStorageHintKey): void => { if (typeof window === "undefined") return; + // 이전 localStorage 이중 저장분 정리 (마이그레이션) try { localStorage.removeItem(key); } catch { diff --git a/src/lib/auth/nickname.ts b/src/lib/auth/nickname.ts index 32d50c3a..505e6c5b 100644 --- a/src/lib/auth/nickname.ts +++ b/src/lib/auth/nickname.ts @@ -6,26 +6,39 @@ import { /** * Header SSR/첫 페인트용 표시 이름만 저장합니다. - * (nickname 쿠키 + localStorage) + * (nickname Soft UX 쿠키) */ export const NICKNAME_STORAGE_KEY = "moving_nickname" as const; +/** Soft UX 표시·쿠키 용량 제한 */ +const MAX_NICKNAME_HINT_LENGTH = 50; + /** 이전 전체 user 캐시 키 — 마이그레이션 시 제거 */ const LEGACY_AUTH_USER_CACHE_KEY = "moving_auth_user"; /** @deprecated `@/lib/auth/clientStorageHint`에서 import하세요. 기존 경로 호환용 */ export { safeDecodeCookieValue } from "@/lib/auth/clientStorageHint"; +/** Soft UX용 표시 이름. 제어문자 제거·길이 제한 */ +export const sanitizeSoftUxNickname = (value: string | null | undefined): string | null => { + const trimmed = value?.trim() ?? ""; + if (!trimmed) return null; + + const cleaned = trimmed.replace(/[\u0000-\u001F\u007F]/g, "").slice(0, MAX_NICKNAME_HINT_LENGTH); + + return cleaned.length > 0 ? cleaned : null; +}; + export const saveNickname = (name: string): void => { - const trimmed = name.trim(); - if (!trimmed) return; + const safe = sanitizeSoftUxNickname(name); + if (!safe) return; - setClientStorageHint(NICKNAME_STORAGE_KEY, trimmed); + setClientStorageHint(NICKNAME_STORAGE_KEY, safe); }; export const loadNickname = (): string | null => { - return getClientStorageHint(NICKNAME_STORAGE_KEY); + return sanitizeSoftUxNickname(getClientStorageHint(NICKNAME_STORAGE_KEY)); }; export const clearNickname = (): void => { diff --git a/src/lib/auth/profileCompleted.ts b/src/lib/auth/profileCompleted.ts index 492b9076..26a74655 100644 --- a/src/lib/auth/profileCompleted.ts +++ b/src/lib/auth/profileCompleted.ts @@ -5,7 +5,7 @@ import { } from "@/lib/auth/clientStorageHint"; /** - * Header·가드용 프로필 완료 힌트 (cookie + localStorage) + * Header·가드용 프로필 완료 힌트 (profileCompleted Soft UX 쿠키) * - true: status 생략 가능 (Soft UX) * - false: 미완료 낙관 표시 후 status로 확정 * - null: 힌트 없음 → status 조회 diff --git a/src/lib/auth/profileImage.ts b/src/lib/auth/profileImage.ts index f6c38602..5f97fbc5 100644 --- a/src/lib/auth/profileImage.ts +++ b/src/lib/auth/profileImage.ts @@ -1,3 +1,4 @@ +import { isAllowedImageRemoteUrl } from "@/lib/constants/allowedImageHosts"; import { clearClientStorageHint, getClientStorageHint, @@ -6,23 +7,52 @@ import { /** * Header SSR/첫 페인트용 표시 이미지만 저장합니다. - * (profileImage 쿠키 + localStorage) + * (profileImage Soft UX 쿠키) */ +/** Soft UX 쿠키 용량·남용 방지 */ +const MAX_PROFILE_IMAGE_HINT_LENGTH = 2048; + export const PROFILE_IMAGE_STORAGE_KEY = "moving_profile_image" as const; +/** + * Soft UX용 프로필 이미지 URL. + * - `/...` 로컬 경로만 (프로토콜 상대 `//` 제외) + * - 원격은 https allowlist만 + * - javascript:/data:/http: 등은 null + */ +export const sanitizeSoftUxProfileImageUrl = (value: string | null | undefined): string | null => { + const trimmed = value?.trim() ?? ""; + if (!trimmed || trimmed.length > MAX_PROFILE_IMAGE_HINT_LENGTH) { + return null; + } + + if (trimmed.startsWith("/") && !trimmed.startsWith("//")) { + if (trimmed.includes("\\") || trimmed.includes("..")) { + return null; + } + return trimmed; + } + + if (isAllowedImageRemoteUrl(trimmed)) { + return trimmed; + } + + return null; +}; + export const saveProfileImage = (imageUrl: string): void => { - const trimmed = imageUrl.trim(); - if (!trimmed) { + const safe = sanitizeSoftUxProfileImageUrl(imageUrl); + if (!safe) { clearProfileImage(); return; } - setClientStorageHint(PROFILE_IMAGE_STORAGE_KEY, imageUrl); + setClientStorageHint(PROFILE_IMAGE_STORAGE_KEY, safe); }; export const loadProfileImage = (): string | null => { - return getClientStorageHint(PROFILE_IMAGE_STORAGE_KEY); + return sanitizeSoftUxProfileImageUrl(getClientStorageHint(PROFILE_IMAGE_STORAGE_KEY)); }; export const clearProfileImage = (): void => { diff --git a/src/lib/auth/role.ts b/src/lib/auth/role.ts index 44aa9629..7af8bfea 100644 --- a/src/lib/auth/role.ts +++ b/src/lib/auth/role.ts @@ -6,13 +6,14 @@ import { } from "@/lib/auth/clientStorageHint"; /** - * Header SSR/첫 페인트용 role 힌트 (cookie + localStorage) + * Header SSR/첫 페인트용 role 힌트 (role Soft UX 쿠키) */ export const ROLE_STORAGE_KEY = "moving_role" as const; export type AuthRole = AuthUser["role"]; +/** JWT·API payload용. ADMIN 포함 */ export const parseAuthRole = (value: string | null | undefined): AuthRole | null => { if (value === "CUSTOMER" || value === "MOVER" || value === "ADMIN") { return value; @@ -20,12 +21,23 @@ export const parseAuthRole = (value: string | null | undefined): AuthRole | null return null; }; +/** Soft UX(Header/가드 힌트)용. ADMIN·임의 문자열은 무시 */ +export const parseSoftUxAuthRole = (value: string | null | undefined): AuthRole | null => { + if (value === "CUSTOMER" || value === "MOVER") { + return value; + } + return null; +}; + export const saveRole = (role: AuthRole): void => { - setClientStorageHint(ROLE_STORAGE_KEY, role); + const softUxRole = parseSoftUxAuthRole(role); + if (!softUxRole) return; + + setClientStorageHint(ROLE_STORAGE_KEY, softUxRole); }; export const loadRole = (): AuthRole | null => { - return parseAuthRole(getClientStorageHint(ROLE_STORAGE_KEY)); + return parseSoftUxAuthRole(getClientStorageHint(ROLE_STORAGE_KEY)); }; export const clearRole = (): void => { diff --git a/src/lib/utils/moverProfileImage.ts b/src/lib/utils/moverProfileImage.ts index 097b47c1..98b77d9d 100644 --- a/src/lib/utils/moverProfileImage.ts +++ b/src/lib/utils/moverProfileImage.ts @@ -2,13 +2,11 @@ import { isAllowedImageRemoteUrl } from "@/lib/constants/allowedImageHosts"; export const DEFAULT_MOVER_PROFILE_IMAGE = "/images/profile-character.png"; -function isLocalPublicPath(src: string) { - return src.startsWith("/"); -} +const isLocalPublicPath = (src: string) => src.startsWith("/") && !src.startsWith("//"); /** * 카드/목록에 넣을 프로필 이미지 URL. - * - 로컬 `/...` 허용 + * - 로컬 `/...` 허용 (프로토콜 상대 `//` 제외) * - 원격은 allowlist(seed picsum + NEXT_PUBLIC_PROFILE_IMAGE_HOSTS)만 허용 * - 그 외는 기본 이미지 */ diff --git a/src/stores/useAuthStore.ts b/src/stores/useAuthStore.ts index 911cb3aa..3a54c2d5 100644 --- a/src/stores/useAuthStore.ts +++ b/src/stores/useAuthStore.ts @@ -28,14 +28,14 @@ interface AuthState { isAuthenticated: boolean; /** 인증 중 여부 */ isCheckingAuth: boolean; - /** localStorage hydrate 완료 여부 — SSR/CSR 첫 페인트 일치용 */ + /** Soft UX 힌트 hydrate 완료 여부 — SSR/CSR 첫 페인트 일치용 */ hasHydrated: boolean; /** * 로그인/가입 직후 GuestOnly가 사용할 목적지. * consume 시 한 번만 읽고 null로 비웁니다. */ postAuthRedirectPath: string | null; - /** localStorage에서 인증 상태 초기화 */ + /** Soft UX 쿠키 힌트로 표시 상태 초기화 */ hydrateFromStorage: () => void; /** 인증 상태 확인 */ checkAuth: (options?: { hasRefreshCookie?: boolean }) => Promise; From aac0c407d6710fbf33cf84633561bf5e3d039cf0 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 02:11:44 +0900 Subject: [PATCH 02/11] =?UTF-8?q?feat:=20role=20=EB=B6=88=EC=9D=BC?= =?UTF-8?q?=EC=B9=98=20=EC=8B=9C=20logout=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/auth/LoginForm.tsx | 17 ++++------------- src/components/auth/RoleGuard.tsx | 2 +- src/hooks/auth/useLoginMutation.ts | 3 ++- src/lib/api/auth.ts | 6 ++++-- src/lib/auth/oauth.ts | 13 ++----------- src/lib/auth/redirect.ts | 12 +++++++++++- src/lib/auth/role.ts | 11 +++++++---- src/lib/auth/startOAuthLogin.ts | 5 ++--- 8 files changed, 33 insertions(+), 36 deletions(-) diff --git a/src/components/auth/LoginForm.tsx b/src/components/auth/LoginForm.tsx index 4c88548f..fe7b2a9e 100644 --- a/src/components/auth/LoginForm.tsx +++ b/src/components/auth/LoginForm.tsx @@ -16,8 +16,7 @@ import { useLoginMutation } from "@/hooks/auth/useLoginMutation"; import { getApiErrorMessage } from "@/lib/api/getApiErrorMessage"; import { clearProfileCompleted } from "@/lib/auth/profileCompleted"; import { - getAudienceMismatchMessage, - getAuthAudienceFromRole, + audienceToLoginRole, getLoginRedirectParam, getPostAuthRedirectPath, getRoleHomePath, @@ -37,7 +36,6 @@ 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(null); const { @@ -59,21 +57,14 @@ const LoginForm = ({ audience = "customer" }: LoginFormProps) => { 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), }); diff --git a/src/components/auth/RoleGuard.tsx b/src/components/auth/RoleGuard.tsx index cea297d4..633166d8 100644 --- a/src/components/auth/RoleGuard.tsx +++ b/src/components/auth/RoleGuard.tsx @@ -15,7 +15,7 @@ import { getAccessToken } from "@/lib/auth/token"; import { useAuthStore } from "@/stores/useAuthStore"; interface RoleGuardProps { - allowedRole: Extract; + allowedRole: AuthRole; children: ReactNode; loadingFallback?: ReactNode; } diff --git a/src/hooks/auth/useLoginMutation.ts b/src/hooks/auth/useLoginMutation.ts index dd542e31..f3e7e98c 100644 --- a/src/hooks/auth/useLoginMutation.ts +++ b/src/hooks/auth/useLoginMutation.ts @@ -3,7 +3,8 @@ import { useApiMutation } from "@/hooks/queries/useApiMutation"; /** * 로그인 — fetchInstance(BFF). - * 세션 반영은 audience 검증 후 LoginForm에서 establishSession 호출. + * 세션 반영은 LoginForm에서 establishSession 호출. + * role 불일치는 BE가 토큰 발급 전에 거부한다. */ export const useLoginMutation = () => { return useApiMutation({ diff --git a/src/lib/api/auth.ts b/src/lib/api/auth.ts index f1794baa..8aa7fc37 100644 --- a/src/lib/api/auth.ts +++ b/src/lib/api/auth.ts @@ -1,6 +1,7 @@ import fetchInstance from "@/lib/api/fetchInstance"; import { ensureAccessTokenRefreshed } from "@/lib/auth/refreshAccessToken"; import type { EnsureAccessTokenOptions } from "@/lib/auth/refreshAccessToken"; +import type { AuthRole, LoginRole } from "@/lib/auth/role"; import { setAccessToken } from "@/lib/auth/token"; import { AUTH_BFF_BASE } from "@/lib/constants/authBff"; import { API_ROUTES } from "@/lib/constants/apiRoutes"; @@ -10,6 +11,7 @@ import { OAuthProvider } from "../auth/oauth"; export interface LoginInput { email: string; password: string; + role: LoginRole; } export interface SignUpCustomerInput { @@ -26,7 +28,7 @@ export interface AuthUser { email: string; name: string; phone: string | null; - role: "CUSTOMER" | "MOVER" | "ADMIN"; + role: AuthRole; imageUrl?: string | null; } @@ -98,7 +100,7 @@ export const logout = async (): Promise => { export interface OAuthLoginInput { code: string; - role: "CUSTOMER" | "MOVER"; + role: LoginRole; state?: string; } diff --git a/src/lib/auth/oauth.ts b/src/lib/auth/oauth.ts index 30bedbd7..3160d259 100644 --- a/src/lib/auth/oauth.ts +++ b/src/lib/auth/oauth.ts @@ -1,5 +1,5 @@ -import type { AuthAudience } from "@/lib/auth/redirect"; import { APP_ROUTES } from "@/lib/constants/appRoutes"; +import type { LoginRole } from "@/lib/auth/role"; import { ApiError } from "@/types/api"; export type OAuthProvider = "google" | "kakao" | "naver"; @@ -9,7 +9,7 @@ const OAUTH_STATE_KEY = "moving_oauth_state"; export interface OAuthPendingSession { provider: OAuthProvider; - role: "CUSTOMER" | "MOVER"; + role: LoginRole; returnPath?: string | null; } @@ -19,15 +19,6 @@ interface OAuthAuthorizeConfig { scope?: string; } -// 관리자는 포함 안됨 -export const audienceToOAuthRole = (audience: AuthAudience): "CUSTOMER" | "MOVER" => { - if (audience === "admin") { - throw new ApiError("관리자는 소셜 로그인을 사용할 수 없습니다."); - } - - return audience === "mover" ? "MOVER" : "CUSTOMER"; -}; - /** oauth 대기 세션 저장 */ export const saveOAuthPendingSession = (session: OAuthPendingSession): void => { sessionStorage.setItem(OAUTH_PENDING_KEY, JSON.stringify(session)); diff --git a/src/lib/auth/redirect.ts b/src/lib/auth/redirect.ts index fe8b39d8..0700678f 100644 --- a/src/lib/auth/redirect.ts +++ b/src/lib/auth/redirect.ts @@ -1,11 +1,21 @@ import { getCustomerProfileStatus, getMoverProfileStatus } from "@/lib/api/profile"; import { saveProfileCompleted } from "@/lib/auth/profileCompleted"; -import type { AuthRole } from "@/lib/auth/role"; +import type { AuthRole, LoginRole } from "@/lib/auth/role"; import { APP_ROUTES } from "@/lib/constants/appRoutes"; import { isMoverDetailId } from "@/lib/utils/isMoverDetailId"; +import { ApiError } from "@/types/api"; export type AuthAudience = "customer" | "mover" | "admin"; +/** 로그인 입구 audience → 요청 role. ADMIN 입구는 일반/소셜 로그인에 사용하지 않는다. */ +export const audienceToLoginRole = (audience: AuthAudience): LoginRole => { + if (audience === "admin") { + throw new ApiError("관리자는 이 로그인 경로를 사용할 수 없습니다."); + } + + return audience === "mover" ? "MOVER" : "CUSTOMER"; +}; + const AUTH_PATH_PREFIXES = [ APP_ROUTES.LOGIN, APP_ROUTES.SIGN_UP, diff --git a/src/lib/auth/role.ts b/src/lib/auth/role.ts index 7af8bfea..0d2d3977 100644 --- a/src/lib/auth/role.ts +++ b/src/lib/auth/role.ts @@ -1,4 +1,3 @@ -import type { AuthUser } from "@/lib/api/auth"; import { clearClientStorageHint, getClientStorageHint, @@ -11,7 +10,11 @@ import { export const ROLE_STORAGE_KEY = "moving_role" as const; -export type AuthRole = AuthUser["role"]; +/** 일반 로그인·OAuth 요청에 사용하는 역할 (ADMIN 제외) */ +export type LoginRole = "CUSTOMER" | "MOVER"; + +/** JWT·API·세션용. ADMIN 포함 */ +export type AuthRole = LoginRole | "ADMIN"; /** JWT·API payload용. ADMIN 포함 */ export const parseAuthRole = (value: string | null | undefined): AuthRole | null => { @@ -22,7 +25,7 @@ export const parseAuthRole = (value: string | null | undefined): AuthRole | null }; /** Soft UX(Header/가드 힌트)용. ADMIN·임의 문자열은 무시 */ -export const parseSoftUxAuthRole = (value: string | null | undefined): AuthRole | null => { +export const parseSoftUxAuthRole = (value: string | null | undefined): LoginRole | null => { if (value === "CUSTOMER" || value === "MOVER") { return value; } @@ -36,7 +39,7 @@ export const saveRole = (role: AuthRole): void => { setClientStorageHint(ROLE_STORAGE_KEY, softUxRole); }; -export const loadRole = (): AuthRole | null => { +export const loadRole = (): LoginRole | null => { return parseSoftUxAuthRole(getClientStorageHint(ROLE_STORAGE_KEY)); }; diff --git a/src/lib/auth/startOAuthLogin.ts b/src/lib/auth/startOAuthLogin.ts index ed399c2f..675b1763 100644 --- a/src/lib/auth/startOAuthLogin.ts +++ b/src/lib/auth/startOAuthLogin.ts @@ -1,13 +1,12 @@ import { getNaverOAuthState } from "@/lib/api/auth"; import { - audienceToOAuthRole, buildOAuthAuthorizeUrl, clearOAuthPendingSession, saveOAuthClientState, saveOAuthPendingSession, type OAuthProvider, } from "@/lib/auth/oauth"; -import { getLoginRedirectParam, type AuthAudience } from "@/lib/auth/redirect"; +import { audienceToLoginRole, getLoginRedirectParam, type AuthAudience } from "@/lib/auth/redirect"; /** * SNS 로그인 시작 — pending 저장 후 Provider 인가 화면으로 이동합니다. @@ -16,7 +15,7 @@ export const startOAuthLogin = async ( provider: OAuthProvider, audience: AuthAudience, ): Promise => { - const role = audienceToOAuthRole(audience); + const role = audienceToLoginRole(audience); saveOAuthPendingSession({ provider, From 9c906a01c34db37974d21353e7db1d837fca8414 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 02:23:04 +0900 Subject: [PATCH 03/11] =?UTF-8?q?fix:=20=EA=B3=A0=EA=B0=9D,=20=EA=B8=B0?= =?UTF-8?q?=EC=82=AC=20=ED=94=84=EB=A1=9C=ED=95=84=20=EC=83=9D=EC=84=B1=20?= =?UTF-8?q?=EB=B0=8F=20=EC=88=98=EC=A0=95=20=EC=8B=9C=20input=20=EB=82=B4?= =?UTF-8?q?=EB=B6=80=20enter=3Dsubmit=20=EB=A7=89=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/profile/CustomerProfileEditForm.tsx | 2 ++ src/components/profile/CustomerProfileForm.tsx | 2 ++ src/components/profile/MoverBasicInfoEditForm.tsx | 2 ++ src/components/profile/MoverProfileEditForm.tsx | 2 ++ src/components/profile/MoverProfileForm.tsx | 2 ++ src/lib/utils/preventEnterSubmitOnInput.ts | 12 ++++++++++++ 6 files changed, 22 insertions(+) create mode 100644 src/lib/utils/preventEnterSubmitOnInput.ts diff --git a/src/components/profile/CustomerProfileEditForm.tsx b/src/components/profile/CustomerProfileEditForm.tsx index a17763df..4f4543c1 100644 --- a/src/components/profile/CustomerProfileEditForm.tsx +++ b/src/components/profile/CustomerProfileEditForm.tsx @@ -24,6 +24,7 @@ import { customerProfileEditSchema, type CustomerProfileEditFormValues, } from "@/lib/schemas/customerProfileEditSchema"; +import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; import { ApiError } from "@/types/api"; import type { MoveType } from "@/types/move"; @@ -171,6 +172,7 @@ const CustomerProfileEditForm = ({
diff --git a/src/components/profile/CustomerProfileForm.tsx b/src/components/profile/CustomerProfileForm.tsx index d9879104..e5165142 100644 --- a/src/components/profile/CustomerProfileForm.tsx +++ b/src/components/profile/CustomerProfileForm.tsx @@ -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"; @@ -100,6 +101,7 @@ const CustomerProfileForm = ({ diff --git a/src/components/profile/MoverBasicInfoEditForm.tsx b/src/components/profile/MoverBasicInfoEditForm.tsx index fde452ba..579b29ea 100644 --- a/src/components/profile/MoverBasicInfoEditForm.tsx +++ b/src/components/profile/MoverBasicInfoEditForm.tsx @@ -19,6 +19,7 @@ import { } from "@/lib/schemas/moverBasicInfoEditSchema"; import { toPasswordChangePayload } from "@/lib/schemas/passwordChangeFields"; import { cn } from "@/lib/utils/cn"; +import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; import { ApiError } from "@/types/api"; interface MoverBasicInfoEditFormProps { @@ -106,6 +107,7 @@ const MoverBasicInfoEditForm = ({ diff --git a/src/components/profile/MoverProfileEditForm.tsx b/src/components/profile/MoverProfileEditForm.tsx index 1d7b3e70..3b0ee3e8 100644 --- a/src/components/profile/MoverProfileEditForm.tsx +++ b/src/components/profile/MoverProfileEditForm.tsx @@ -19,6 +19,7 @@ import { MOVE_TYPE_OPTIONS } from "@/lib/constants/moveType"; import { REGION_OPTIONS, type RegionId } from "@/lib/constants/region"; import { uploadProfileImage } from "@/lib/profile/uploadProfileImage"; import { moverProfileSchema, type MoverProfileFormValues } from "@/lib/schemas/moverProfileSchema"; +import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; import { ApiError } from "@/types/api"; import type { MoveType } from "@/types/move"; @@ -97,6 +98,7 @@ const MoverProfileEditForm = ({ diff --git a/src/components/profile/MoverProfileForm.tsx b/src/components/profile/MoverProfileForm.tsx index ee5d089b..5675b7c3 100644 --- a/src/components/profile/MoverProfileForm.tsx +++ b/src/components/profile/MoverProfileForm.tsx @@ -23,6 +23,7 @@ import { createMoverProfileSchema, type MoverProfileFormValues, } from "@/lib/schemas/moverProfileSchema"; +import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; import { ApiError } from "@/types/api"; import type { MoveType } from "@/types/move"; @@ -113,6 +114,7 @@ const MoverProfileForm = ({ diff --git a/src/lib/utils/preventEnterSubmitOnInput.ts b/src/lib/utils/preventEnterSubmitOnInput.ts new file mode 100644 index 00000000..c9a7248b --- /dev/null +++ b/src/lib/utils/preventEnterSubmitOnInput.ts @@ -0,0 +1,12 @@ +import type { KeyboardEvent } from "react"; + +/** + * 한 줄 input에서 Enter로 form이 submit되는 기본 동작을 막습니다. + * textarea·button 등 input이 아닌 요소에서는 동작하지 않습니다. + */ +export const preventEnterSubmitOnInput = (event: KeyboardEvent) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return; + if (!(event.target instanceof HTMLInputElement)) return; + + event.preventDefault(); +}; From ea9881ba5c0adf264f0c9e3d62a1d46e0aa56a33 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 02:32:40 +0900 Subject: [PATCH 04/11] =?UTF-8?q?fix:=20=ED=8F=BC=20=EC=88=98=EC=A0=95?= =?UTF-8?q?=EC=82=AC=ED=95=AD=20=EC=97=86=EC=9D=84=20=EB=95=8C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95=ED=95=98=EA=B8=B0=20=EB=B2=84=ED=8A=BC=20disabled?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../profile/CustomerProfileEditForm.tsx | 4 ++-- .../profile/MoverBasicInfoEditForm.tsx | 18 ++++++++++++------ .../profile/MoverProfileEditForm.tsx | 12 ++++++++++-- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/components/profile/CustomerProfileEditForm.tsx b/src/components/profile/CustomerProfileEditForm.tsx index 4f4543c1..b7869a70 100644 --- a/src/components/profile/CustomerProfileEditForm.tsx +++ b/src/components/profile/CustomerProfileEditForm.tsx @@ -58,7 +58,7 @@ const CustomerProfileEditForm = ({ getValues, reset, resetField, - formState: { errors, isValid, isSubmitting, dirtyFields }, + formState: { errors, isValid, isSubmitting, dirtyFields, isDirty }, } = useForm({ resolver: zodResolver(customerProfileEditSchema), mode: "onChange", @@ -312,7 +312,7 @@ const CustomerProfileEditForm = ({ ) : null} - + {toastMessage ? setToastMessage(null)}>{toastMessage} : null} diff --git a/src/components/profile/MoverBasicInfoEditForm.tsx b/src/components/profile/MoverBasicInfoEditForm.tsx index 579b29ea..d499c990 100644 --- a/src/components/profile/MoverBasicInfoEditForm.tsx +++ b/src/components/profile/MoverBasicInfoEditForm.tsx @@ -42,8 +42,9 @@ const MoverBasicInfoEditForm = ({ handleSubmit, setError, setFocus, - setValue, - formState: { errors, isValid, isSubmitting }, + getValues, + reset, + formState: { errors, isValid, isSubmitting, isDirty }, } = useForm({ resolver: zodResolver(moverBasicInfoEditSchema), mode: "onChange", @@ -68,9 +69,14 @@ const MoverBasicInfoEditForm = ({ phone: formValues.phone, ...(hasPassword ? toPasswordChangePayload(formValues) : {}), }); - setValue("currentPassword", "", { shouldValidate: true }); - setValue("newPassword", "", { shouldValidate: true }); - setValue("newPasswordConfirm", "", { shouldValidate: true }); + + const current = getValues(); + reset({ + ...current, + currentPassword: "", + newPassword: "", + newPasswordConfirm: "", + }); setToastMessage("기본정보가 수정되었습니다."); } catch (error) { if ( @@ -192,7 +198,7 @@ const MoverBasicInfoEditForm = ({ ) : null} diff --git a/src/components/profile/MoverProfileEditForm.tsx b/src/components/profile/MoverProfileEditForm.tsx index 3b0ee3e8..4767fb45 100644 --- a/src/components/profile/MoverProfileEditForm.tsx +++ b/src/components/profile/MoverProfileEditForm.tsx @@ -42,7 +42,9 @@ const MoverProfileEditForm = ({ handleSubmit, setError, setFocus, - formState: { errors, isValid, isSubmitting }, + getValues, + reset, + formState: { errors, isValid, isSubmitting, isDirty }, } = useForm({ resolver: zodResolver(moverProfileSchema), mode: "onChange", @@ -75,6 +77,12 @@ const MoverProfileEditForm = ({ serviceTypes: formValues.serviceTypes, ...(imageKey ? { imageUrl: imageKey } : {}), }); + + const current = getValues(); + reset({ + ...current, + imageFile: null, + }); setToastMessage("프로필이 수정되었습니다."); } catch (error) { if ( @@ -210,7 +218,7 @@ const MoverProfileEditForm = ({ ) : null} - + {toastMessage ? setToastMessage(null)}>{toastMessage} : null} From 1c2de62a40dee40015ca6ce77bbeb51fac1e4bd8 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 02:53:18 +0900 Subject: [PATCH 05/11] =?UTF-8?q?fix:=20=EB=B9=84=EB=B0=80=EB=B2=88?= =?UTF-8?q?=ED=98=B8=20=EB=B3=80=EA=B2=BD=20=EC=8B=9C=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=9D=B8=20=ED=8E=98=EC=9D=B4=EC=A7=80=EB=A1=9C=20=EC=9D=B4?= =?UTF-8?q?=EB=8F=99=20(toast=20=EC=95=8C=EB=A6=BC=20=EC=B6=94=EA=B0=80)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/auth/LoginForm.tsx | 18 ++++++++++-- .../profile/CustomerProfileEditForm.tsx | 28 +++++++++++++++++++ .../profile/MoverBasicInfoEditForm.tsx | 20 ++++++++++++- src/lib/auth/passwordChangedToast.ts | 25 +++++++++++++++++ 4 files changed, 88 insertions(+), 3 deletions(-) create mode 100644 src/lib/auth/passwordChangedToast.ts diff --git a/src/components/auth/LoginForm.tsx b/src/components/auth/LoginForm.tsx index fe7b2a9e..5760eae1 100644 --- a/src/components/auth/LoginForm.tsx +++ b/src/components/auth/LoginForm.tsx @@ -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"; @@ -12,8 +12,11 @@ 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 { audienceToLoginRole, @@ -26,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; @@ -37,6 +39,7 @@ const LoginForm = ({ audience = "customer" }: LoginFormProps) => { const establishSession = useAuthStore((state) => state.establishSession); const setPostAuthRedirectPath = useAuthStore((state) => state.setPostAuthRedirectPath); const [submitError, setSubmitError] = useState(null); + const [toastMessage, setToastMessage] = useState(null); const { register, @@ -51,6 +54,16 @@ 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) => { @@ -78,6 +91,7 @@ const LoginForm = ({ audience = "customer" }: LoginFormProps) => { return (
+ {toastMessage ? setToastMessage(null)}>{toastMessage} : null}
diff --git a/src/components/profile/CustomerProfileEditForm.tsx b/src/components/profile/CustomerProfileEditForm.tsx index b7869a70..d9c89a1a 100644 --- a/src/components/profile/CustomerProfileEditForm.tsx +++ b/src/components/profile/CustomerProfileEditForm.tsx @@ -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 { markPasswordChangedToast } from "@/lib/auth/passwordChangedToast"; +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"; @@ -25,6 +27,7 @@ import { type CustomerProfileEditFormValues, } from "@/lib/schemas/customerProfileEditSchema"; import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; +import { useAuthStore } from "@/stores/useAuthStore"; import { ApiError } from "@/types/api"; import type { MoveType } from "@/types/move"; @@ -46,6 +49,7 @@ const CustomerProfileEditForm = ({ }: CustomerProfileEditFormProps) => { const updateCustomerBasicInfo = useUpdateCustomerBasicInfo(); const updateCustomerProfile = useUpdateCustomerProfile(); + const logout = useAuthStore((state) => state.logout); const [submitError, setSubmitError] = useState(null); const [toastMessage, setToastMessage] = useState(null); @@ -100,6 +104,7 @@ const CustomerProfileEditForm = ({ return; } + const didChangePassword = Boolean(basic?.currentPassword && basic?.newPassword); let didBasicSucceed = false; if (basic) { @@ -120,6 +125,18 @@ const CustomerProfileEditForm = ({ try { await updateCustomerProfile.mutateAsync(profile); } catch (profileError) { + if (didBasicSucceed && didChangePassword) { + // refresh token 이미 폐기됨 → 머무르면 F5 시 강제 로그아웃만 발생 + markPasswordChangedToast(); + try { + await logout({ deferUiClear: true }); + } catch { + // refresh 폐기 후 logout API 실패해도 로컬 세션은 정리됨 + } + window.location.assign(APP_ROUTES.LOGIN); + return; + } + if (didBasicSucceed) { setSubmitError(PROFILE_PARTIAL_SAVE_ERROR); return; @@ -129,6 +146,17 @@ const CustomerProfileEditForm = ({ } } + if (didChangePassword) { + markPasswordChangedToast(); + try { + await logout({ deferUiClear: true }); + } catch { + // refresh 폐기 후 logout API 실패해도 로컬 세션은 정리됨 + } + window.location.assign(APP_ROUTES.LOGIN); + return; + } + const current = getValues(); reset({ ...current, diff --git a/src/components/profile/MoverBasicInfoEditForm.tsx b/src/components/profile/MoverBasicInfoEditForm.tsx index d499c990..e6344545 100644 --- a/src/components/profile/MoverBasicInfoEditForm.tsx +++ b/src/components/profile/MoverBasicInfoEditForm.tsx @@ -13,6 +13,8 @@ import ProfileFormActions from "@/components/profile/ProfileFormActions"; import ProfilePageHeader from "@/components/profile/ProfilePageHeader"; import { useUpdateMoverBasicInfo } from "@/hooks/profile/useUpdateMoverBasicInfo"; import { getApiErrorMessage } from "@/lib/api/getApiErrorMessage"; +import { markPasswordChangedToast } from "@/lib/auth/passwordChangedToast"; +import { APP_ROUTES } from "@/lib/constants/appRoutes"; import { moverBasicInfoEditSchema, type MoverBasicInfoEditFormValues, @@ -20,6 +22,7 @@ import { import { toPasswordChangePayload } from "@/lib/schemas/passwordChangeFields"; import { cn } from "@/lib/utils/cn"; import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; +import { useAuthStore } from "@/stores/useAuthStore"; import { ApiError } from "@/types/api"; interface MoverBasicInfoEditFormProps { @@ -34,6 +37,7 @@ const MoverBasicInfoEditForm = ({ defaultValues, }: MoverBasicInfoEditFormProps) => { const updateMoverBasicInfo = useUpdateMoverBasicInfo(); + const logout = useAuthStore((state) => state.logout); const [submitError, setSubmitError] = useState(null); const [toastMessage, setToastMessage] = useState(null); @@ -64,12 +68,26 @@ const MoverBasicInfoEditForm = ({ setSubmitError(null); try { + const passwordPayload = hasPassword ? toPasswordChangePayload(formValues) : {}; + const didChangePassword = Object.keys(passwordPayload).length > 0; + await updateMoverBasicInfo.mutateAsync({ name: formValues.name, phone: formValues.phone, - ...(hasPassword ? toPasswordChangePayload(formValues) : {}), + ...passwordPayload, }); + if (didChangePassword) { + markPasswordChangedToast(); + try { + await logout({ deferUiClear: true }); + } catch { + // refresh 폐기 후 logout API 실패해도 로컬 세션은 정리됨 + } + window.location.assign(APP_ROUTES.MOVER_LOGIN); + return; + } + const current = getValues(); reset({ ...current, diff --git a/src/lib/auth/passwordChangedToast.ts b/src/lib/auth/passwordChangedToast.ts new file mode 100644 index 00000000..6fcebb39 --- /dev/null +++ b/src/lib/auth/passwordChangedToast.ts @@ -0,0 +1,25 @@ +/** 비밀번호 변경 성공 → 로그인 페이지 one-shot Toast */ +export const PASSWORD_CHANGED_TOAST_KEY = "moving:password-changed-toast"; + +export const PASSWORD_CHANGED_TOAST_MESSAGE = "비밀번호가 변경되었습니다. 다시 로그인해 주세요."; + +export const markPasswordChangedToast = (): void => { + try { + sessionStorage.setItem(PASSWORD_CHANGED_TOAST_KEY, "1"); + } catch { + // sessionStorage 불가 환경에서는 Toast 없이 이동 + } +}; + +export const consumePasswordChangedToast = (): string | null => { + try { + if (sessionStorage.getItem(PASSWORD_CHANGED_TOAST_KEY) === "1") { + sessionStorage.removeItem(PASSWORD_CHANGED_TOAST_KEY); + return PASSWORD_CHANGED_TOAST_MESSAGE; + } + } catch { + // ignore + } + + return null; +}; From 8719482c4603e89fd964447529d82b6fb91e6575 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 03:31:07 +0900 Subject: [PATCH 06/11] =?UTF-8?q?fix:=20scroll=20rock=20=EC=B2=98=EB=A6=AC?= =?UTF-8?q?=EB=A5=BC=20=EC=9C=84=ED=95=9C=20=ED=9B=85=20=EC=83=9D=EC=84=B1?= =?UTF-8?q?=20=EB=B0=8F=20scroll=20freezing=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/Header/HeaderSideNav.tsx | 15 +---- src/components/common/Modal/ModalMain.tsx | 19 +----- src/hooks/useBodyScrollLock.ts | 61 +++++++++++++++++++ 3 files changed, 65 insertions(+), 30 deletions(-) create mode 100644 src/hooks/useBodyScrollLock.ts diff --git a/src/components/common/Header/HeaderSideNav.tsx b/src/components/common/Header/HeaderSideNav.tsx index b581a38c..bf3e7309 100644 --- a/src/components/common/Header/HeaderSideNav.tsx +++ b/src/components/common/Header/HeaderSideNav.tsx @@ -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"; @@ -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) => { if (event.target !== event.currentTarget) return; diff --git a/src/components/common/Modal/ModalMain.tsx b/src/components/common/Modal/ModalMain.tsx index 7bc17aac..5ebe9bc5 100644 --- a/src/components/common/Modal/ModalMain.tsx +++ b/src/components/common/Modal/ModalMain.tsx @@ -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"; @@ -96,23 +97,7 @@ 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]); + useBodyScrollLock(open); useFocusTrap({ containerRef: panelRef, diff --git a/src/hooks/useBodyScrollLock.ts b/src/hooks/useBodyScrollLock.ts new file mode 100644 index 00000000..14ec85a8 --- /dev/null +++ b/src/hooks/useBodyScrollLock.ts @@ -0,0 +1,61 @@ +"use client"; + +import { useEffect } from "react"; + +let lockCount = 0; +let previousOverflow = ""; +let previousPaddingRight = ""; + +/** + * body 스크롤을 잠급니다. + * 이미 잠금 중이면 스타일은 다시 건드리지 않고 lockCount만 올립니다. + * (Modal + SideNav처럼 중첩 오픈 시 한쪽이 닫혀도 스크롤이 풀리지 않도록) + */ +const lockBodyScroll = () => { + if (lockCount === 0) { + // 잠금 해제 시 원래 인라인 스타일로 되돌리기 위해 보관 + previousOverflow = document.body.style.overflow; + previousPaddingRight = document.body.style.paddingRight; + + // overflow: hidden 시 스크롤바가 사라져 레이아웃이 흔들리지 않도록 보정 + const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth; + document.body.style.overflow = "hidden"; + if (scrollbarWidth > 0) { + document.body.style.paddingRight = `${scrollbarWidth}px`; + } + } + + lockCount += 1; +}; + +/** + * 잠금 참조를 하나 줄입니다. + * lockCount가 0이 될 때만 실제 스크롤 잠금을 해제합니다. + */ +const unlockBodyScroll = () => { + // 언락이 락보다 많이 호출되어도 음수가 되지 않도록 방어 + lockCount = Math.max(0, lockCount - 1); + + if (lockCount === 0) { + document.body.style.overflow = previousOverflow; + document.body.style.paddingRight = previousPaddingRight; + } +}; + +/** + * overlay(Modal, SideNav 등)가 열려 있는 동안 body 스크롤을 잠급니다. + * 중첩 잠금은 참조 카운트로 관리해, 한쪽이 닫혀도 다른 잠금이 남아 있으면 유지합니다. + */ +export function useBodyScrollLock(locked: boolean): void { + useEffect(() => { + if (!locked) { + return; + } + + lockBodyScroll(); + + return () => { + unlockBodyScroll(); + }; + }, [locked]); +} From 370055f7c39d5fcb57824e1d8010c478ed05dee1 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 03:51:45 +0900 Subject: [PATCH 07/11] =?UTF-8?q?fix:=20=EC=A4=91=EB=B3=B5=20=EB=A1=9C?= =?UTF-8?q?=EC=A7=81=20=ED=95=A9=EC=B9=A8,=20modal=20isOpne->isRendered=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../(auth)/oauth/[provider]/callback/page.tsx | 2 +- src/components/common/Modal/ModalMain.tsx | 3 ++- .../profile/CustomerProfileEditForm.tsx | 23 ++++--------------- .../profile/MoverBasicInfoEditForm.tsx | 19 ++++++--------- src/hooks/useBodyScrollLock.ts | 4 ++-- src/lib/auth/reauthAfterPasswordChange.ts | 18 +++++++++++++++ src/lib/schemas/passwordChangeFields.ts | 5 ++++ 7 files changed, 40 insertions(+), 34 deletions(-) create mode 100644 src/lib/auth/reauthAfterPasswordChange.ts diff --git a/src/app/(auth)/oauth/[provider]/callback/page.tsx b/src/app/(auth)/oauth/[provider]/callback/page.tsx index ee4d109e..3b8822bd 100644 --- a/src/app/(auth)/oauth/[provider]/callback/page.tsx +++ b/src/app/(auth)/oauth/[provider]/callback/page.tsx @@ -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); diff --git a/src/components/common/Modal/ModalMain.tsx b/src/components/common/Modal/ModalMain.tsx index 5ebe9bc5..8ca289d3 100644 --- a/src/components/common/Modal/ModalMain.tsx +++ b/src/components/common/Modal/ModalMain.tsx @@ -97,7 +97,8 @@ const ModalMain = ({ useCloseOnPathnameChange(isVisible ? onClose : undefined); - useBodyScrollLock(open); + // exit 애니메이션 동안(isRendered)에도 스크롤 잠금 유지 + useBodyScrollLock(isRendered); useFocusTrap({ containerRef: panelRef, diff --git a/src/components/profile/CustomerProfileEditForm.tsx b/src/components/profile/CustomerProfileEditForm.tsx index d9c89a1a..d2f9a1a8 100644 --- a/src/components/profile/CustomerProfileEditForm.tsx +++ b/src/components/profile/CustomerProfileEditForm.tsx @@ -16,7 +16,7 @@ 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 { markPasswordChangedToast } from "@/lib/auth/passwordChangedToast"; +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"; @@ -26,8 +26,8 @@ import { customerProfileEditSchema, type CustomerProfileEditFormValues, } from "@/lib/schemas/customerProfileEditSchema"; +import { hasPasswordChangePayload } from "@/lib/schemas/passwordChangeFields"; import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; -import { useAuthStore } from "@/stores/useAuthStore"; import { ApiError } from "@/types/api"; import type { MoveType } from "@/types/move"; @@ -49,7 +49,6 @@ const CustomerProfileEditForm = ({ }: CustomerProfileEditFormProps) => { const updateCustomerBasicInfo = useUpdateCustomerBasicInfo(); const updateCustomerProfile = useUpdateCustomerProfile(); - const logout = useAuthStore((state) => state.logout); const [submitError, setSubmitError] = useState(null); const [toastMessage, setToastMessage] = useState(null); @@ -104,7 +103,7 @@ const CustomerProfileEditForm = ({ return; } - const didChangePassword = Boolean(basic?.currentPassword && basic?.newPassword); + const didChangePassword = hasPasswordChangePayload(basic); let didBasicSucceed = false; if (basic) { @@ -127,13 +126,7 @@ const CustomerProfileEditForm = ({ } catch (profileError) { if (didBasicSucceed && didChangePassword) { // refresh token 이미 폐기됨 → 머무르면 F5 시 강제 로그아웃만 발생 - markPasswordChangedToast(); - try { - await logout({ deferUiClear: true }); - } catch { - // refresh 폐기 후 logout API 실패해도 로컬 세션은 정리됨 - } - window.location.assign(APP_ROUTES.LOGIN); + await reauthAfterPasswordChange(APP_ROUTES.LOGIN); return; } @@ -147,13 +140,7 @@ const CustomerProfileEditForm = ({ } if (didChangePassword) { - markPasswordChangedToast(); - try { - await logout({ deferUiClear: true }); - } catch { - // refresh 폐기 후 logout API 실패해도 로컬 세션은 정리됨 - } - window.location.assign(APP_ROUTES.LOGIN); + await reauthAfterPasswordChange(APP_ROUTES.LOGIN); return; } diff --git a/src/components/profile/MoverBasicInfoEditForm.tsx b/src/components/profile/MoverBasicInfoEditForm.tsx index e6344545..ad11fee9 100644 --- a/src/components/profile/MoverBasicInfoEditForm.tsx +++ b/src/components/profile/MoverBasicInfoEditForm.tsx @@ -13,16 +13,18 @@ import ProfileFormActions from "@/components/profile/ProfileFormActions"; import ProfilePageHeader from "@/components/profile/ProfilePageHeader"; import { useUpdateMoverBasicInfo } from "@/hooks/profile/useUpdateMoverBasicInfo"; import { getApiErrorMessage } from "@/lib/api/getApiErrorMessage"; -import { markPasswordChangedToast } from "@/lib/auth/passwordChangedToast"; +import { reauthAfterPasswordChange } from "@/lib/auth/reauthAfterPasswordChange"; import { APP_ROUTES } from "@/lib/constants/appRoutes"; import { moverBasicInfoEditSchema, type MoverBasicInfoEditFormValues, } from "@/lib/schemas/moverBasicInfoEditSchema"; -import { toPasswordChangePayload } from "@/lib/schemas/passwordChangeFields"; +import { + hasPasswordChangePayload, + toPasswordChangePayload, +} from "@/lib/schemas/passwordChangeFields"; import { cn } from "@/lib/utils/cn"; import { preventEnterSubmitOnInput } from "@/lib/utils/preventEnterSubmitOnInput"; -import { useAuthStore } from "@/stores/useAuthStore"; import { ApiError } from "@/types/api"; interface MoverBasicInfoEditFormProps { @@ -37,7 +39,6 @@ const MoverBasicInfoEditForm = ({ defaultValues, }: MoverBasicInfoEditFormProps) => { const updateMoverBasicInfo = useUpdateMoverBasicInfo(); - const logout = useAuthStore((state) => state.logout); const [submitError, setSubmitError] = useState(null); const [toastMessage, setToastMessage] = useState(null); @@ -69,7 +70,7 @@ const MoverBasicInfoEditForm = ({ try { const passwordPayload = hasPassword ? toPasswordChangePayload(formValues) : {}; - const didChangePassword = Object.keys(passwordPayload).length > 0; + const didChangePassword = hasPasswordChangePayload(passwordPayload); await updateMoverBasicInfo.mutateAsync({ name: formValues.name, @@ -78,13 +79,7 @@ const MoverBasicInfoEditForm = ({ }); if (didChangePassword) { - markPasswordChangedToast(); - try { - await logout({ deferUiClear: true }); - } catch { - // refresh 폐기 후 logout API 실패해도 로컬 세션은 정리됨 - } - window.location.assign(APP_ROUTES.MOVER_LOGIN); + await reauthAfterPasswordChange(APP_ROUTES.MOVER_LOGIN); return; } diff --git a/src/hooks/useBodyScrollLock.ts b/src/hooks/useBodyScrollLock.ts index 14ec85a8..4f3e17c1 100644 --- a/src/hooks/useBodyScrollLock.ts +++ b/src/hooks/useBodyScrollLock.ts @@ -46,7 +46,7 @@ const unlockBodyScroll = () => { * overlay(Modal, SideNav 등)가 열려 있는 동안 body 스크롤을 잠급니다. * 중첩 잠금은 참조 카운트로 관리해, 한쪽이 닫혀도 다른 잠금이 남아 있으면 유지합니다. */ -export function useBodyScrollLock(locked: boolean): void { +export const useBodyScrollLock = (locked: boolean): void => { useEffect(() => { if (!locked) { return; @@ -58,4 +58,4 @@ export function useBodyScrollLock(locked: boolean): void { unlockBodyScroll(); }; }, [locked]); -} +}; diff --git a/src/lib/auth/reauthAfterPasswordChange.ts b/src/lib/auth/reauthAfterPasswordChange.ts new file mode 100644 index 00000000..380b4c92 --- /dev/null +++ b/src/lib/auth/reauthAfterPasswordChange.ts @@ -0,0 +1,18 @@ +import { markPasswordChangedToast } from "@/lib/auth/passwordChangedToast"; +import { useAuthStore } from "@/stores/useAuthStore"; + +/** + * 비밀번호 변경 후 refresh가 폐기된 상태이므로 + * Toast 플래그를 남기고 로컬 세션을 정리한 뒤 로그인 페이지로 이동합니다. + */ +export const reauthAfterPasswordChange = async (loginPath: string): Promise => { + markPasswordChangedToast(); + + try { + await useAuthStore.getState().logout({ deferUiClear: true }); + } catch { + // refresh 폐기 후 logout API 실패해도 로컬 세션은 정리됨 + } + + window.location.assign(loginPath); +}; diff --git a/src/lib/schemas/passwordChangeFields.ts b/src/lib/schemas/passwordChangeFields.ts index bea32a9c..317250c0 100644 --- a/src/lib/schemas/passwordChangeFields.ts +++ b/src/lib/schemas/passwordChangeFields.ts @@ -66,3 +66,8 @@ export const toPasswordChangePayload = ( newPasswordConfirm: values.newPasswordConfirm, }; }; + +/** basic/password payload에 실제 비밀번호 변경 필드가 포함됐는지 */ +export const hasPasswordChangePayload = ( + payload: { currentPassword?: string; newPassword?: string } | null | undefined, +): boolean => Boolean(payload?.currentPassword && payload?.newPassword); From a86b0ad6a9a867192ec91198bb6194fa4f51163c Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 03:57:33 +0900 Subject: [PATCH 08/11] =?UTF-8?q?fix:=20customer=20basicInfo=EC=84=B1?= =?UTF-8?q?=EA=B3=B5,=20profile=EC=8B=A4=ED=8C=A8=20=EC=8B=9C=20toast=20?= =?UTF-8?q?=EC=95=88=EB=82=B4=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../profile/CustomerProfileEditForm.tsx | 2 +- src/lib/auth/passwordChangedToast.ts | 33 ++++++++++++++++--- src/lib/auth/reauthAfterPasswordChange.ts | 12 +++++-- src/stores/useAuthStore.ts | 12 +++++-- 4 files changed, 49 insertions(+), 10 deletions(-) diff --git a/src/components/profile/CustomerProfileEditForm.tsx b/src/components/profile/CustomerProfileEditForm.tsx index d2f9a1a8..eb2f3e0a 100644 --- a/src/components/profile/CustomerProfileEditForm.tsx +++ b/src/components/profile/CustomerProfileEditForm.tsx @@ -126,7 +126,7 @@ const CustomerProfileEditForm = ({ } catch (profileError) { if (didBasicSucceed && didChangePassword) { // refresh token 이미 폐기됨 → 머무르면 F5 시 강제 로그아웃만 발생 - await reauthAfterPasswordChange(APP_ROUTES.LOGIN); + await reauthAfterPasswordChange(APP_ROUTES.LOGIN, { profileFailed: true }); return; } diff --git a/src/lib/auth/passwordChangedToast.ts b/src/lib/auth/passwordChangedToast.ts index 6fcebb39..0c4b5db6 100644 --- a/src/lib/auth/passwordChangedToast.ts +++ b/src/lib/auth/passwordChangedToast.ts @@ -3,9 +3,28 @@ export const PASSWORD_CHANGED_TOAST_KEY = "moving:password-changed-toast"; export const PASSWORD_CHANGED_TOAST_MESSAGE = "비밀번호가 변경되었습니다. 다시 로그인해 주세요."; -export const markPasswordChangedToast = (): void => { +export const PASSWORD_CHANGED_PROFILE_FAILED_TOAST_MESSAGE = + "비밀번호는 변경되었습니다. 프로필 일부 저장에 실패해 다시 로그인한 뒤 확인해 주세요."; + +/** sessionStorage 직렬화용 플래그 */ +const PASSWORD_CHANGED_TOAST_FLAG = { + DEFAULT: "1", + PROFILE_FAILED: "profile-failed", +} as const; + +type PasswordChangedToastFlag = + (typeof PASSWORD_CHANGED_TOAST_FLAG)[keyof typeof PASSWORD_CHANGED_TOAST_FLAG]; + +export interface MarkPasswordChangedToastOptions { + profileFailed?: boolean; +} + +export const markPasswordChangedToast = (options?: MarkPasswordChangedToastOptions): void => { try { - sessionStorage.setItem(PASSWORD_CHANGED_TOAST_KEY, "1"); + const flag: PasswordChangedToastFlag = options?.profileFailed + ? PASSWORD_CHANGED_TOAST_FLAG.PROFILE_FAILED + : PASSWORD_CHANGED_TOAST_FLAG.DEFAULT; + sessionStorage.setItem(PASSWORD_CHANGED_TOAST_KEY, flag); } catch { // sessionStorage 불가 환경에서는 Toast 없이 이동 } @@ -13,9 +32,15 @@ export const markPasswordChangedToast = (): void => { export const consumePasswordChangedToast = (): string | null => { try { - if (sessionStorage.getItem(PASSWORD_CHANGED_TOAST_KEY) === "1") { + const flag = sessionStorage.getItem(PASSWORD_CHANGED_TOAST_KEY); + if ( + flag === PASSWORD_CHANGED_TOAST_FLAG.DEFAULT || + flag === PASSWORD_CHANGED_TOAST_FLAG.PROFILE_FAILED + ) { sessionStorage.removeItem(PASSWORD_CHANGED_TOAST_KEY); - return PASSWORD_CHANGED_TOAST_MESSAGE; + return flag === PASSWORD_CHANGED_TOAST_FLAG.PROFILE_FAILED + ? PASSWORD_CHANGED_PROFILE_FAILED_TOAST_MESSAGE + : PASSWORD_CHANGED_TOAST_MESSAGE; } } catch { // ignore diff --git a/src/lib/auth/reauthAfterPasswordChange.ts b/src/lib/auth/reauthAfterPasswordChange.ts index 380b4c92..bd3ba90e 100644 --- a/src/lib/auth/reauthAfterPasswordChange.ts +++ b/src/lib/auth/reauthAfterPasswordChange.ts @@ -1,12 +1,18 @@ -import { markPasswordChangedToast } from "@/lib/auth/passwordChangedToast"; +import { + markPasswordChangedToast, + type MarkPasswordChangedToastOptions, +} from "@/lib/auth/passwordChangedToast"; import { useAuthStore } from "@/stores/useAuthStore"; /** * 비밀번호 변경 후 refresh가 폐기된 상태이므로 * Toast 플래그를 남기고 로컬 세션을 정리한 뒤 로그인 페이지로 이동합니다. */ -export const reauthAfterPasswordChange = async (loginPath: string): Promise => { - markPasswordChangedToast(); +export const reauthAfterPasswordChange = async ( + loginPath: string, + options?: MarkPasswordChangedToastOptions, +): Promise => { + markPasswordChangedToast(options); try { await useAuthStore.getState().logout({ deferUiClear: true }); diff --git a/src/stores/useAuthStore.ts b/src/stores/useAuthStore.ts index 3a54c2d5..cf90f921 100644 --- a/src/stores/useAuthStore.ts +++ b/src/stores/useAuthStore.ts @@ -14,7 +14,11 @@ import { getAccessTokenPayload, getAccessTokenRole } from "@/lib/auth/accessToke import { isAuthPagePath, isOAuthCallbackPath } from "@/lib/auth/redirect"; import { clearAllClientStorageHints } from "@/lib/auth/clientStorageHint"; import { loadNickname, saveNickname } from "@/lib/auth/nickname"; -import { loadProfileImage, saveProfileImage } from "@/lib/auth/profileImage"; +import { + loadProfileImage, + saveProfileImage, + sanitizeSoftUxProfileImageUrl, +} from "@/lib/auth/profileImage"; import { loadRole, saveRole } from "@/lib/auth/role"; import { clearAuthTokens, getAccessToken } from "@/lib/auth/token"; import { clearAppQueryCache } from "@/providers/query/appQueryClient"; @@ -83,10 +87,14 @@ const setAuthenticatedUser = ( saveProfileImage(user.imageUrl ?? ""); } + // Soft UX 힌트만 sanitize. user.imageUrl(원본)은 그대로 유지 + const softUxProfileImage = + user.imageUrl === undefined ? undefined : sanitizeSoftUxProfileImageUrl(user.imageUrl); + set({ user, displayName: user.name, - ...(user.imageUrl !== undefined && { profileImage: user.imageUrl }), + ...(softUxProfileImage !== undefined && { profileImage: softUxProfileImage }), isAuthenticated: true, isCheckingAuth, hasHydrated: true, From eb709c537d1d8d37c1669e3b1fbfc93b04bb26a4 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 04:11:33 +0900 Subject: [PATCH 09/11] =?UTF-8?q?fix:=20header=20=EB=82=B4=20profile=20ima?= =?UTF-8?q?ge=20sanitize=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/common/Header/ProfileMenuTrigger.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/components/common/Header/ProfileMenuTrigger.tsx b/src/components/common/Header/ProfileMenuTrigger.tsx index b729d39f..d2ac5028 100644 --- a/src/components/common/Header/ProfileMenuTrigger.tsx +++ b/src/components/common/Header/ProfileMenuTrigger.tsx @@ -10,11 +10,11 @@ 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"; import { cn } from "@/lib/utils/cn"; -import { resolveMoverProfileImageSrc } from "@/lib/utils/moverProfileImage"; import { DROPDOWN_EXIT_DURATION_MS, dropdownMotionClassName } from "@/lib/utils/uiMotion"; import { useAuthStore } from "@/stores/useAuthStore"; @@ -46,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(null); @@ -174,10 +175,10 @@ export default function ProfileMenuTrigger({ > {isAvatarPending ? ( - ) : imageUrl ? ( + ) : safeImageUrl ? (
Date: Thu, 13 Aug 2026 11:52:26 +0900 Subject: [PATCH 10/11] =?UTF-8?q?fix:=20=EC=BD=94=EB=93=9C=EB=9E=98?= =?UTF-8?q?=EB=B9=97=20=EB=A6=AC=EB=B7=B0=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../profile/CustomerProfileEditForm.tsx | 16 ++++++++++------ .../profile/MoverBasicInfoEditForm.tsx | 8 +++++--- src/components/profile/MoverProfileEditForm.tsx | 11 ++++++++--- src/components/profile/ProfileChipGroup.tsx | 12 +++++++++++- src/components/profile/ProfileImageUploader.tsx | 5 +++++ src/hooks/useBodyScrollLock.ts | 5 ++++- src/lib/auth/role.ts | 13 ++++++++----- src/lib/utils/moverProfileImage.ts | 3 ++- src/lib/utils/preventEnterSubmitOnInput.ts | 3 +++ 9 files changed, 56 insertions(+), 20 deletions(-) diff --git a/src/components/profile/CustomerProfileEditForm.tsx b/src/components/profile/CustomerProfileEditForm.tsx index eb2f3e0a..f52767d6 100644 --- a/src/components/profile/CustomerProfileEditForm.tsx +++ b/src/components/profile/CustomerProfileEditForm.tsx @@ -58,7 +58,6 @@ const CustomerProfileEditForm = ({ handleSubmit, setError, setFocus, - getValues, reset, resetField, formState: { errors, isValid, isSubmitting, dirtyFields, isDirty }, @@ -112,9 +111,8 @@ const CustomerProfileEditForm = ({ // basic/비밀번호만 default 승격. profile 필드 dirty는 유지 // (profile PATCH 실패 후 재시도 시 payload가 비지 않도록) - const current = getValues(); - resetField("name", { defaultValue: current.name }); - resetField("phone", { defaultValue: current.phone }); + resetField("name", { defaultValue: formValues.name }); + resetField("phone", { defaultValue: formValues.phone }); resetField("currentPassword", { defaultValue: "" }); resetField("newPassword", { defaultValue: "" }); resetField("newPasswordConfirm", { defaultValue: "" }); @@ -144,9 +142,8 @@ const CustomerProfileEditForm = ({ return; } - const current = getValues(); reset({ - ...current, + ...formValues, currentPassword: "", newPassword: "", newPasswordConfirm: "", @@ -202,6 +199,7 @@ const CustomerProfileEditForm = ({ placeholder="성함을 입력해 주세요" error={errors.name?.message} maxLength={50} + disabled={isPending} {...register("name")} /> @@ -230,6 +228,7 @@ const CustomerProfileEditForm = ({ autoComplete="current-password" placeholder="현재 비밀번호를 입력해 주세요" error={errors.currentPassword?.message} + disabled={isPending} {...register("currentPassword")} /> @@ -241,6 +240,7 @@ const CustomerProfileEditForm = ({ autoComplete="new-password" placeholder="새 비밀번호를 입력해 주세요" error={errors.newPassword?.message} + disabled={isPending} {...register("newPassword")} /> @@ -252,6 +252,7 @@ const CustomerProfileEditForm = ({ autoComplete="new-password" placeholder="새 비밀번호를 다시 입력해 주세요" error={errors.newPasswordConfirm?.message} + disabled={isPending} {...register("newPasswordConfirm")} /> @@ -271,6 +272,7 @@ const CustomerProfileEditForm = ({ initialPreviewUrl={initialImageUrl} onChange={field.onChange} error={errors.imageFile?.message} + disabled={isPending} /> )} /> @@ -292,6 +294,7 @@ const CustomerProfileEditForm = ({ value={field.value} onChange={field.onChange} error={errors.serviceTypes?.message} + disabled={isPending} /> )} /> @@ -314,6 +317,7 @@ const CustomerProfileEditForm = ({ onChange={field.onChange} error={errors.regionId?.message} className="max-w-[277px] gap-x-8 gap-y-12 md:max-w-none" + disabled={isPending} /> )} /> diff --git a/src/components/profile/MoverBasicInfoEditForm.tsx b/src/components/profile/MoverBasicInfoEditForm.tsx index ad11fee9..b8e12568 100644 --- a/src/components/profile/MoverBasicInfoEditForm.tsx +++ b/src/components/profile/MoverBasicInfoEditForm.tsx @@ -47,7 +47,6 @@ const MoverBasicInfoEditForm = ({ handleSubmit, setError, setFocus, - getValues, reset, formState: { errors, isValid, isSubmitting, isDirty }, } = useForm({ @@ -83,9 +82,8 @@ const MoverBasicInfoEditForm = ({ return; } - const current = getValues(); reset({ - ...current, + ...formValues, currentPassword: "", newPassword: "", newPasswordConfirm: "", @@ -153,6 +151,7 @@ const MoverBasicInfoEditForm = ({ placeholder="성함을 입력해 주세요" error={errors.name?.message} maxLength={50} + disabled={isPending} {...register("name")} /> @@ -175,6 +174,7 @@ const MoverBasicInfoEditForm = ({ autoComplete="current-password" placeholder="현재 비밀번호를 입력해 주세요" error={errors.currentPassword?.message} + disabled={isPending} {...register("currentPassword")} /> @@ -186,6 +186,7 @@ const MoverBasicInfoEditForm = ({ autoComplete="new-password" placeholder="새 비밀번호를 입력해 주세요" error={errors.newPassword?.message} + disabled={isPending} {...register("newPassword")} /> @@ -197,6 +198,7 @@ const MoverBasicInfoEditForm = ({ autoComplete="new-password" placeholder="새 비밀번호를 다시 입력해 주세요" error={errors.newPasswordConfirm?.message} + disabled={isPending} {...register("newPasswordConfirm")} /> diff --git a/src/components/profile/MoverProfileEditForm.tsx b/src/components/profile/MoverProfileEditForm.tsx index 4767fb45..d127b16f 100644 --- a/src/components/profile/MoverProfileEditForm.tsx +++ b/src/components/profile/MoverProfileEditForm.tsx @@ -42,7 +42,6 @@ const MoverProfileEditForm = ({ handleSubmit, setError, setFocus, - getValues, reset, formState: { errors, isValid, isSubmitting, isDirty }, } = useForm({ @@ -78,9 +77,8 @@ const MoverProfileEditForm = ({ ...(imageKey ? { imageUrl: imageKey } : {}), }); - const current = getValues(); reset({ - ...current, + ...formValues, imageFile: null, }); setToastMessage("프로필이 수정되었습니다."); @@ -124,6 +122,7 @@ const MoverProfileEditForm = ({ initialPreviewUrl={initialImageUrl} onChange={field.onChange} error={errors.imageFile?.message} + disabled={isPending} /> )} /> @@ -136,6 +135,7 @@ const MoverProfileEditForm = ({ placeholder="사이트에 노출될 별명을 입력해 주세요" error={errors.nickname?.message} maxLength={20} + disabled={isPending} {...register("nickname")} /> @@ -148,6 +148,7 @@ const MoverProfileEditForm = ({ numericOnly placeholder="기사님의 경력을 입력해 주세요" error={errors.career?.message} + disabled={isPending} {...register("career")} /> @@ -159,6 +160,7 @@ const MoverProfileEditForm = ({ placeholder="한 줄 소개를 입력해 주세요" error={errors.shortIntro?.message} maxLength={100} + disabled={isPending} {...register("shortIntro")} /> @@ -171,6 +173,7 @@ const MoverProfileEditForm = ({ placeholder="상세 내용을 입력해 주세요" error={errors.description?.message} maxLength={1000} + disabled={isPending} {...register("description")} /> @@ -187,6 +190,7 @@ const MoverProfileEditForm = ({ value={field.value} onChange={field.onChange} error={errors.serviceTypes?.message} + disabled={isPending} /> )} /> @@ -205,6 +209,7 @@ const MoverProfileEditForm = ({ onChange={field.onChange} error={errors.regionIds?.message} className="max-w-[277px] gap-x-8 gap-y-12 md:max-w-none" + disabled={isPending} /> )} /> diff --git a/src/components/profile/ProfileChipGroup.tsx b/src/components/profile/ProfileChipGroup.tsx index 024dc983..4d980bf4 100644 --- a/src/components/profile/ProfileChipGroup.tsx +++ b/src/components/profile/ProfileChipGroup.tsx @@ -12,6 +12,7 @@ interface ProfileChipGroupBaseProps { className?: string; chipClassName?: string; error?: string; + disabled?: boolean; "aria-labelledby"?: string; } @@ -63,7 +64,14 @@ const handleSelect = ( /** 프로필 서비스·지역 Chip 선택 그룹 */ const ProfileChipGroup = (props: ProfileChipGroupProps) => { - const { options, className, chipClassName, error, "aria-labelledby": ariaLabelledby } = props; + const { + options, + className, + chipClassName, + error, + disabled, + "aria-labelledby": ariaLabelledby, + } = props; return (
@@ -71,12 +79,14 @@ const ProfileChipGroup = (props: ProfileChipGroupProp className={cn("flex flex-wrap gap-8 md:gap-12", className)} role="group" aria-labelledby={ariaLabelledby} + aria-disabled={disabled || undefined} > {options.map((option) => ( handleSelect(props, option.value)} className={chipClassName} > diff --git a/src/components/profile/ProfileImageUploader.tsx b/src/components/profile/ProfileImageUploader.tsx index 9949a17b..8a115581 100644 --- a/src/components/profile/ProfileImageUploader.tsx +++ b/src/components/profile/ProfileImageUploader.tsx @@ -15,6 +15,7 @@ interface ProfileImageUploaderProps { initialPreviewUrl?: string | null; onChange: (file: File | null) => void; error?: string; + disabled?: boolean; className?: string; } @@ -25,6 +26,7 @@ const ProfileImageUploader = ({ initialPreviewUrl = null, onChange, error, + disabled = false, className, }: ProfileImageUploaderProps) => { const generatedId = useId(); @@ -64,6 +66,7 @@ const ProfileImageUploader = ({ type="file" accept={PROFILE_IMAGE_ACCEPT} className="sr-only" + disabled={disabled} aria-invalid={Boolean(error)} aria-describedby={error ? errorId : undefined} onChange={handleChange} @@ -72,6 +75,7 @@ const ProfileImageUploader = ({ type="button" aria-label={"프로필 이미지 선택"} aria-describedby={error ? errorId : undefined} + disabled={disabled} onClick={() => { inputRef.current?.click(); }} @@ -79,6 +83,7 @@ const ProfileImageUploader = ({ "bg-background-muted rounded-6 relative flex items-center justify-center overflow-hidden", "size-100 md:size-160", "focus-visible:ring-border-brand focus-visible:ring-2 focus-visible:outline-none", + "disabled:cursor-not-allowed disabled:opacity-50", )} > {previewUrl ? ( diff --git a/src/hooks/useBodyScrollLock.ts b/src/hooks/useBodyScrollLock.ts index 4f3e17c1..a5f57fe8 100644 --- a/src/hooks/useBodyScrollLock.ts +++ b/src/hooks/useBodyScrollLock.ts @@ -19,9 +19,12 @@ const lockBodyScroll = () => { // overflow: hidden 시 스크롤바가 사라져 레이아웃이 흔들리지 않도록 보정 const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth; + const existingPaddingRight = + Number.parseFloat(window.getComputedStyle(document.body).paddingRight) || 0; + document.body.style.overflow = "hidden"; if (scrollbarWidth > 0) { - document.body.style.paddingRight = `${scrollbarWidth}px`; + document.body.style.paddingRight = `${existingPaddingRight + scrollbarWidth}px`; } } diff --git a/src/lib/auth/role.ts b/src/lib/auth/role.ts index 0d2d3977..e1417f9f 100644 --- a/src/lib/auth/role.ts +++ b/src/lib/auth/role.ts @@ -32,9 +32,16 @@ export const parseSoftUxAuthRole = (value: string | null | undefined): LoginRole return null; }; +export const clearRole = (): void => { + clearClientStorageHint(ROLE_STORAGE_KEY); +}; + export const saveRole = (role: AuthRole): void => { const softUxRole = parseSoftUxAuthRole(role); - if (!softUxRole) return; + if (!softUxRole) { + clearRole(); + return; + } setClientStorageHint(ROLE_STORAGE_KEY, softUxRole); }; @@ -42,7 +49,3 @@ export const saveRole = (role: AuthRole): void => { export const loadRole = (): LoginRole | null => { return parseSoftUxAuthRole(getClientStorageHint(ROLE_STORAGE_KEY)); }; - -export const clearRole = (): void => { - clearClientStorageHint(ROLE_STORAGE_KEY); -}; diff --git a/src/lib/utils/moverProfileImage.ts b/src/lib/utils/moverProfileImage.ts index 98b77d9d..21669d48 100644 --- a/src/lib/utils/moverProfileImage.ts +++ b/src/lib/utils/moverProfileImage.ts @@ -2,7 +2,8 @@ import { isAllowedImageRemoteUrl } from "@/lib/constants/allowedImageHosts"; export const DEFAULT_MOVER_PROFILE_IMAGE = "/images/profile-character.png"; -const isLocalPublicPath = (src: string) => src.startsWith("/") && !src.startsWith("//"); +const isLocalPublicPath = (src: string) => + src.startsWith("/") && !src.startsWith("//") && !src.includes("\\") && !src.includes(".."); /** * 카드/목록에 넣을 프로필 이미지 URL. diff --git a/src/lib/utils/preventEnterSubmitOnInput.ts b/src/lib/utils/preventEnterSubmitOnInput.ts index c9a7248b..b2a6cf37 100644 --- a/src/lib/utils/preventEnterSubmitOnInput.ts +++ b/src/lib/utils/preventEnterSubmitOnInput.ts @@ -1,5 +1,7 @@ import type { KeyboardEvent } from "react"; +const TEXT_INPUT_TYPES = new Set(["text", "password", "email", "tel", "search", "url"]); + /** * 한 줄 input에서 Enter로 form이 submit되는 기본 동작을 막습니다. * textarea·button 등 input이 아닌 요소에서는 동작하지 않습니다. @@ -7,6 +9,7 @@ import type { KeyboardEvent } from "react"; export const preventEnterSubmitOnInput = (event: KeyboardEvent) => { if (event.key !== "Enter" || event.nativeEvent.isComposing) return; if (!(event.target instanceof HTMLInputElement)) return; + if (!TEXT_INPUT_TYPES.has(event.target.type)) return; event.preventDefault(); }; From c9f8d6bd60e1e19c23dd9cfd4840f2269439e851 Mon Sep 17 00:00:00 2001 From: 9g-g9 Date: Thu, 13 Aug 2026 13:53:19 +0900 Subject: [PATCH 11/11] =?UTF-8?q?fix:=20preventDefault=20=ED=95=A8?= =?UTF-8?q?=EC=88=98=20=EB=B9=BC=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/lib/utils/preventEnterSubmitOnInput.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/lib/utils/preventEnterSubmitOnInput.ts b/src/lib/utils/preventEnterSubmitOnInput.ts index b2a6cf37..127650dd 100644 --- a/src/lib/utils/preventEnterSubmitOnInput.ts +++ b/src/lib/utils/preventEnterSubmitOnInput.ts @@ -6,10 +6,15 @@ const TEXT_INPUT_TYPES = new Set(["text", "password", "email", "tel", "search", * 한 줄 input에서 Enter로 form이 submit되는 기본 동작을 막습니다. * textarea·button 등 input이 아닌 요소에서는 동작하지 않습니다. */ -export const preventEnterSubmitOnInput = (event: KeyboardEvent) => { - if (event.key !== "Enter" || event.nativeEvent.isComposing) return; - if (!(event.target instanceof HTMLInputElement)) return; - if (!TEXT_INPUT_TYPES.has(event.target.type)) return; +export const shouldPreventEnterSubmitOnInput = (event: KeyboardEvent) => { + if (event.key !== "Enter" || event.nativeEvent.isComposing) return false; + if (!(event.target instanceof HTMLInputElement)) return false; + + return TEXT_INPUT_TYPES.has(event.target.type); +}; - event.preventDefault(); +export const preventEnterSubmitOnInput = (event: KeyboardEvent) => { + if (shouldPreventEnterSubmitOnInput(event)) { + event.preventDefault(); + } };