FIRInstallations.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseInstallations/Source/Library/Public/FirebaseInstallations/FIRInstallations.h"
  17. #if __has_include(<FBLPromises/FBLPromises.h>)
  18. #import <FBLPromises/FBLPromises.h>
  19. #else
  20. #import "FBLPromises.h"
  21. #endif
  22. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  23. #import "FirebaseInstallations/Source/Library/FIRInstallationsAuthTokenResultInternal.h"
  24. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsErrorUtil.h"
  25. #import "FirebaseInstallations/Source/Library/FIRInstallationsItem.h"
  26. #import "FirebaseInstallations/Source/Library/FIRInstallationsLogger.h"
  27. #import "FirebaseInstallations/Source/Library/InstallationsIDController/FIRInstallationsIDController.h"
  28. #import "FirebaseInstallations/Source/Library/InstallationsStore/FIRInstallationsStoredAuthToken.h"
  29. NS_ASSUME_NONNULL_BEGIN
  30. static const NSUInteger kExpectedAPIKeyLength = 39;
  31. @protocol FIRInstallationsInstanceProvider <FIRLibrary>
  32. @end
  33. @interface FIRInstallations () <FIRInstallationsInstanceProvider>
  34. @property(nonatomic, readonly) FIROptions *appOptions;
  35. @property(nonatomic, readonly) NSString *appName;
  36. @property(nonatomic, readonly) FIRInstallationsIDController *installationsIDController;
  37. @end
  38. @implementation FIRInstallations
  39. #pragma mark - Firebase component
  40. + (void)load {
  41. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-install"];
  42. }
  43. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  44. FIRComponentCreationBlock creationBlock =
  45. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  46. *isCacheable = YES;
  47. FIRInstallations *installations = [[FIRInstallations alloc] initWithApp:container.app];
  48. return installations;
  49. };
  50. FIRComponent *installationsProvider =
  51. [FIRComponent componentWithProtocol:@protocol(FIRInstallationsInstanceProvider)
  52. instantiationTiming:FIRInstantiationTimingAlwaysEager
  53. dependencies:@[]
  54. creationBlock:creationBlock];
  55. return @[ installationsProvider ];
  56. }
  57. - (instancetype)initWithApp:(FIRApp *)app {
  58. FIRInstallationsIDController *IDController =
  59. [[FIRInstallationsIDController alloc] initWithApp:app];
  60. // `prefetchAuthToken` is disabled due to b/156746574.
  61. return [self initWithAppOptions:app.options
  62. appName:app.name
  63. installationsIDController:IDController
  64. prefetchAuthToken:NO];
  65. }
  66. /// This designated initializer can be exposed for testing.
  67. - (instancetype)initWithAppOptions:(FIROptions *)appOptions
  68. appName:(NSString *)appName
  69. installationsIDController:(FIRInstallationsIDController *)installationsIDController
  70. prefetchAuthToken:(BOOL)prefetchAuthToken {
  71. self = [super init];
  72. if (self) {
  73. [[self class] validateAppOptions:appOptions appName:appName];
  74. [[self class] assertCompatibleIIDVersion];
  75. _appOptions = [appOptions copy];
  76. _appName = [appName copy];
  77. _installationsIDController = installationsIDController;
  78. // Pre-fetch auth token.
  79. if (prefetchAuthToken) {
  80. [self authTokenWithCompletion:^(FIRInstallationsAuthTokenResult *_Nullable tokenResult,
  81. NSError *_Nullable error){
  82. }];
  83. }
  84. }
  85. return self;
  86. }
  87. + (void)validateAppOptions:(FIROptions *)appOptions appName:(NSString *)appName {
  88. NSMutableArray *missingFields = [NSMutableArray array];
  89. if (appName.length < 1) {
  90. [missingFields addObject:@"`FirebaseApp.name`"];
  91. }
  92. if (appOptions.APIKey.length < 1) {
  93. [missingFields addObject:@"`FirebaseOptions.APIKey`"];
  94. }
  95. if (appOptions.googleAppID.length < 1) {
  96. [missingFields addObject:@"`FirebaseOptions.googleAppID`"];
  97. }
  98. if (appOptions.projectID.length < 1) {
  99. [missingFields addObject:@"`FirebaseOptions.projectID`"];
  100. }
  101. if (missingFields.count > 0) {
  102. [NSException
  103. raise:kFirebaseInstallationsErrorDomain
  104. format:
  105. @"%@[%@] Could not configure Firebase Installations due to invalid FirebaseApp "
  106. @"options. The following parameters are nil or empty: %@. If you use "
  107. @"GoogleServices-Info.plist please download the most recent version from the Firebase "
  108. @"Console. If you configure Firebase in code, please make sure you specify all "
  109. @"required parameters.",
  110. kFIRLoggerInstallations, kFIRInstallationsMessageCodeInvalidFirebaseAppOptions,
  111. [missingFields componentsJoinedByString:@", "]];
  112. }
  113. [self validateAPIKey:appOptions.APIKey];
  114. }
  115. + (void)validateAPIKey:(nullable NSString *)APIKey {
  116. NSMutableArray<NSString *> *validationIssues = [[NSMutableArray alloc] init];
  117. if (APIKey.length != kExpectedAPIKeyLength) {
  118. [validationIssues addObject:[NSString stringWithFormat:@"API Key length must be %lu characters",
  119. (unsigned long)kExpectedAPIKeyLength]];
  120. }
  121. if (![[APIKey substringToIndex:1] isEqualToString:@"A"]) {
  122. [validationIssues addObject:@"API Key must start with `A`"];
  123. }
  124. NSMutableCharacterSet *allowedCharacters = [NSMutableCharacterSet alphanumericCharacterSet];
  125. [allowedCharacters
  126. formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:@"-_"]];
  127. NSCharacterSet *characters = [NSCharacterSet characterSetWithCharactersInString:APIKey];
  128. if (![allowedCharacters isSupersetOfSet:characters]) {
  129. [validationIssues addObject:@"API Key must contain only base64 url-safe characters characters"];
  130. }
  131. if (validationIssues.count > 0) {
  132. [NSException
  133. raise:kFirebaseInstallationsErrorDomain
  134. format:
  135. @"%@[%@] Could not configure Firebase Installations due to invalid FirebaseApp "
  136. @"options. `FirebaseOptions.APIKey` doesn't match the expected format: %@. If you use "
  137. @"GoogleServices-Info.plist please download the most recent version from the Firebase "
  138. @"Console. If you configure Firebase in code, please make sure you specify all "
  139. @"required parameters.",
  140. kFIRLoggerInstallations, kFIRInstallationsMessageCodeInvalidFirebaseAppOptions,
  141. [validationIssues componentsJoinedByString:@", "]];
  142. }
  143. }
  144. #pragma mark - Public
  145. + (FIRInstallations *)installations {
  146. FIRApp *defaultApp = [FIRApp defaultApp];
  147. if (!defaultApp) {
  148. [NSException raise:kFirebaseInstallationsErrorDomain
  149. format:@"The default FirebaseApp instance must be configured before the default"
  150. @"FirebaseApp instance can be initialized. One way to ensure this is to "
  151. @"call `FirebaseApp.configure()` in the App Delegate's "
  152. @"`application(_:didFinishLaunchingWithOptions:)` "
  153. @"(or the `@main` struct's initializer in SwiftUI)."];
  154. }
  155. return [self installationsWithApp:defaultApp];
  156. }
  157. + (FIRInstallations *)installationsWithApp:(FIRApp *)app {
  158. id<FIRInstallationsInstanceProvider> installations =
  159. FIR_COMPONENT(FIRInstallationsInstanceProvider, app.container);
  160. return (FIRInstallations *)installations;
  161. }
  162. - (void)installationIDWithCompletion:(FIRInstallationsIDHandler)completion {
  163. [self.installationsIDController getInstallationItem]
  164. .then(^id(FIRInstallationsItem *installation) {
  165. completion(installation.firebaseInstallationID, nil);
  166. return nil;
  167. })
  168. .catch(^(NSError *error) {
  169. completion(nil, [FIRInstallationsErrorUtil publicDomainErrorWithError:error]);
  170. });
  171. }
  172. - (void)authTokenWithCompletion:(FIRInstallationsTokenHandler)completion {
  173. [self authTokenForcingRefresh:NO completion:completion];
  174. }
  175. - (void)authTokenForcingRefresh:(BOOL)forceRefresh
  176. completion:(FIRInstallationsTokenHandler)completion {
  177. [self.installationsIDController getAuthTokenForcingRefresh:forceRefresh]
  178. .then(^FIRInstallationsAuthTokenResult *(FIRInstallationsItem *installation) {
  179. FIRInstallationsAuthTokenResult *result = [[FIRInstallationsAuthTokenResult alloc]
  180. initWithToken:installation.authToken.token
  181. expirationDate:installation.authToken.expirationDate];
  182. return result;
  183. })
  184. .then(^id(FIRInstallationsAuthTokenResult *token) {
  185. completion(token, nil);
  186. return nil;
  187. })
  188. .catch(^void(NSError *error) {
  189. completion(nil, [FIRInstallationsErrorUtil publicDomainErrorWithError:error]);
  190. });
  191. }
  192. - (void)deleteWithCompletion:(void (^)(NSError *__nullable error))completion {
  193. [self.installationsIDController deleteInstallation]
  194. .then(^id(id result) {
  195. completion(nil);
  196. return nil;
  197. })
  198. .catch(^void(NSError *error) {
  199. completion([FIRInstallationsErrorUtil publicDomainErrorWithError:error]);
  200. });
  201. }
  202. #pragma mark - IID version compatibility
  203. + (void)assertCompatibleIIDVersion {
  204. // We use this flag to disable IID compatibility exception for unit tests.
  205. #ifdef FIR_INSTALLATIONS_ALLOWS_INCOMPATIBLE_IID_VERSION
  206. return;
  207. #else
  208. if (![self isIIDVersionCompatible]) {
  209. [NSException
  210. raise:kFirebaseInstallationsErrorDomain
  211. format:@"Firebase Instance ID is not compatible with Firebase 8.x+. Please remove the "
  212. @"dependency from the app. See the documentation at "
  213. @"https://firebase.google.com/docs/cloud-messaging/ios/"
  214. @"client#fetching-the-current-registration-token."];
  215. }
  216. #endif
  217. }
  218. + (BOOL)isIIDVersionCompatible {
  219. Class IIDClass = NSClassFromString(@"FIRInstanceID");
  220. if (IIDClass == nil) {
  221. // It is OK if there is no IID at all.
  222. return YES;
  223. }
  224. // We expect a compatible version having the method `+[FIRInstanceID usesFIS]` defined.
  225. BOOL isCompatibleVersion = [IIDClass respondsToSelector:NSSelectorFromString(@"usesFIS")];
  226. return isCompatibleVersion;
  227. }
  228. @end
  229. NS_ASSUME_NONNULL_END