251121_01_ENH : 로그인 및 인증 저장, api통신 시 자동으로 accessKey 붙게 조치

This commit is contained in:
2025-11-21 15:33:51 +09:00
parent 0707c91d41
commit 74de3d58f7
63 changed files with 2056 additions and 261 deletions

View File

@@ -0,0 +1,209 @@
"use client";
import Image from "next/image";
import {Button} from "@/components/ui/button";
import {Card, CardContent, CardHeader} from "@/components/ui/card";
import {Input} from "@/components/ui/input";
import React, {useEffect, useRef, useState} from "react";
import {HttpError, nextApi} from "@/lib/http-client";
import {useRouter, useSearchParams} from "next/navigation";
import {LoginUser} from "@/types/auth";
import { useAuth } from "@/hooks/useAuth";
import { useLoading } from "@/hooks/useLoading";
import { useStorage } from "@/hooks/useStorage"
import { StorageKeys } from "@/store/storage/storage-keys";
const LoginPage = () => {
const router = useRouter();
const searchParams = useSearchParams();
const { setFromLoginResponse } = useAuth();
const { withLoadingAsync } = useLoading();
const { get: getSeatNumberStorage, set: setSeatNumberStorage } = useStorage(StorageKeys.SeatNumber);
const { get: getLoginTypeStorage, set: setLoginTypeStorage } = useStorage(StorageKeys.LoginType);
const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>("");
const [seatNum, setSeatNum] = useState<string>(getSeatNumberStorage());
const [loginType, setLoginType] = useState<string>(getLoginTypeStorage());
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const seatNumberInputRef = useRef<HTMLInputElement | null>(null);
const tryLogin = () => {
if(!userId){
alert("아이디를 입력해 주세요");
}
if(!userPw){
alert("PW를 입력해 주세요");
}
if(loginType === "call" && !seatNum){
alert("자리번호를 입력해 주세요");
}
setError(null);
const loginRequestBody = {userId, userPw};
const loginRequestOptions = {autoLogoutOnAuthError: false};
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
return withLoadingAsync(() =>
nextApi.post<LoginUser>(
"/api/login", loginRequestBody, loginRequestOptions
).then(async (data) => { // Jotai 기반 전역 인증 상태 갱신
setFromLoginResponse(data, seatNum);
// 요구사항: 페이지 이동 전에 SeatNumber를 secure-local-storage에 저장
try {
setSeatNumberStorage(seatNum);
setLoginTypeStorage(loginType);
} catch (e) {
// 저장 실패는 치명적이지 않으므로 콘솔 로깅만
console.warn("Failed to persist SeatNumber to secure storage:", e);
}
// 메인 페이지로 이동 (보호 라우트 진입)
router.replace("/");
}).catch((err) => {
if (err instanceof HttpError) {
if (err.status === 401 || err.status === 403) {
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
} else {
setError(`로그인에 실패했습니다. (status: ${err.status})`);
}
} else {
console.error(err);
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
}
})
);
}
// URL 쿼리 파라미터에서 type 수신
useEffect(() => {
const typeParam = searchParams.get("type") ?? "";
let seatNumTemp = "";
if(typeParam === "call") {
seatNumTemp = getSeatNumberStorage();
}
setSeatNum(seatNumTemp);
setLoginType(typeParam);
}, [searchParams]);
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
passwordInputRef.current?.focus();
}
};
const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
const seatNumberInput = seatNumberInputRef.current;
if(loginType === "call" && seatNumberInput?.value === ""){
seatNumberInput.focus();
}
else{
tryLogin();
}
}
};
const handleSeatNumberKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
tryLogin();
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
<Card className="w-full max-w-md shadow-xl">
<CardHeader className="space-y-4 pb-8">
<div className="flex justify-center">
<div className="w-60 h-32 flex items-center justify-center">
<Image
src="/kri_logo.png" // public/kri_logo.png
alt="KRI 로고"
width={500} // 원하는 크기로 줄이기
height={500}
className="object-contain ml-10"
priority
/>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="space-y-2">
<label className="text-sm font-medium">ID</label>
<Input
id="id"
name="id"
type="text"
required
placeholder="아이디를 입력하세요"
value={userId}
onChange={(e) => setUserId(e.currentTarget.value)}
onKeyDown={handleIdKeyDown}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">Password</label>
<Input
id="password"
name="password"
type="password"
autoComplete="current-password"
required
placeholder="PW를 입력하세요"
value={userPw}
onChange={(e) => setUserPw(e.currentTarget.value)}
onKeyDown={handlePwKeyDown}
ref={passwordInputRef}
/>
</div>
{loginType === "call"?
<div className="space-y-2">
<label className="text-sm font-medium">자리번호 (면접원)</label>
<Input
id="seatNum"
name="seatNum"
type="text"
placeholder="자리번호를 입력하세요"
value={seatNum}
onChange={(e) => setSeatNum(e.currentTarget.value)}
onKeyDown={handleSeatNumberKeyDown}
ref={seatNumberInputRef}
/>
</div>
:
null
}
{error && (
<p className="text-sm text-red-500">
{error}
</p>
)}
<Button
type="submit"
className="w-full mt-6 h-11"
onClick={(e) => {
e.preventDefault();
tryLogin();
}}
>
로그인
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
export default LoginPage;