-
Notifications
You must be signed in to change notification settings - Fork 1
Feat/firebase #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Feat/firebase #19
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7d6f305
chore: firebase 설정
dasosann c66feec
feat: firebaseConfig 백엔드와 일치작업
dasosann 1df1e33
feat: Firebase 설정 개선 및 서비스 워커 초기화 로직 추가
dasosann 5e6cf70
feat: 토큰 만료시 alert 로직 추가
dasosann 638c412
feat: 소셜 로그인 열기
dasosann febeb7c
feat: firebase api 요청
dasosann a1c62a7
Merge branch 'main' into feat/firebase
dasosann 43c193e
fix: 주석 수정
dasosann File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| "use client"; | ||
|
|
||
| import { useEffect } from "react"; | ||
| import { registerServiceWorkerAndGetToken } from "@/lib/firebase"; | ||
| import { api } from "@/lib/axios"; | ||
|
|
||
| const FCM_REGISTERED_KEY = "fcm_registered"; | ||
|
|
||
| export default function FcmInitializer() { | ||
| useEffect(() => { | ||
| // 세션 당 1회만 실행 (페이지 이동마다 중복 등록 방지) | ||
| if (sessionStorage.getItem(FCM_REGISTERED_KEY)) return; | ||
|
|
||
| const registerFcmToken = async () => { | ||
| try { | ||
| // 알림 권한 요청 | ||
| const permission = await Notification.requestPermission(); | ||
| if (permission !== "granted") { | ||
| console.log("[FCM] 알림 권한 거부됨. 토큰 등록 skip."); | ||
| return; | ||
| } | ||
|
|
||
| // Firebase에서 FCM 토큰 발급 | ||
| const token = await registerServiceWorkerAndGetToken(); | ||
| if (!token) { | ||
| console.warn("[FCM] 토큰 발급 실패."); | ||
| return; | ||
| } | ||
|
|
||
| // 백엔드에 FCM 토큰 등록 | ||
| await api.post("/api/fcm/token", { token }); | ||
|
|
||
| // 세션 플래그 저장 (재등록 방지) | ||
| sessionStorage.setItem(FCM_REGISTERED_KEY, "true"); | ||
| console.log("[FCM] 토큰 등록 완료."); | ||
| } catch (error) { | ||
| console.error("[FCM] 토큰 등록 중 오류:", error); | ||
| } | ||
| }; | ||
|
|
||
| registerFcmToken(); | ||
| }, []); | ||
|
|
||
| return null; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,23 +1,108 @@ | ||
| export const NICKNAME_MODIFIERS = [ | ||
| // 리듬/움직임 | ||
| "노래하는", "춤추는", "뛰어노는", "구르는", "빙글도는", "날아가는", "흐느적이는", "뒹구는", "달리는", "흔들리는", | ||
| "노래하는", | ||
| "춤추는", | ||
| "뛰어노는", | ||
| "구르는", | ||
| "빙글도는", | ||
| "날아가는", | ||
| "흐느적이는", | ||
| "뒹구는", | ||
| "달리는", | ||
| "흔들리는", | ||
| // 감정/표정 | ||
| "웃는", "반짝이는", "두근대는", "깔깔대는", "놀라는", "감탄하는", "감동한", "행복한", "수줍은", "즐거운", | ||
| "웃는", | ||
| "반짝이는", | ||
| "두근대는", | ||
| "깔깔대는", | ||
| "놀라는", | ||
| "감탄하는", | ||
| "감동한", | ||
| "행복한", | ||
| "수줍은", | ||
| "즐거운", | ||
| // 상태/분위기 | ||
| "반짝반짝한", "포근한", "시원한", "따뜻한", "향기나는", "알록달록한", "몽글몽글한", "부드러운", "촉촉한", | ||
| "반짝반짝한", | ||
| "포근한", | ||
| "시원한", | ||
| "따뜻한", | ||
| "향기나는", | ||
| "알록달록한", | ||
| "몽글몽글한", | ||
| "부드러운", | ||
| "촉촉한", | ||
| // 행동 스타일 | ||
| "장난치는", "휘파람 부는", "손흔드는", "인사하는", "하품하는", "손뻗는", "끄덕이는", "기지개 켜는", "숨바꼭질하는", | ||
| "장난치는", | ||
| "휘파람 부는", | ||
| "손흔드는", | ||
| "인사하는", | ||
| "하품하는", | ||
| "손뻗는", | ||
| "끄덕이는", | ||
| "기지개 켜는", | ||
| "숨바꼭질하는", | ||
| // 캐릭터 감성 | ||
| "멋부린", "잠에서 깬", "바람 타는", "구경하는", "편지 쓰는", "노을 보는", "초콜릿 든", "선물 고르는" | ||
| "멋부린", | ||
| "잠에서 깬", | ||
| "바람 타는", | ||
| "구경하는", | ||
| "편지 쓰는", | ||
| "노을 보는", | ||
| "초콜릿 든", | ||
| "선물 고르는", | ||
| ]; | ||
|
|
||
| export const NICKNAME_NOUNS = [ | ||
| // 동물 | ||
| "나무늘보", "햄스터", "다람쥐", "고슴도치", "기린", "오리", "판다", "앵무새", "물개", "코알라", "돌고래", "코끼리", "라마", "고래", "아기곰", | ||
| "나무늘보", | ||
| "햄스터", | ||
| "다람쥐", | ||
| "고슴도치", | ||
| "기린", | ||
| "오리", | ||
| "판다", | ||
| "앵무새", | ||
| "물개", | ||
| "코알라", | ||
| "돌고래", | ||
| "코끼리", | ||
| "라마", | ||
| "고래", | ||
| "아기곰", | ||
| // 식물/꽃 | ||
| "데이지", "민들레", "코스모스", "라벤더", "동백꽃", "연꽃", "수국", "벚꽃잎", "클로버", "벚꽃", "해바라기", | ||
| "데이지", | ||
| "민들레", | ||
| "코스모스", | ||
| "라벤더", | ||
| "동백꽃", | ||
| "연꽃", | ||
| "수국", | ||
| "벚꽃잎", | ||
| "클로버", | ||
| "벚꽃", | ||
| "해바라기", | ||
| // 자연/사물 | ||
| "파도", "구름", "별똥별", "바람", "노을", "햇살", "모래성", "무지개", "달빛", "눈송이", | ||
| "파도", | ||
| "구름", | ||
| "별똥별", | ||
| "바람", | ||
| "노을", | ||
| "햇살", | ||
| "모래성", | ||
| "무지개", | ||
| "달빛", | ||
| "눈송이", | ||
| // 캐릭터형 단어 | ||
| "화가", "작가", "바리스타", "제빵사", "소방관", "탐험가", "마술사", "사진작가", "연기자", "시인", "조향사", "고고학자" | ||
| "화가", | ||
| "작가", | ||
| "바리스타", | ||
| "제빵사", | ||
| "소방관", | ||
| "탐험가", | ||
| "마술사", | ||
| "사진작가", | ||
| "연기자", | ||
| "시인", | ||
| "조향사", | ||
| "고고학자", | ||
| ]; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| "use client"; | ||
|
|
||
| import { initializeApp, getApps } from "firebase/app"; | ||
| import { getAnalytics } from "firebase/analytics"; | ||
| import { getMessaging, getToken, onMessage } from "firebase/messaging"; | ||
|
|
||
| export const firebaseConfig = { | ||
| apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, | ||
| authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, | ||
| projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, | ||
| storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, | ||
| messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, | ||
| appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, | ||
| measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID, | ||
| }; | ||
|
|
||
| // Initialize Firebase (중복 초기화 방지) | ||
| const app = | ||
| getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0]; | ||
|
|
||
| // Analytics (브라우저에서만 실행) | ||
| let analytics; | ||
| if (typeof window !== "undefined") { | ||
| analytics = getAnalytics(app); | ||
| } | ||
|
|
||
| // 서비스 워커 등록 및 FCM 토큰 가져오기 | ||
| export async function registerServiceWorkerAndGetToken() { | ||
| if (typeof window === "undefined" || !("serviceWorker" in navigator)) { | ||
| return null; | ||
| } | ||
|
|
||
| try { | ||
| // 서비스 워커 등록 | ||
| const registration = await navigator.serviceWorker.register( | ||
| "/firebase-messaging-sw.js", | ||
| ); | ||
|
|
||
| // 서비스 워커에 Firebase Config 전달 | ||
| registration.active?.postMessage({ | ||
| type: "INIT_FIREBASE", | ||
| config: firebaseConfig, | ||
| }); | ||
|
|
||
| // Messaging 인스턴스 가져오기 | ||
| const messaging = getMessaging(app); | ||
|
|
||
| // FCM 토큰 요청 | ||
| const token = await getToken(messaging, { | ||
| vapidKey: process.env.NEXT_PUBLIC_FIREBASE_VAPID_KEY, | ||
| serviceWorkerRegistration: registration, | ||
| }); | ||
|
|
||
| console.log("FCM Token:", token); | ||
|
|
||
| // 포그라운드 메시지 수신 리스너 | ||
| onMessage(messaging, (payload) => { | ||
| console.log("[Foreground] 메시지 수신:", payload); | ||
| // 여기에 포그라운드 알림 UI 처리 | ||
| }); | ||
dasosann marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return token; | ||
| } catch (error) { | ||
| console.error("서비스 워커 등록 실패:", error); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| export { app, analytics }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FcmInitializer컴포넌트는RootLayout에 포함되어 모든 페이지에서 렌더링됩니다. 현재 구현은 사용자의 인증 상태와 관계없이 FCM 토큰 등록을 시도합니다.문제점:
api.post("/api/fcm/token", ...))를 호출하게 되어 불필요한 네트워크 요청이 발생합니다.개선 제안:
토큰 등록 로직은 사용자가 로그인한 상태일 때만 실행되도록 변경해야 합니다.
useProfile훅 등을 사용하여 사용자 인증 상태를 확인하고, 인증된 경우에만registerFcmToken함수를 호출하도록 수정하는 것을 권장합니다.