- 중간 보고 양식(월~금요일)
- TO-DO LIST : 오늘의 할 일 작성
- 배운 내용 요약 정리 : 강의 수강 후 배운 내용을 나만의 방식으로 정리
1. firebase로 이미지 파일 다루기
1-1. firebase Storage / 주소는 firebase console에 들어가면 확인 가능.
import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";
// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
storageBucket: '파이어베이스 버킷 주소'
1-2. BLOB 또는 File에서 업로드
import { getStorage, ref, uploadBytes } from "firebase/storage";
const storage = getStorage();
const storageRef = ref(storage, '스토리지에 올릴 파일 이름');
// 'file' comes from the Blob or File API
uploadBytes(storageRef, file).then((snapshot) => {
console.log('Uploaded a blob or file!');
});
웹에서 Cloud Storage로 파일 업로드 | Cloud Storage for Firebase
5월 14일, Google I/O에서 Firebase를 다시 만나보세요. 지금 등록하기 의견 보내기 웹에서 Cloud Storage로 파일 업로드 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요
firebase.google.com
2. firebase 유저 인증과 소셜 로그인
2-1. 왜 소셜로그인이 필요할까?
- 유저 입장에서 새롭게 회원가입을 하는 것이 아니어서 쉽게 로그인이 가능
- 보안측면에서도 이점이 있다.
- 개발자 입장에서도 쉽게 개발할 수 있다.
2-2. 구글로그인
const firebaseConfig = {
// ...
// The value of `databaseURL` depends on the location of the database
databaseURL: import.meta.env.VITE_DB_URL,
storageBucket: import.meta.env.VITE_STORAGE_BUCKET,
apiKey: import.meta.env.VITE_API_KEY,
authDomain: import.meta.env.VITE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_PROJECT_ID,
messagingSenderId: import.meta.env.VITE_MESSAGE_ID,
appId: import.meta.env.VITE_APP_ID,
measurementId: "G-WFM8RN1RRG",
};
firebaseConfig 변수에 내용 추가
2-3. 인증 객체 생성
import { GoogleAuthProvider } from "firebase/auth";
const provider = new GoogleAuthProvider();
//선택사항 : 권한 범위 설정
provider.addScope('https://www.googleapis.com/auth/contacts.readonly');
2-4. 로그인 팝업창 / 리다이렉션
1) 로그인 팝업 띄우는 방식
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// IdP data available using getAdditionalUserInfo(result)
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
2) 로그인 페이지로 리다이렉션하여 로그인하기
import { getAuth, signInWithRedirect } from "firebase/auth";
const auth = getAuth();
signInWithRedirect(auth, provider);
3. 로그인 유지와 로그아웃
1) 구글로그인을 하면 credential 이라는 로그인 정보를 가져와서 유저정보를 user$ 변수에 저장하고 credential에 있는 accessToken 정보를 로컬 스토리지에 저장하고,
2) accessToken 정보가 로컬스토리지에 있으면 로그인 된 것으로 판단, 아니라면 로그인 페이지로 이동
3) 로그아웃은 유저정보가 저장된 user$ 변수의 값을 null로 세팅( user$.set(null) ), 로컬스토리지에 있는 token 정보를 삭제.
3-1. 로그인 및 유지 : 로컬스토리지에 저장
//로그인 되었는지 체크 // App.svelte
const checkLogin = async () => {
const token = localStorage.getItem("token");
if (!token) return (isLoading = false);
const credential = GoogleAuthProvider.credential(null, token);
const result = await signInWithCredential(auth, credential);
const user = result.user;
user$.set(user);
isLoading = false;
};
//구글로그인하여 받아온 값에 대한 토큰을 로컬스토리지에 token이라는 key로 저장 //Login.svelte
const loginWithGoogle = async () => {
try {
const result = await signInWithPopup(auth, provider);
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
const user = result.user;
user$.set(user);
localStorage.setItem("token", token);
window.location.hash = "/";
} catch (error) {
console.log(error);
}
};
3-2. 로그아웃
//Mypage.svelte
const logout = () => {
user$.set(null); //store.js에 있는 유저정보 삭제
localStorage.removeItem("token"); //로컬스토리지에 token 키 값 삭제
};
#슈퍼코딩, #1:1관리형부트캠프, #백엔드, #backend, #백엔드공부, #개발공부, #백엔드개발자 #취준일기, #취준기록, #취뽀, #빡공, #HTML/CSS, #javascript, #react , #java, #spring