본문 바로가기
React.js/SNS Project

Day 2

by Jinny96 2022. 8. 21.

1. 폴더 구조


2. 라우터 설정

-Router.js

import { Route, Routes } from "react-router-dom";

import Home from "../Components/Home";
import SignIn from "../Components/SignIn";
import SignUp from "../Components/SignUp";

const Router = () => {
    return (
        <Routes>
            <Route path="/" element={<SignIn />} />
            <Route path="/signup" element={<SignUp />} />
            <Route path="/home" element={<Home />} />
        </Routes>
    )
}

export default Router;

 

 

-App.js

import Router from "./Env/Router";
import CssBaseline from '@mui/material/CssBaseline';

const App = () => {
  return (
    <>
      <CssBaseline />
      <Router />
    </>
  )
}

export default App;

3. Firebase 연동

-Firebase.js

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

const firebaseConfig = {
  apiKey: "",
  authDomain: "youngstagram-e6806.firebaseapp.com",
  projectId: "youngstagram-e6806",
  storageBucket: "youngstagram-e6806.appspot.com",
  messagingSenderId: "72953816598",
  appId: "",
  measurementId: "G-J2YNTMENVF"
};

const app = initializeApp(firebaseConfig);
export const auth = getAuth(); // Firebase Authentication

 


4. 로그인 페이지

-SignIn.jsx

import { useState } from "react";
import { useNavigate } from 'react-router-dom';

import { Box, Button, Grid, TextField, Typography } from "@mui/material";
import InstagramIcon from '@mui/icons-material/Instagram';

import Swal from 'sweetalert2'

import { signInWithEmailAndPassword,  setPersistence, browserSessionPersistence } from "firebase/auth";
import { auth } from "../Env/Firebase";

const SignIn = () => {
    const navigate = useNavigate();
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

    const onChange = (event) => {
        const { target: { id, value } } = event;
        if (id === "email") {
            setEmail(value)
        } else if (id === "password") {
            setPassword(value)
        }
    }

    const onKeyPress = (e) => {
        if (e.key === 'Enter') {
            onClickSignIn();
        }
    }

    const onClickSignIn = () => {
        setPersistence(auth, browserSessionPersistence).then(() => {
            return signInWithEmailAndPassword(auth, email, password).then((res) => {
                sessionStorage.setItem("user_id", res._tokenResponse.localId);
                navigate("/home");
            }).catch(() => {
                Swal.fire({
                    icon: 'error',
                    title: '로그인 실패',
                    html: "이메일 혹은 비밀번호를 확인해주세요.",
                    showClass: {
                        popup: 'animate__animated animate__fadeInDown'
                    },
                    hideClass: {
                        popup: 'animate__animated animate__fadeOutUp'
                    }
                });
            });
        }).catch(r => {
            console.log(r);
        })
    }

    return (
        <Box 
            style={{ 
                width: 350, 
                height: "100vh",
                alignItems: "center",
                display: "flex",
                textAlign: "center",
                margin: "auto"
            }}
        >
            <Grid container>
                <Grid item xs={12}>
                    <InstagramIcon fontSize="large" style={{ color: "black" }} />
                </Grid>
                <Grid item xs={12}>
                    <Typography variant="h4" style={{ color: "black" }}>
                        Youngstagram
                    </Typography>
                </Grid>
                <Grid item xs={12} style={{ marginTop: 50 }}>
                    <TextField
                        id="email"
                        label="Email"
                        variant="outlined"
                        sx={{
                            "& .MuiInputLabel-root": { color: 'black' },
                            "& .MuiOutlinedInput-root": { "& > fieldset": { borderColor: "black" } },
                            "& .MuiOutlinedInput-root.Mui-focused": { "& > fieldset": { borderColor: "black" } },
                            "& .MuiOutlinedInput-root:hover": { "& > fieldset": { borderColor: "black" } },
                            width: 250
                        }}
                        onChange={onChange}
                        onKeyPress={onKeyPress}
                    />
                </Grid>
                <Grid item xs={12} style={{ marginTop: 10 }}>
                    <TextField
                        id="password"
                        label="Password"
                        type="password"
                        variant="outlined"
                        sx={{
                            "& .MuiInputLabel-root": { color: 'black' },
                            "& .MuiOutlinedInput-root": { "& > fieldset": { borderColor: "black" } },
                            "& .MuiOutlinedInput-root.Mui-focused": { "& > fieldset": { borderColor: "black" } },
                            "& .MuiOutlinedInput-root:hover": { "& > fieldset": { borderColor: "black" } },
                            width: 250
                        }}
                        onChange={onChange}
                        onKeyPress={onKeyPress}
                    />
                </Grid>
                <Grid item xs={12} style={{ marginTop: 40 }}>
                    <Button
                        variant="contained"
                        style={{ width: 250, color: "white", height: 50 }}
                        onClick={onClickSignIn}
                    >
                        <Typography variant="subtitle1">
                            로그인
                        </Typography>
                    </Button>
                </Grid>
                <Grid item xs={12} style={{ marginTop: 20 }}>
                    <Typography variant="subtitle2">
                        계정이 없으신가요? <a href="/signup" style={{color: "#4e4dec", textDecoration: "none"}}>가입하기</a>
                    </Typography>
                </Grid>
            </Grid>
        </Box>
    )
}

export default SignIn;

-onChange : onChange로 들어온 값을 id 별로 구분하여 각각 email, password에 값 할당

-onKeyPress : 유저가 엔터를 눌렀을 때 onClickSignIn 함수 실행

-onClickSignIn : setPersistence함수로 인증 지속을 세션이 닫힐 때 까지로 설정 -> signInWithEmailAndPassword 함수로 Firebase에 인증 요청 -> 인증이 완료되면 세션 스토리지에 uid 저장 -> "/home"으로 이동

(등록되지 않은 유저라면 alert 띄운다)

'React.js > SNS Project' 카테고리의 다른 글

Day 6  (0) 2022.08.25
Day 5  (0) 2022.08.24
Day 4  (0) 2022.08.23
Day 3  (0) 2022.08.22
Day 1  (0) 2022.08.20

댓글