백엔드/Supabase
[Supabase] 로그인 기능 구현하기
순코딩
2024. 12. 18. 15:07
로그인 컴포넌트 ( src / components / signIn / SignIn.tsx )
"use client";
import { useState } from "react";
import useAuth from "@/hooks/auth/useAuth";
export default function SignIn() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const { handleSignIn } = useAuth();
// 로그인 처리 함수
const signIn = async (e: React.FormEvent) => {
e.preventDefault();
handleSignIn({ email, password });
};
return (
<div>
<h2>로그인</h2>
<form onSubmit={signIn}>
<label>이메일</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
placeholder="example@email.com"
/>
<label>비밀번호</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
placeholder="비밀번호 입력"
/>
<button type="submit">로그인</button>
</form>
</div>
);
}
로그인 커스텀훅 ( src / hooks / auth / useAuth.ts )
import { checkUserSession } from "@/services/auth/checkUserSession";
import { supabase } from "@/lib/supabaseClient";
import { useState } from "react";
import { signIn } from "@/services/auth/signIn";
import { signInType } from "@/types/auth/login.type";
import { useModalStore } from "@/store";
import { useRouter } from "next/navigation";
const useAuth = () => {
const { open } = useModalStore();
const router = useRouter();
// 로그인
async function handleSignIn({ email, password }: signInType) {
const error = await signIn({ email, password });
if (error) {
open({
title: "Error",
content: "로그인 에러 발생",
});
}
else{
router.push("/");
}
}
return { handleSignIn };
};
export default useAuth;
로그인 모듈 ( src / service / signIn.ts )
import { supabase } from "@/lib/supabaseClient";
import { signInType } from "@/types/auth/login.type";
export async function signIn({ email, password }: signInType) {
const { error } = await supabase.auth.signInWithPassword({
email,
password,
});
if (error) {
return error;
}
}