스파르타코딩 TIL - 파이어베이스 1편 로그인

developer.do·2023년 1월 10일
0

파이어베이스로 로그인을 연결해보자

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  apiKey:  
  authDomain:  
  projectId:  
  storageBucket:  
  messagingSenderId:  
  appId:  
};

const app = initializeApp(firebaseConfig);
export const dbService = getFirestore(app);
export const authService = getAuth(app);

정규식 - utils라는 파일을 만들어보자

export const emailRegex = /^[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/g;
// 이메일 정규식
export const pwRegex =
  /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
// 비밀번호 정규식, 특수문자 영문자 최소 8자리부터 포함

다음 로그인 페이지에서 아래를 import 해준다

import { authService } from "../firebase";
import { signInWithEmailAndPassword } from "firebase/auth";

useState 설정

 const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

로그인 버튼을 만들고 onPress를 넣어주자

 <LoginButton onPress={handleLogin}>
   
 handlelogin 함수 안에 아래와 같이 넣어주자
   const handleLogin = () => {
    if (!email) {
      alert("email을 입력해주세요.");
      emailRef.current.focus();
      return true;
    }
    if (!password) {
      alert("password를 입력해주세요.");
      passwordRef.current.focus();
      return true;
    }

    const matchedEmail = email.match(emailRegex);
    const matchedPw = password.match(pwRegex);

    if (matchedEmail === null) {
      alert("이메일 형식에 맞게 입력해 주세요.");
      emailRef.current.focus();
      return true;
    }
    if (matchedPw === null) {
      alert("비밀번호는 8자리 이상 영문자, 숫자, 특수문자 조합이어야 합니다.");
      passwordRef.current.focus();
      return true;
    }

    signInWithEmailAndPassword(authService, email, password)
      .then(() => {
        console.log("로그인성공");
        setEmail("");
        setPassword("");
        // navigate("Stacks", { screen: "Main" });
        navigate("Stacks", { screen: "Main" });
      })
      .catch((err) => {
        console.log("err.message:", err.message);
        if (err.message.includes("user-not-found")) {
          alert("회원이 아닙니다. 회원가입을 먼저 진행해주세요.");
        }
        if (err.message.includes("wrong-password")) {
          alert("비밀번호 틀렸습니다.");
        }
      });
  };
   

랜더링 화면 설정

    return (
    <Background>
      <Image source={require("../assets/images/Logo_1.png")} />

      <TouchableOpacity onPress={() => emailRef.current.focus()}>
        <Text style={{ color: "#3b71f3", right: 155, top: 10 }}>아이디</Text>
      </TouchableOpacity>
      <ContainerStyle value={email} ref={emailRef} onChangeText={setEmail} />

      <TouchableOpacity onPress={() => passwordRef.current.focus()}>
        <Text style={{ color: "#3b71f3", right: 150, top: 10 }}>비밀번호</Text>
      </TouchableOpacity>
      <ContainerStyle
        value={password}
        ref={passwordRef}
        onChangeText={setPassword}
        secureTextEntry={true}
      />

      <CustomButton onPress={handleLogin}>
        <CustomButtonText>로그인</CustomButtonText>
      </CustomButton>
      <CustomButton2 onPress={() => navigate("Join")}>
        <CustomButtonText2>회원가입</CustomButtonText2>
      </CustomButton2>
    </Background>
  );
}

파이어베이스로 2편 회원가입을 해보자

handleRegister함수를 만들자

const handleRegister = () => {
    if (
      (email.includes("@") === false || email.includes(".com") === false) &&
      email !== ""
    ) {
      setEmailError(true);
    } else {
      setEmailError(false);
    }
    if (password !== checkPassword) {
      setPasswordError(true);
    } else {
      setPasswordError(false);
    }

    createUserWithEmailAndPassword(authService, email, password)
      .then(() => {
        console.log("회원가입성공");
        setEmail("");
        setNickname("");
        setPassword("");
        setCheckPassword("");
        navigate("Login");
      })
      .catch((err) => {
        console.log("err.message:", err.message);
        if (err.message.includes("already-in-use")) {
          alert("이미 사용중인 아이디 입니다.");
        }
      });
  };

0개의 댓글