diff --git a/ssh/package-lock.json b/ssh/package-lock.json index b0b0f84..c8442b2 100644 --- a/ssh/package-lock.json +++ b/ssh/package-lock.json @@ -20,6 +20,7 @@ "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-tooltip": "^1.2.8", + "axios": "^1.11.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "embla-carousel": "^8.6.0", @@ -2900,6 +2901,12 @@ "node": ">=10" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, "node_modules/autoprefixer": { "version": "10.4.21", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.21.tgz", @@ -2938,6 +2945,17 @@ "postcss": "^8.1.0" } }, + "node_modules/axios": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.11.0.tgz", + "integrity": "sha512-1Lx3WLFQWm3ooKDYZD1eXmoGO9fxYQjrycfHFC8P0sCfQVXyROp0p9PFWBehewBOdCwHc+f/b8I0fMto5eSfwA==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -3012,6 +3030,19 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -3218,6 +3249,18 @@ "dev": true, "license": "MIT" }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/commander": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", @@ -3327,6 +3370,15 @@ "dev": true, "license": "MIT" }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/detect-node-es": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/detect-node-es/-/detect-node-es-1.1.0.tgz", @@ -3345,6 +3397,20 @@ "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", "license": "MIT" }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/eastasianwidth": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", @@ -3405,6 +3471,51 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/esbuild": { "version": "0.25.9", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.9.tgz", @@ -3800,6 +3911,26 @@ "dev": true, "license": "ISC" }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/foreground-child": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", @@ -3816,6 +3947,22 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/form-data": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fraction.js": { "version": "4.3.7", "resolved": "https://registry.npmjs.org/fraction.js/-/fraction.js-4.3.7.tgz", @@ -3876,6 +4023,30 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-nonce": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", @@ -3885,6 +4056,19 @@ "node": ">=6" } }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/get-stream": { "version": "8.0.1", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-8.0.1.tgz", @@ -3967,6 +4151,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graphemer": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", @@ -3984,6 +4180,33 @@ "node": ">=8" } }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/hasown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", @@ -4569,6 +4792,15 @@ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", @@ -4598,6 +4830,27 @@ "node": ">=8.6" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/mimic-fn": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", @@ -5112,6 +5365,12 @@ "url": "https://github.com/prettier/prettier?sponsor=1" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/ssh/package.json b/ssh/package.json index 18b0a74..e6ed5f3 100644 --- a/ssh/package.json +++ b/ssh/package.json @@ -22,6 +22,7 @@ "@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-tooltip": "^1.2.8", + "axios": "^1.11.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", "embla-carousel": "^8.6.0", diff --git a/ssh/src/App.tsx b/ssh/src/App.tsx index c7b97b3..77dae9b 100644 --- a/ssh/src/App.tsx +++ b/ssh/src/App.tsx @@ -1,6 +1,10 @@ -import { RouterProvider } from "react-router-dom"; -import { routers } from "@/routes/routing"; - +import { RouterProvider } from 'react-router-dom'; +import { routers } from '@/routes/routing'; +import AuthProvider from '@/auth/AuthProvider'; export default function App() { - return ; + return ( + + + + ); } diff --git a/ssh/src/auth/AuthContext.tsx b/ssh/src/auth/AuthContext.tsx new file mode 100644 index 0000000..15fa9be --- /dev/null +++ b/ssh/src/auth/AuthContext.tsx @@ -0,0 +1,10 @@ +import { createContext } from 'react'; + +export type User = { id: string; name: string; email: string } | null; +export type AuthCtx = { + user: User; + reload: () => Promise; + logout: () => Promise; +}; + +export const AuthContext = createContext(null); diff --git a/ssh/src/auth/AuthProvider.tsx b/ssh/src/auth/AuthProvider.tsx new file mode 100644 index 0000000..62790dd --- /dev/null +++ b/ssh/src/auth/AuthProvider.tsx @@ -0,0 +1,35 @@ +import { useEffect, useState } from 'react'; +import { api } from '@/lib/auth.api'; +import { AuthContext, type AuthCtx, type User } from './AuthContext'; + +export default function AuthProvider({ children }: { children: React.ReactNode }) { + const [user, setUser] = useState(null); + + const reload = async () => { + try { + const { data } = await api.get('/auth/me'); + setUser(data); + } catch { + setUser(null); + } + }; + + useEffect(() => { + reload(); + }, []); + + const logout = async () => { + try { + await api.post('/auth/logout'); + } catch (e) { + // 서버/네트워크 오류는 무시하고 클라이언트 상태만 정리 + if (import.meta.env.DEV) console.debug('logout error ignored:', e); + } finally { + localStorage.removeItem('accessToken'); + setUser(null); + } + }; + + const value: AuthCtx = { user, reload, logout }; + return {children}; +} diff --git a/ssh/src/auth/ProtectedRoute.tsx b/ssh/src/auth/ProtectedRoute.tsx new file mode 100644 index 0000000..583b543 --- /dev/null +++ b/ssh/src/auth/ProtectedRoute.tsx @@ -0,0 +1,16 @@ +import { Navigate, Outlet, useLocation } from 'react-router-dom'; +import { ROUTING_PATH } from '@/routes/path.constants'; +import { useAuth } from '@/auth/useAuth'; + +const toAbs = (seg: string) => (seg.startsWith('/') ? seg : '/' + seg); + +export default function ProtectedRoute() { + const { user } = useAuth(); + const loc = useLocation(); + + if (!user) { + const redirect = encodeURIComponent(loc.pathname + loc.search); + return ; + } + return ; +} diff --git a/ssh/src/auth/useAuth.ts b/ssh/src/auth/useAuth.ts new file mode 100644 index 0000000..38a3bbf --- /dev/null +++ b/ssh/src/auth/useAuth.ts @@ -0,0 +1,8 @@ +import { useContext } from 'react'; +import { AuthContext } from './AuthContext'; + +export function useAuth() { + const ctx = useContext(AuthContext); + if (!ctx) throw new Error('useAuth must be used within '); + return ctx; +} diff --git a/ssh/src/components/Layout/Header/index.tsx b/ssh/src/components/Layout/Header/index.tsx index 3e28df3..209a9b8 100644 --- a/ssh/src/components/Layout/Header/index.tsx +++ b/ssh/src/components/Layout/Header/index.tsx @@ -1,13 +1,14 @@ -import { Link, useLocation } from 'react-router-dom'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; import { ROUTING_PATH } from '@/routes/path.constants'; -import { MessageSquare, CircleUserRound } from 'lucide-react'; +import { MessageSquare, CircleUserRound, LogOut } from 'lucide-react'; import logo from '@/assets/logo1.png'; - +import { useAuth } from '@/auth/useAuth'; const toAbs = (seg: string) => (!seg ? '/' : seg.startsWith('/') ? seg : `/${seg}`); export default function Header() { const { pathname } = useLocation(); - + const navigate = useNavigate(); + const { user, logout } = useAuth(); const NAV = [ { label: '홈페이지', seg: ROUTING_PATH.home }, { label: '채팅하기', seg: ROUTING_PATH.chatbot }, @@ -29,6 +30,11 @@ export default function Header() { const activePill = 'bg-primary/10 text-primary ring-1 ring-primary/20'; const inactivePill = 'text-foreground/70 hover:bg-muted active:bg-muted/80'; + const handleLogout = async () => { + await logout(); + navigate('/login'); + }; + return ( @@ -55,18 +61,27 @@ export default function Header() { })} + - - - 로그인/회원가입 - + {!user ? ( + + + 로그인 + + ) : ( + + + 로그아웃 + + )} - - - - - - > - ); -} diff --git a/ssh/src/constants/nav.ts b/ssh/src/constants/nav.ts index d828d6c..397b051 100644 --- a/ssh/src/constants/nav.ts +++ b/ssh/src/constants/nav.ts @@ -1,11 +1,12 @@ -import { ROUTING_PATH } from "@/routes/path.constants"; +import { ROUTING_PATH } from '@/routes/path.constants'; export const MAIN_NAV = [ - { text: "홈", path: "/" }, - { text: "로그인", path: `/${ROUTING_PATH.landing}` }, - { text: "ATM 지도", path: `/${ROUTING_PATH.atmmap}` }, - { text: "보이스피싱", path: `/${ROUTING_PATH.voicephishing}` }, - { text: "챗봇", path: `/${ROUTING_PATH.chatbot}` }, - { text: "기부", path: `/${ROUTING_PATH.donation}` }, - { text: "설정", path: `/${ROUTING_PATH.setting}` }, + { text: '홈', path: '/' }, + { text: '로그인', path: `/${ROUTING_PATH.login}` }, + { text: '회원가입', path: `/${ROUTING_PATH.signup}` }, + { text: 'ATM 지도', path: `/${ROUTING_PATH.atmmap}` }, + { text: '보이스피싱', path: `/${ROUTING_PATH.voicephishing}` }, + { text: '챗봇', path: `/${ROUTING_PATH.chatbot}` }, + { text: '기부', path: `/${ROUTING_PATH.donation}` }, + { text: '설정', path: `/${ROUTING_PATH.setting}` }, ] as const; diff --git a/ssh/src/lib/auth.api.ts b/ssh/src/lib/auth.api.ts new file mode 100644 index 0000000..8a24184 --- /dev/null +++ b/ssh/src/lib/auth.api.ts @@ -0,0 +1,107 @@ +import axios, { AxiosError, type AxiosRequestConfig } from 'axios'; + +// 환경변수 명 통일: VITE_API_URL 권장 +export const baseURL = import.meta.env.VITE_API_URL ?? 'http://localhost:8080/api'; + +export const api = axios.create({ + baseURL, + // 쿠키 기반이면 활성화 + // withCredentials: true, +}); + +// 리프레시 전용(인터셉터 최소화/분리) +const refreshClient = axios.create({ + baseURL, + // 쿠키 기반이면 필요 + // withCredentials: true, +}); + +type TokenPair = { accessToken: string; refreshToken?: string }; + +// 실제 리프레시 요청 함수 (별도 클라이언트 사용) +async function getNewTokens(): Promise { + // 예시: Authorization 없이 쿠키/리프레시 토큰으로 재발급 + const { data } = await refreshClient.post('/auth/tokens/refresh'); + return data as TokenPair; +} + +// 동시성 제어 +let isRefreshing = false; +let waitQueue: Array<() => void> = []; + +function subscribeRefresh(resolve: () => void) { + waitQueue.push(resolve); +} +function flushQueue() { + waitQueue.forEach((fn) => fn()); + waitQueue = []; +} + +// 요청 인터셉터: 항상 최신 accessToken 부착 +api.interceptors.request.use((config) => { + const at = localStorage.getItem('accessToken'); + if (at) { + config.headers = config.headers ?? {}; + config.headers.Authorization = `Bearer ${at}`; + } + return config; +}); + +// 응답 인터셉터: 401 처리 +api.interceptors.response.use( + (res) => res, + async (error: AxiosError) => { + const original = error.config as (AxiosRequestConfig & { _retry?: boolean }) | undefined; + + // config 없는 에러(CORS, 네트워크 다운 등) + if (!original) throw error; + + const status = error.response?.status; + const url = original.url ?? ''; + + // 리프레시 자체 실패거나, 이미 재시도했다면 중단 + const isRefreshCall = url.includes('/auth/tokens/refresh') || url.includes('/auth/tokens'); + if (isRefreshCall || original._retry) throw error; + + // 만료 + if (status === 401) { + original._retry = true; + + // 이미 누군가 리프레시 중이면 대기 후 재요청 + if (isRefreshing) { + await new Promise((resolve) => subscribeRefresh(resolve)); + // 대기 후 최신 토큰으로 재요청 + const at = localStorage.getItem('accessToken'); + original.headers = original.headers ?? {}; + if (at) original.headers.Authorization = `Bearer ${at}`; + return api(original); + } + + try { + isRefreshing = true; + const tokens = await getNewTokens(); + localStorage.setItem('accessToken', tokens.accessToken); + // 필요 시 리프레시 토큰도 저장(로컬스토리지는 권장 X) + if (tokens.refreshToken) localStorage.setItem('refreshToken', tokens.refreshToken); + + // ✅ 기본값 갱신(이후 요청들) + api.defaults.headers.common.Authorization = `Bearer ${tokens.accessToken}`; + + flushQueue(); + + // 원 요청 재시도 + original.headers = original.headers ?? {}; + original.headers.Authorization = `Bearer ${tokens.accessToken}`; + return api(original); + } catch (e) { + // 전파 전에 대기자 해제 + flushQueue(); + throw e; + } finally { + isRefreshing = false; + } + } + + throw error; + }, +); diff --git a/ssh/src/pages/Landing/index.tsx b/ssh/src/pages/Landing/index.tsx deleted file mode 100644 index ca63d54..0000000 --- a/ssh/src/pages/Landing/index.tsx +++ /dev/null @@ -1,5 +0,0 @@ -const LandingPage = () => { - return 로그인 페이지; -}; - -export default LandingPage; diff --git a/ssh/src/pages/Login/index.tsx b/ssh/src/pages/Login/index.tsx new file mode 100644 index 0000000..e56d61e --- /dev/null +++ b/ssh/src/pages/Login/index.tsx @@ -0,0 +1,162 @@ +import { useState } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; +import { api } from '@/lib/auth.api'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Checkbox } from '@/components/ui/checkbox'; +import { User2, Lock, Eye, EyeOff, Loader2 } from 'lucide-react'; +import { useAuth } from '@/auth/useAuth'; + +export default function LoginPage() { + const [id, setId] = useState(''); + const [pw, setPw] = useState(''); + const [showPw, setShowPw] = useState(false); + const [error, setError] = useState(''); + const [submitting, setSubmitting] = useState(false); + const [search] = useSearchParams(); + const navigate = useNavigate(); + const { reload } = useAuth(); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(''); + + if (id.trim().length < 3) { + setError('아이디는 3자 이상 입력해주세요.'); + return; + } + if (!pw) { + setError('비밀번호를 입력하세요.'); + return; + } + + try { + setSubmitting(true); + const res = await api.post('/auth/login', { id, password: pw }); + + if (res.data?.accessToken) { + localStorage.setItem('accessToken', res.data.accessToken); + } + await reload(); + + const to = search.get('redirect') ?? '/'; + navigate(to, { replace: true }); + } catch { + setError('로그인에 실패했습니다. 아이디/비밀번호를 확인해주세요.'); + } finally { + setSubmitting(false); + } + }; + + return ( + + + + 로그인 + + 아이디와 비밀번호를 입력해주세요. + + + + + + + + 아이디 + + + + setId(e.target.value)} + placeholder="아이디를 입력하세요" + autoComplete="username" + className="pl-11 pr-3 h-12 md:h-14 text-base md:text-lg" + /> + + + + + + 비밀번호 + + + + setPw(e.target.value)} + placeholder="비밀번호를 입력하세요" + autoComplete="current-password" + className="pl-11 pr-12 h-12 md:h-14 text-base md:text-lg" + /> + setShowPw((v) => !v)} + className="absolute right-2 top-1/2 -translate-y-1/2 rounded p-2 md:p-2.5 text-muted-foreground hover:bg-accent" + aria-label={showPw ? '비밀번호 숨기기' : '비밀번호 보기'} + > + {showPw ? ( + + ) : ( + + )} + + + + + + + + 로그인 상태 유지 + + + 비밀번호 찾기 + + + + {error && ( + + {error} + + )} + + + {submitting ? ( + <> + + 로그인 중… + > + ) : ( + '로그인' + )} + + + + 아직 계정이 없으신가요?{' '} + + 회원가입 + + + + + + + ); +} diff --git a/ssh/src/pages/SignUp/index.tsx b/ssh/src/pages/SignUp/index.tsx new file mode 100644 index 0000000..16be946 --- /dev/null +++ b/ssh/src/pages/SignUp/index.tsx @@ -0,0 +1,200 @@ +import { useState } from 'react'; +import { useNavigate, useSearchParams } from 'react-router-dom'; +import { api } from '@/lib/auth.api'; +import { useAuth } from '@/auth/useAuth'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { User2, Mail, IdCard, Lock, Eye, EyeOff, Loader2 } from 'lucide-react'; + +export default function RegisterPage() { + const [userId, setUserId] = useState(''); + const [name, setName] = useState(''); + const [email, setEmail] = useState(''); + const [pw, setPw] = useState(''); + const [confirm, setConfirm] = useState(''); + const [showPw, setShowPw] = useState(false); + const [error, setError] = useState(''); + const [submitting, setSubmitting] = useState(false); + + const [search] = useSearchParams(); + const navigate = useNavigate(); + const { reload } = useAuth(); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(''); + + if (userId.trim().length < 3) return setError('아이디는 3자 이상 입력해주세요.'); + if (name.trim().length < 2) return setError('이름은 2자 이상 입력해주세요.'); + if (!email.includes('@')) return setError('이메일 형식이 올바르지 않습니다.'); + if (pw.length < 8) return setError('비밀번호는 8자 이상이어야 합니다.'); + if (pw !== confirm) return setError('비밀번호가 일치하지 않습니다.'); + + try { + setSubmitting(true); + + await api.post('/auth/register', { id: userId, name, email, password: pw }); + + try { + const res = await api.post('/auth/login', { id: userId, password: pw }); + if (res.data?.accessToken) { + localStorage.setItem('accessToken', res.data.accessToken); + } + await reload(); + const to = search.get('redirect') ?? '/'; + navigate(to, { replace: true }); + return; + } catch { + navigate('/login?redirect=/', { replace: true }); + return; + } + } catch { + setError('회원가입에 실패했습니다. 이미 존재하는 아이디/이메일일 수 있습니다.'); + } finally { + setSubmitting(false); + } + }; + + return ( + + + + 회원가입 + + 아이디, 이름, 이메일과 비밀번호를 입력해주세요. + + + + + + + + 아이디 + + + + setUserId(e.target.value)} + placeholder="아이디를 입력하세요 (3자 이상)" + autoComplete="username" + className="pl-11 pr-3 h-12 md:h-14 text-base md:text-lg" + /> + + + + + + 이름 + + + + setName(e.target.value)} + placeholder="이름을 입력하세요" + className="pl-11 pr-3 h-12 md:h-14 text-base md:text-lg" + /> + + + + + + 이메일 + + + + setEmail(e.target.value)} + placeholder="이메일을 입력하세요" + autoComplete="email" + className="pl-11 pr-3 h-12 md:h-14 text-base md:text-lg" + /> + + + + + + 비밀번호 + + + + setPw(e.target.value)} + placeholder="8자 이상, 안전한 비밀번호" + autoComplete="new-password" + className="pl-11 pr-12 h-12 md:h-14 text-base md:text-lg" + /> + setShowPw((v) => !v)} + className="absolute right-2 top-1/2 -translate-y-1/2 rounded p-2 md:p-2.5 text-muted-foreground hover:bg-accent" + aria-label={showPw ? '비밀번호 숨기기' : '비밀번호 보기'} + > + {showPw ? ( + + ) : ( + + )} + + + + + + + 비밀번호 확인 + + setConfirm(e.target.value)} + placeholder="비밀번호를 다시 입력하세요" + autoComplete="new-password" + className="h-12 md:h-14 text-base md:text-lg" + /> + + + {error && ( + + {error} + + )} + + + {submitting ? ( + <> + + 가입 중… + > + ) : ( + '회원가입' + )} + + + + 이미 계정이 있으신가요?{' '} + + 로그인 + + + + + + + ); +} diff --git a/ssh/src/routes/path.constants.ts b/ssh/src/routes/path.constants.ts index 031735f..c1b76b3 100644 --- a/ssh/src/routes/path.constants.ts +++ b/ssh/src/routes/path.constants.ts @@ -1,6 +1,7 @@ export const ROUTING_PATH = { home: '/', - landing: 'landing', + login: 'login', + signup: 'signup', chatbot: 'chatbot', voicephishing: 'voicephishing', donation: 'donation', diff --git a/ssh/src/routes/routing.tsx b/ssh/src/routes/routing.tsx index 6089236..4daa491 100644 --- a/ssh/src/routes/routing.tsx +++ b/ssh/src/routes/routing.tsx @@ -2,7 +2,8 @@ import { createBrowserRouter } from 'react-router-dom'; import { ROUTING_PATH } from './path.constants'; import HomePage from '@/pages/Home/HomePage'; -import LandingPage from '@/pages/Landing'; +import LoginPage from '@/pages/Login'; +import SignUpPage from '@/pages/SignUp'; import AtmMapPage from '@/pages/AtmMap'; import VoicephishingPage from '@/pages/Voicephishing'; import ChatbotPage from '@/pages/Chatbot'; @@ -12,6 +13,7 @@ import RootLayout from '@/components/Layout/RootLayout'; import RegisterPage from '@/pages/Donation/sections/Features/Register/RegisterPage'; import BankLinkPage from '@/pages/Donation/sections/Features/Register/BankLinkPage'; +import ProtectedRoute from '@/auth/ProtectedRoute'; export const routers = createBrowserRouter([ { @@ -19,13 +21,20 @@ export const routers = createBrowserRouter([ element: , children: [ { path: ROUTING_PATH.home, element: }, - { path: ROUTING_PATH.landing, element: }, + { path: ROUTING_PATH.login, element: }, + { path: ROUTING_PATH.signup, element: }, { path: ROUTING_PATH.atmmap, element: }, { path: ROUTING_PATH.voicephishing, element: }, { path: ROUTING_PATH.donation, element: }, - { path: `${ROUTING_PATH.donation}/register`, element: }, - { path: `${ROUTING_PATH.donation}/banks`, element: }, - { path: ROUTING_PATH.setting, element: }, + + { + element: , + children: [ + { path: ROUTING_PATH.setting, element: }, + { path: `${ROUTING_PATH.donation}/register`, element: }, + { path: `${ROUTING_PATH.donation}/banks`, element: }, + ], + }, ], }, { path: ROUTING_PATH.chatbot, element: },
+ 아이디와 비밀번호를 입력해주세요. +
+ {error} +
+ 아직 계정이 없으신가요?{' '} + + 회원가입 + +
+ 아이디, 이름, 이메일과 비밀번호를 입력해주세요. +
+ 이미 계정이 있으신가요?{' '} + + 로그인 + +