Как установить и получить доступ к переменным среды (закрытые ключи API) из облачных функций Firebase в приложении для iOS - PullRequest
0 голосов
/ 25 сентября 2019

Я использую Firebase для своего бэкэнда, удаленных уведомлений и использую Google Maps и Places API внутри моего приложения для iOS.Все работает нормально, но я хочу скрыть свои учетные данные API .

Для отправки удаленного уведомления мне нужен ключ сервера от Firebase, а для доступа к API Google Maps и Places мне нужны их учетные данные API

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    static var fbServerKey = "someReallyLongFirebaseServerKey"

    override init() {
        super.init()

        Messaging.messaging().delegate = self
        FirebaseApp.configure()

        GMSPlacesClient.provideAPIKey("my_Places_API_Key") // places api credential key
        GMSServices.provideAPIKey("my_Maps_API_Key") // maps api credential key

        GMSPlacesClient.openSourceLicenseInfo()
        GMSServices.openSourceLicenseInfo()
        GADMobileAds.sharedInstance().start(completionHandler: nil)    
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    }
}

Чтобы отправить push-уведомление, я получаю доступ к fbServerKey из AppDelegate:

let fbServerKey = AppDelegate.fbServerKey // *** 1. the server key is accessed here and used below ***

var params = [String: Any]() // add keys and values to params

var request = URLRequest(url: URL(string: "https://fcm.googleapis.com/fcm/send")!)
request.httpMethod = "POST"

// *** 2. the server key is used HERE ***
request.setValue("key=\(fbServerKey)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in ...

У меня есть свои правила Firebase, но если вы посмотрите на приведенный выше код, fbServerKey ивсе учетные данные API карт / мест находятся в текст .

Чтобы избежать этой проблемы, я переключился на использование CloudKit:

// these keys are all set prior to going live and won't be inside the user's applications
NSUbiquitousKeyValueStore().set("someReallyLongFirebaseServerKey", forKey: "fbServerKey")
NSUbiquitousKeyValueStore().set("my_Places_API_Key", forKey: "placesAPIKey")
NSUbiquitousKeyValueStore().set("my_Maps_API_Key", forKey: "mapsAPIKey")
NSUbiquitousKeyValueStore().synchronize()

Для получения ключей:

static var fbServerKey = NSUbiquitousKeyValueStore()string(forKey: "fbServerKey")

GMSPlacesClient.provideAPIKey(NSUbiquitousKeyValueStore()string(forKey: "placesAPIKey"))
GMSServices.provideAPIKey(NSUbiquitousKeyValueStore()string(forKey: "mapsAPIKey"))

Проблема здесь в том, что если пользователь не подключен к iCloud, он не сможет получить доступ к ключам.

Сейчас я нахожусь в процессеперехода на облачные функции Firebase.Дело в том, что мне непонятно, как его использовать.

1- В терминале I cd в папку моего проекта Xcode и запускаю

// $ firebase init functions *** I initially used this command but DO NOT RUN THIS line >firebase init functions<. Read the first comment below from @DougStevenson for the reason to avoid it
$ npm install -g firebase-tools
$ npm install --save firebase-functions@latest

2- Я выбираю проект fbЯ хочу развернуть облачные функции на

3- Я устанавливаю ключи, используя нижеприведенное значение, из-за которого я теряюсь, потому что я не знаю, что такое someservice.key, и при этом я не знаю, что такое someservice.id илия на 100% уверен, где найти my client id (я предполагаю, что это CLIENT_ID из GoogleService-Info.plist)

$ firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID

4- Внутри предоставленной папки functions/index.js я добавляю кодустановите код из шага 3

const functions = require('firebase-functions'); // already present
// don't know what to add here???

5- Чтобы развернуть код, который я запускаю:

$ firebase deploy --only functions

6- Теперь, когда код находится в облаке, я могу как-то вызвать этот код изнутрив моем приложении для безопасного доступа к ключам?

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    static var fbServerKey = somehow_Call_The_Firebase_GetFunction_For_This_Server_Key

    override init() {
        super.init()

        Messaging.messaging().delegate = self
        FirebaseApp.configure()

        GMSPlacesClient.provideAPIKey(somehow_Call_The_Firebase_GetFunction_For_This_Places_Key) // places api credential key
        GMSServices.provideAPIKey(somehow_Call_The_Firebase_GetFunction_For_This_Maps_Key) // maps api credential key

        GMSPlacesClient.openSourceLicenseInfo()
        GMSServices.openSourceLicenseInfo()
        GADMobileAds.sharedInstance().start(completionHandler: nil)    
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    }
}

Мне нужна помощь с шагами 3, 4 и 6

...