Files
sumoc-backend/src/main/java/SuMoC/backend/firebase/FirebaseConfiguration.java
T
neuhauss fb49fa2130
LocationBasedServices/sumoc-backend/pipeline/head This commit looks good
prevent error when firebase is already inited
2026-01-25 18:22:17 +01:00

57 lines
2.0 KiB
Java

package SuMoC.backend.firebase;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.io.InputStream;
@Configuration
@EnableConfigurationProperties(FirebaseProperties.class)
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "firebase.config", name = "enabled", havingValue = "true", matchIfMissing = false)
public class FirebaseConfiguration {
private final FirebaseProperties firebaseProperties;
@Bean
FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) {
return FirebaseMessaging.getInstance(firebaseApp);
}
@Bean
FirebaseApp firebaseApp(GoogleCredentials credentials) {
try {
return FirebaseApp.getInstance();
} catch (IllegalStateException e) {
// App doesn't exist yet, create it
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(credentials)
.build();
return FirebaseApp.initializeApp(options);
}
}
@Bean
GoogleCredentials googleCredentials(FirebaseProperties firebaseProperties) throws IOException {
if (firebaseProperties.serviceAccount() != null) {
try (InputStream is = firebaseProperties.serviceAccount().getInputStream()) {
return GoogleCredentials.fromStream(is);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
// Use standard credentials chain. Useful when running inside GKE
return GoogleCredentials.getApplicationDefault();
}
}
}