page.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. 'use client';
  2. import './style.scss';
  3. import Link from 'next/link';
  4. import { Checkbox } from '@/components/ui/checkbox';
  5. import { Field, FieldGroup, FieldLabel } from "@/components/ui/field";
  6. import { useState, useEffect, useRef } from 'react';
  7. import { useSearchParams } from 'next/navigation';
  8. import { GoogleLogin } from '@react-oauth/google';
  9. import { fetchApi } from '@/lib/utils/client';
  10. import { LoginRequest } from '@/types/request/auth';
  11. import { LoginResponse } from '@/types/response/auth';
  12. import useAuth from '@/hooks/useAuth';
  13. import { useConfigContext } from '@/contexts/configProvider';
  14. export default function Page()
  15. {
  16. const { login } = useAuth();
  17. const config = useConfigContext();
  18. // 소셜 로그인 on/off (Admin /Config/External) — 값이 없으면(구버전 config) 노출(fail-open), 백엔드가 최종 게이트
  19. const naverEnabled = config?.external?.naverLoginEnabled !== false;
  20. const kakaoEnabled = config?.external?.kakaoLoginEnabled !== false;
  21. const googleEnabled = config?.external?.googleLoginEnabled !== false;
  22. const searchParams = useSearchParams();
  23. const [error, setError] = useState<string>('');
  24. const [loading, setLoading] = useState<boolean>(false);
  25. const [email, setEmail] = useState<string>('');
  26. const [password, setPassword] = useState<string>('');
  27. const [rememberMe, setRememberMe] = useState<boolean>(false);
  28. const emailRef = useRef<HTMLInputElement>(null);
  29. const passwordRef = useRef<HTMLInputElement>(null);
  30. const googleBtnRef = useRef<HTMLDivElement>(null);
  31. const [googleBtnWidth, setGoogleBtnWidth] = useState<number>(0);
  32. useEffect(() => {
  33. if (error) {
  34. alert(error);
  35. setError('');
  36. }
  37. }, [error]);
  38. // URL ?error=... 처리 — Google OAuth callback 등 외부에서 리다이렉트된 에러 메시지 표시
  39. useEffect(() => {
  40. const urlError = searchParams.get('error');
  41. if (urlError) {
  42. setError(urlError);
  43. // 뒤로가기/새로고침 시 alert 중복 방지를 위해 query 정리
  44. const url = new URL(window.location.href);
  45. url.searchParams.delete('error');
  46. window.history.replaceState({}, '', url.toString());
  47. }
  48. }, [searchParams]);
  49. useEffect(() => {
  50. if (googleBtnRef.current) {
  51. const observer = new ResizeObserver(entries => {
  52. for (const entry of entries) {
  53. setGoogleBtnWidth(Math.floor(entry.contentRect.width));
  54. }
  55. });
  56. observer.observe(googleBtnRef.current);
  57. return () => observer.disconnect();
  58. }
  59. }, []);
  60. // 로그인 검증
  61. const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
  62. e.preventDefault();
  63. try {
  64. if (email.length < 1) {
  65. emailRef.current?.focus();
  66. throw new Error('이메일을 입력하세요.');
  67. }
  68. if (password.length < 1) {
  69. passwordRef.current?.focus();
  70. throw new Error('비밀번호를 입력하세요.');
  71. }
  72. await fetchApi<LoginResponse>('/api/auth/login', {
  73. method: 'POST',
  74. body: { Email: email, Password: password } as LoginRequest
  75. });
  76. login(rememberMe);
  77. } catch (err) {
  78. if (err instanceof Error) {
  79. setError(err.message);
  80. }
  81. } finally {
  82. setLoading(false);
  83. }
  84. }
  85. // 구글 로그인
  86. const handleGoogleLogin = async (credentialResponse: { credential?: string }) => {
  87. try {
  88. await fetchApi<LoginResponse>('/api/auth/google-login', {
  89. method: 'POST',
  90. body: {
  91. credential: credentialResponse.credential
  92. }
  93. });
  94. login(rememberMe);
  95. } catch (err) {
  96. if (err instanceof Error) {
  97. setError(err.message);
  98. }
  99. }
  100. };
  101. const handleGoogleLoginFailed = () => {
  102. setError('Google 로그인에 실패했습니다.');
  103. };
  104. return (
  105. <>
  106. <div id="loginForm" className="row-start-2 flex flex-col sm:flex-row gap-2">
  107. <fieldset className="grow min-w-0 sm:basis-1/2">
  108. <legend>로그인</legend>
  109. <form method="post" acceptCharset="utf-8" autoComplete="off" className="grid min-w-0 p-4" onSubmit={handleSubmit}>
  110. <label htmlFor="email">이메일</label>
  111. <input type="email" name="email" id="email" ref={emailRef} maxLength={30} onChange={e => setEmail(e.target.value)} autoComplete="off" autoFocus />
  112. <label htmlFor="password">비밀번호</label>
  113. <input type="password" name="password" id="password" ref={passwordRef} maxLength={20} onChange={e => setPassword(e.target.value)} />
  114. <button type="submit" className="btn btn-primary" disabled={loading}>
  115. {loading ? "로그인 중..." : "로그인"}
  116. </button>
  117. {googleEnabled && (
  118. <div ref={googleBtnRef} className='w-full mt-2 pb-1'>
  119. {googleBtnWidth > 0 && (
  120. <GoogleLogin
  121. onSuccess={handleGoogleLogin}
  122. onError={handleGoogleLoginFailed}
  123. width={googleBtnWidth}
  124. size="large"
  125. shape="rectangular"
  126. context="signin"
  127. ux_mode="redirect"
  128. login_uri={`${window.location.origin}/login/google/callback`}
  129. logo_alignment="center"
  130. />
  131. )}
  132. </div>
  133. )}
  134. {/* Naver/Kakao 소셜 로그인 — start 라우트가 state 생성 후 각사 authorize 로 리다이렉트.
  135. route handler 라 Link prefetch 시 OAuth 시작이 실행되므로 일반 <a> 사용.
  136. 노출 여부는 Admin /Config/External 의 사용 체크박스(config.external.*LoginEnabled)로 제어 */}
  137. {(naverEnabled || kakaoEnabled) && (
  138. <div className="social-login" role="group" aria-label="소셜 로그인">
  139. {naverEnabled && (
  140. <a href="/login/naver/start" className="social-login__button social-login__button--naver">
  141. <span className="social-login__icon social-login__icon--naver" aria-hidden="true">N</span>
  142. <span>네이버 로그인</span>
  143. </a>
  144. )}
  145. {kakaoEnabled && (
  146. <a href="/login/kakao/start" className="social-login__button social-login__button--kakao">
  147. <svg className="social-login__icon social-login__icon--kakao" viewBox="0 0 24 24" aria-hidden="true">
  148. <path fill="currentColor" d="M12 3C6.48 3 2 6.54 2 10.9c0 2.8 1.86 5.25 4.64 6.65-.2.75-.74 2.72-.85 3.14-.13.53.2.52.41.38.17-.11 2.65-1.8 3.72-2.53.67.1 1.37.15 2.08.15 5.52 0 10-3.53 10-7.89S17.52 3 12 3z"/>
  149. </svg>
  150. <span>카카오 로그인</span>
  151. </a>
  152. )}
  153. </div>
  154. )}
  155. </form>
  156. <hr hidden/>
  157. </fieldset>
  158. <fieldset className="grow min-w-0 sm:basis-1/2">
  159. <dl>
  160. <dt>아직 회원이 아니신가요?</dt>
  161. <dd>회원가입 한번으로 커뮤니티에 참여하세요!</dd>
  162. <dd>
  163. <Link href="/register">
  164. <small>></small> 회원가입
  165. </Link>
  166. </dd>
  167. </dl>
  168. <hr />
  169. <dl>
  170. <dt>비밀번호를 잊으셨나요?</dt>
  171. <dd>비밀번호를 깜박했다면 다시 설정할 수 있어요!</dd>
  172. <dd>
  173. <Link href="/forgot-password">
  174. <small>></small> 비밀번호 재설정
  175. </Link>
  176. </dd>
  177. </dl>
  178. <section className="mt-3">
  179. <FieldGroup>
  180. <Field orientation="horizontal">
  181. <Checkbox name="remember_me" id="rememberMe" checked={rememberMe} onCheckedChange={(checked) => setRememberMe(checked === true)} />
  182. <FieldLabel htmlFor="rememberMe">로그인 상태 유지</FieldLabel>
  183. </Field>
  184. </FieldGroup>
  185. </section>
  186. </fieldset>
  187. </div>
  188. </>
  189. );
  190. }