Files
lg-cxdash-front/src/app/(pages)/login/page.tsx

166 lines
5.3 KiB
TypeScript

"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 { nextApi } from "@/lib/http-client";
import {LoginUser} from "@/types/auth";
import { useAuth } from "@/hooks/useAuth";
import { useLoading } from "@/hooks/useLoading";
import {apiError} from "@/lib/http-util";
import {NONE_HTTP_ERROR} from "@/const/commonConst";
const LoginPage = () => {
const { auth, setFromLoginResponse } = useAuth();
const { withLoadingAsync } = useLoading();
const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>("");
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const tryLogin = () => {
if(!userId){
alert("아이디를 입력해 주세요");
return;
}
if(!userPw){
alert("PW를 입력해 주세요");
return;
}
setError(null);
const loginRequestBody = {userId, userPw};
const loginRequestOptions = {autoLogoutOnAuthError: false};
// withLoading 래퍼로 API 호출 전/후 로딩 표시를 자동으로 처리
return withLoadingAsync(() =>
nextApi.post<LoginUser>(
"/login", loginRequestBody, loginRequestOptions
).then(async (data) => {
// Jotai 기반 전역 인증 상태 갱신
setFromLoginResponse(data);
}).catch((e) => {
const err = apiError(e);
console.error(err.status, err.code, err.message);
if (err.status === 401 || err.status === 403) {
setError("아이디 또는 비밀번호를 다시 확인해주세요.");
}
else if(err.code === NONE_HTTP_ERROR) {
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
}
else {
setError(`로그인에 실패했습니다. (status: ${err.status})`);
}
})
);
}
useEffect(() => {
if(auth.user){
window.location.replace("/");
}
}, [auth.user]);
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();
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 p-4 bg-lg-login-body">
<Card className="w-full max-w-md shadow-xl">
<CardHeader className="space-y-4">
<div className="flex justify-center">
<div className="w-60 h-20 flex items-center justify-center">
<Image
src="/logo.png" // public/logo.png
alt="브랜드 로고"
width={500} // 원하는 크기로 줄이기
height={500}
className="object-contain"
priority
/>
</div>
</div>
<div className="flex justify-center">
<span className="content-text-2xl font-bold">LG 보급률 조사 Dashboard</span>
</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>
{error && (
<p className="text-sm text-destructive">
{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;