From 3c4ff8204e643ef94c7261d8509dce8f0eee7e41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=9A=A9=EC=88=98?= Date: Tue, 24 Sep 2024 11:35:57 +0900 Subject: [PATCH] =?UTF-8?q?Feat:=20FCM=20Config=20=EC=84=A4=EC=A0=95=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/worlabel/global/config/FCMConfig.java | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/backend/src/main/java/com/worlabel/global/config/FCMConfig.java b/backend/src/main/java/com/worlabel/global/config/FCMConfig.java index f745d3f..fe3d47e 100644 --- a/backend/src/main/java/com/worlabel/global/config/FCMConfig.java +++ b/backend/src/main/java/com/worlabel/global/config/FCMConfig.java @@ -1,9 +1,20 @@ package com.worlabel.global.config; +import com.google.auth.oauth2.GoogleCredentials; +import com.google.firebase.FirebaseApp; +import com.google.firebase.FirebaseOptions; +import com.google.firebase.messaging.FirebaseMessaging; +import com.worlabel.global.exception.CustomException; +import com.worlabel.global.exception.ErrorCode; import lombok.RequiredArgsConstructor; -import lombok.Value; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.ClassPathResource; + +import java.io.IOException; +import java.io.InputStream; @Slf4j @Configuration @@ -11,4 +22,30 @@ import org.springframework.context.annotation.Configuration; public class FCMConfig { // Firebase 설정 Json 파일의 경로 + @Value("${fcm.config.path}") + private String FIREBASE_CONFIG_PATH; + + @Bean + FirebaseMessaging firebaseMessaging() { + // 클래스패스에서 Firebase 설정 파일을 리소스로 불러옴 + ClassPathResource resource = new ClassPathResource(FIREBASE_CONFIG_PATH); + + // JSON 파일에서 자격 증명을 불러와 Firebase 옵션을 설정 + try (InputStream serviceAccount = resource.getInputStream()) { + FirebaseOptions options = FirebaseOptions.builder() + .setCredentials(GoogleCredentials.fromStream(serviceAccount)) + .build(); + + // FirebaseApp 인스턴스가 초기화되지 않은 경우 초기화, 이미 존재하는 경우 해당 인스턴스를 가져옴 + FirebaseApp firebaseApp = FirebaseApp.getApps().isEmpty() ? + FirebaseApp.initializeApp(options) : + FirebaseApp.getInstance(); + log.debug("firebase 불러오기 성공"); + // 설정된 FirebaseApp 연결된 FirebaseMessaging 인스턴스를 반환 + return FirebaseMessaging.getInstance(firebaseApp); + } catch (IOException e) { + throw new CustomException(ErrorCode.SERVER_ERROR, "Firebase Key 불러오기 실패 "); + } + } + }