Feat: Firebase Config 및 테스트 페이지 추가

This commit is contained in:
홍창기 2024-09-25 18:10:45 +09:00
parent dc153ab0ca
commit f78d4ac7fb
5 changed files with 175 additions and 10 deletions

View File

@ -0,0 +1,15 @@
// import { initializeApp } from 'firebase/app';
// import { getMessaging } from 'firebase/messaging';
// const firebaseConfig = {
// apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
// authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
// projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
// storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
// messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
// appId: import.meta.env.VITE_FIREBASE_APP_ID,
// measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID,
// };
// export const app = initializeApp(firebaseConfig);
// export const messaging = getMessaging(app);

View File

@ -12,3 +12,11 @@ export async function getProfile() {
})
.then(({ data }) => data);
}
export async function saveFcmToken(token: string) {
return api.post('/auth/fcm', { token }).then(({ data }) => data);
}
export async function createTestNotification() {
return api.post('/auth/test').then(({ data }) => data);
}

View File

@ -1,15 +1,57 @@
// import { initializeApp } from 'firebase/app';
// import { getAnalytics } from 'firebase/analytics';
// import { getMessaging, getToken } from 'firebase/messaging';
// const firebaseConfig = {
// apiKey: import.meta.env.FIREBASE_API_KEY,
// authDomain: import.meta.env.FIREBASE_AUTH_DOMAIN,
// projectId: import.meta.env.FIREBASE_PROJECT_ID,
// storageBucket: import.meta.env.FIREBASE_STORAGE_BUCKET,
// messagingSenderId: import.meta.env.FIREBASE_MESSAGING_SENDER_ID,
// appId: import.meta.env.FIREBASE_APP_ID,
// measurementId: import.meta.env.FIREBASE_MEASUREMENT_ID,
// apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
// authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
// projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
// storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
// messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
// appId: import.meta.env.VITE_FIREBASE_APP_ID,
// measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID,
// };
// const app = initializeApp(firebaseConfig);
// const analytics = getAnalytics(app);
// export const app = initializeApp(firebaseConfig);
// export const messaging = getMessaging(app);
// export async function registerServiceWorker() {
// if ('serviceWorker' in navigator) {
// try {
// console.log('서비스 워커 등록 시도 중...');
// const firebaseRegistration = await navigator.serviceWorker.register('/firebase-messaging-sw.js');
// console.log('Firebase Service Worker 등록 성공');
// console.log('서비스 워커 활성화 대기 중...');
// const serviceWorker = await navigator.serviceWorker.ready;
// console.log('서비스 워커 활성화');
// if (serviceWorker && !sessionStorage.getItem('fcmToken')) {
// console.log('세션 체크 중...');
// const permission = await Notification.requestPermission();
// if (permission === 'granted') {
// console.log('알림 권한 허용됨');
// const currentToken = await getToken(messaging, {
// vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
// serviceWorkerRegistration: firebaseRegistration,
// });
// if (currentToken) {
// sessionStorage.setItem('fcmToken', currentToken);
// } else {
// console.warn('FCM 토큰을 가져올 수 없습니다. 권한이 없거나 문제가 발생했습니다.');
// }
// } else {
// console.log('알림 권한이 거부되었습니다.');
// }
// }
// } catch (error) {
// console.error('Service Worker 등록 실패:', error);
// }
// } else {
// console.warn('Service Worker not supported in this browser');
// }
// }

View File

@ -0,0 +1,90 @@
import { createTestNotification, saveFcmToken } from '@/api/authApi';
import { Button } from '@/components/ui/button';
import { initializeApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from 'firebase/messaging';
export default function FirebaseTest() {
const firebaseConfig = {
apiKey: import.meta.env.VITE_FIREBASE_API_KEY,
authDomain: import.meta.env.VITE_FIREBASE_AUTH_DOMAIN,
projectId: import.meta.env.VITE_FIREBASE_PROJECT_ID,
storageBucket: import.meta.env.VITE_FIREBASE_STORAGE_BUCKET,
messagingSenderId: import.meta.env.VITE_FIREBASE_MESSAGING_SENDER_ID,
appId: import.meta.env.VITE_FIREBASE_APP_ID,
measurementId: import.meta.env.VITE_FIREBASE_MEASUREMENT_ID,
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
onMessage(messaging, (payload) => {
console.log('Message recieved. ', payload);
if (!payload || !payload.notification) return;
// 메시지 내용에 따라 사용자에게 알림을 표시할 수 있습니다.
const { title, body } = payload.notification;
if (!title || !body) return;
new Notification(title, { body });
});
const getFcmToken = async () => {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
const currentToken = await getToken(messaging, {
vapidKey: 'BApIruZrx83suCd09dnDCkFSP_Ts08q38trrIL6GHpChtbjQHTHk_38_JRyTiKLqciHxLQ8iXtie3lvgyb4Iphg',
});
if (currentToken) {
sessionStorage.setItem('fcmToken', currentToken);
console.log(currentToken);
} else {
console.warn('FCM 토큰을 가져올 수 없습니다. 권한이 없거나 문제가 발생했습니다.');
}
} else {
console.log('알림 권한이 거부되었습니다.');
}
return null;
};
const handleSaveToken = () => {
const fcmToken = sessionStorage.getItem('fcmToken');
if (fcmToken) {
saveFcmToken(fcmToken);
console.log(fcmToken);
}
};
const handleTest = () => {
createTestNotification();
console.log('ok');
};
getFcmToken();
return (
<div>
<h1 className="heading p-2">hello, firebase!</h1>
<div className="p-2">
<Button
onClick={handleSaveToken}
variant="outlinePrimary"
className="mr-2"
>
handleSaveToken
</Button>
<Button
onClick={handleTest}
variant="outlinePrimary"
>
handleTest
</Button>
</div>
</div>
);
}

View File

@ -20,6 +20,7 @@ import NotFound from '@/pages/NotFound';
import ReviewRequest from '@/pages/ReviewRequest';
import ModelIndex from '@/pages/ModelIndex';
import ModelDetail from '@/pages/ModelDetail';
import FirebaseTest from '@/pages/FirebaseTest';
export const webPath = {
home: () => '/',
@ -27,6 +28,7 @@ export const webPath = {
workspace: () => '/workspace',
admin: () => `/admin`,
oauthCallback: () => '/redirect/oauth2',
firebaseTest: () => '/firebaseTest',
};
const router = createBrowserRouter([
@ -151,6 +153,14 @@ const router = createBrowserRouter([
</Suspense>
),
},
{
path: webPath.firebaseTest(),
element: (
<Suspense fallback={<div></div>}>
<FirebaseTest />
</Suspense>
),
},
]);
export default router;