🎁 Firebase Auth 기능 구현.
💻 jsconfig.json
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
import ~~ from ./~~
-> import ~~ from components/~~
💻 fbase.js
import firebase from "firebase/app"
import "firebase/auth"
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTO_DOMAIN,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGIN_ID,
appId: process.env.REACT_APP_APP_ID,
};
firebase.initializeApp(firebaseConfig);
export const authService = firebase.auth();
import "firebase/auth"
: auth 기능 import💻 App.js
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(authService.currentUser);
return <AppRouter isLoggedIn={isLoggedIn}/>
}
isLoggedIn
의 초기 값을 autoService.currentUser
로 설정.🎈 간단한 LOGIN UI Form
💻 Auth.js
import React,{useState} from "react";
import "firebase/auth";
const Auth = () =>{
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const onChange = e =>{
const {target:{name,value}} = e;
if(name === "email"){
setEmail(e.target.value);
}else if(name === "password") {
setPassword(e.target.value);
}
}
const onSubmit = e =>{
e.preventDefault();
}
return (
<div>
<form onSubmit = {onSubmit}>
<input name = "email" type="text" placeholder = "Email" required value = {email} onChange={onChange}/>
<input name = "password" type="password" placeholder = "Password" required value={password} onChange={onChange}/>
<input type="submit" value="Log In" />
</form>
<div>
<button>Continue with Google</button>
<button>Continue with Github</button>
</div>
</div>
)
}
export default Auth;
📌 코드 설명
💻 Auth.js
import {authService} from "fbase";
...
const [newAccount, setNewAccount] = useState(true);
...
const onSubmit = async(e) =>{
e.preventDefault();
try{
let data;
if(newAccount){
//create account
data = await authService.createUserWithEmailAndPassword(email, password);
}else{
data = await authService.signInWithEmailAndPassword(email, password);
}
}catch(error){
console.log(error);
}
}
return (
...
<input type="submit" value={newAccount ? "Create Account" : "Log In"}/>
...
)
}
export default Auth;
📌 코드 설명
authService.createUserWithEmailAndPassword(email, password);
사용.🧨 그렇다면 왜 isLoggedIn의 값은 null???
-> firebase가 초기화되고 모든 걸 로드할 때까지 기다려줄 시간이 없기 때문.
-> 시작하고 firebase가 실행되기까지의 시간 전에 로그아웃으로 간주하고 isLoggedIn의 값 : false
💻 App.js
function App() {
const [init, setInit] = useState(false); //init이 false이면 router 숨김.
const [isLoggedIn, setIsLoggedIn] = useState(authService.currentUser);
useEffect(() =>{
authService.onAuthStateChanged((user) => {
if(user){
setIsLoggedIn(true);
} else{
setIsLoggedIn(false);
}
setInit(true);
});
}, []);
return (
<>
{init ? <AppRouter isLoggedIn={isLoggedIn} /> : "Initializing..."}
<footer>© {new Date().getFullYear()} Nwitter</footer>
</>
);
}
📌 코드 설명
💻 Auth.js
const toggleAccount = () => setNewAccount((prev) =>!prev);
return (
</form>
<span onClick={toggleAccount}>{newAccount ?"Log In":"Create Account"}</span>
)
📌 코드 설명
await authService.signInWithEmailAndPassword(email, password);
로 전환.💻 fbase.js
export const firebaseInstance = firebase;
💻 Auth.js
const onSocialClick = async(event) =>{
const {target:{name}} = event;
let provider;
if(name === "google"){
provider = new firebaseInstance.auth.GoogleAuthProvider();
}else if(name==="github"){
provider = new firebaseInstance.auth.GithubAuthProvider();
}
await authService.signInWithPopup(provider);
}
<button onClick={onSocialClick}name="google">Continue with Google</button>
<button onClick={onSocialClick}name="github">Continue with Github</button>
📌 코드 설명
provider = new firebaseInstance.auth.GoogleAuthProvider();
authService.signInWithPopup(provider)
실행.💻Router.js
<Router>
{isLoggedIn && <Navigation/>}
<Switch>
{isLoggedIn? (
<>
<Route exact path = "/">
<Home />
</Route>
<Route exact path = "/profile">
<Profile />
</Route>
<Redirect from ="*" to = "/" />
</>
): (
<>
<Route exact path="/">
<Auth />
</Route>
<Redirect from="*" to="/"/>
</>
)}
</Switch>
</Router>
💻Profile.js
const Profile = () =>{
const onLogOutClick = () => authService.signOut();
return(
<>
<button onClick = {onLogOutClick}>Log Out</button>
</>)
}
📌 코드 설명
{isLoggedIn && <Navigation/>}
: isLoggedIn이 true이면 공통적으로 나타나는 Navigation<Redirect from ="*" to = "/" />
authService.signOut();
returnRouter.js에서 Profile 밑 Redirect를 빼준다.
<const Profile = () =>{
const history = useHistory();
const onLogOutClick = () => {
authService.signOut();
history.push("/")
}
return(
<>
<button onClick = {onLogOutClick}>Log Out</button>
</>)
}
📌 코드 설명
<출처 : 노마드코더>