FSTCredentialsProvider.m 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /*
  2. * Copyright 2017 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 "Firestore/Source/Auth/FSTCredentialsProvider.h"
  17. #import <FirebaseCore/FIRApp.h>
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <GRPCClient/GRPCCall.h>
  20. #import "FIRFirestoreErrors.h"
  21. #import "Firestore/Source/Auth/FSTUser.h"
  22. #import "Firestore/Source/Util/FSTAssert.h"
  23. #import "Firestore/Source/Util/FSTClasses.h"
  24. #import "Firestore/Source/Util/FSTDispatchQueue.h"
  25. NS_ASSUME_NONNULL_BEGIN
  26. #pragma mark - FSTGetTokenResult
  27. @implementation FSTGetTokenResult
  28. - (instancetype)initWithUser:(FSTUser *)user token:(NSString *_Nullable)token {
  29. if (self = [super init]) {
  30. _user = user;
  31. _token = token;
  32. }
  33. return self;
  34. }
  35. @end
  36. #pragma mark - FSTFirebaseCredentialsProvider
  37. @interface FSTFirebaseCredentialsProvider ()
  38. @property(nonatomic, strong, readonly) FIRApp *app;
  39. /** Handle used to stop receiving auth changes once userChangeListener is removed. */
  40. @property(nonatomic, strong, nullable, readwrite) id<NSObject> authListenerHandle;
  41. /** The current user as reported to us via our AuthStateDidChangeListener. */
  42. @property(nonatomic, strong, nonnull, readwrite) FSTUser *currentUser;
  43. /**
  44. * Counter used to detect if the user changed while a -getTokenForcingRefresh: request was
  45. * outstanding.
  46. */
  47. @property(nonatomic, assign, readwrite) int userCounter;
  48. @end
  49. @implementation FSTFirebaseCredentialsProvider {
  50. FSTVoidUserBlock _userChangeListener;
  51. }
  52. - (instancetype)initWithApp:(FIRApp *)app {
  53. self = [super init];
  54. if (self) {
  55. _app = app;
  56. _currentUser = [[FSTUser alloc] initWithUID:[self.app getUID]];
  57. _userCounter = 0;
  58. // Register for user changes so that we can internally track the current user.
  59. FSTWeakify(self);
  60. _authListenerHandle = [[NSNotificationCenter defaultCenter]
  61. addObserverForName:FIRAuthStateDidChangeInternalNotification
  62. object:nil
  63. queue:nil
  64. usingBlock:^(NSNotification *notification) {
  65. FSTStrongify(self);
  66. if (self) {
  67. @synchronized(self) {
  68. NSDictionary *userInfo = notification.userInfo;
  69. // ensure we're only notifiying for the current app.
  70. FIRApp *notifiedApp =
  71. userInfo[FIRAuthStateDidChangeInternalNotificationAppKey];
  72. if (![self.app isEqual:notifiedApp]) {
  73. return;
  74. }
  75. NSString *userID = userInfo[FIRAuthStateDidChangeInternalNotificationUIDKey];
  76. FSTUser *newUser = [[FSTUser alloc] initWithUID:userID];
  77. if (![newUser isEqual:self.currentUser]) {
  78. self.currentUser = newUser;
  79. self.userCounter++;
  80. FSTVoidUserBlock listenerBlock = self.userChangeListener;
  81. if (listenerBlock) {
  82. listenerBlock(self.currentUser);
  83. }
  84. }
  85. }
  86. }
  87. }];
  88. }
  89. return self;
  90. }
  91. - (void)getTokenForcingRefresh:(BOOL)forceRefresh
  92. completion:(FSTVoidGetTokenResultBlock)completion {
  93. FSTAssert(self.authListenerHandle, @"getToken cannot be called after listener removed.");
  94. // Take note of the current value of the userCounter so that this method can fail (with a
  95. // FIRFirestoreErrorCodeAborted error) if there is a user change while the request is outstanding.
  96. int initialUserCounter = self.userCounter;
  97. void (^getTokenCallback)(NSString *, NSError *) =
  98. ^(NSString *_Nullable token, NSError *_Nullable error) {
  99. @synchronized(self) {
  100. if (initialUserCounter != self.userCounter) {
  101. // Cancel the request since the user changed while the request was outstanding so the
  102. // response is likely for a previous user (which user, we can't be sure).
  103. NSDictionary *errorInfo = @{@"details" : @"getToken aborted due to user change."};
  104. NSError *cancelError = [NSError errorWithDomain:FIRFirestoreErrorDomain
  105. code:FIRFirestoreErrorCodeAborted
  106. userInfo:errorInfo];
  107. completion(nil, cancelError);
  108. } else {
  109. FSTGetTokenResult *result =
  110. [[FSTGetTokenResult alloc] initWithUser:self.currentUser token:token];
  111. completion(result, error);
  112. }
  113. };
  114. };
  115. [self.app getTokenForcingRefresh:forceRefresh withCallback:getTokenCallback];
  116. }
  117. - (void)setUserChangeListener:(nullable FSTVoidUserBlock)block {
  118. @synchronized(self) {
  119. if (block) {
  120. FSTAssert(!_userChangeListener, @"UserChangeListener set twice!");
  121. // Fire initial event.
  122. block(self.currentUser);
  123. } else {
  124. FSTAssert(self.authListenerHandle, @"UserChangeListener removed twice!");
  125. FSTAssert(_userChangeListener, @"UserChangeListener removed without being set!");
  126. [[NSNotificationCenter defaultCenter] removeObserver:self.authListenerHandle];
  127. self.authListenerHandle = nil;
  128. }
  129. _userChangeListener = block;
  130. }
  131. }
  132. - (nullable FSTVoidUserBlock)userChangeListener {
  133. @synchronized(self) {
  134. return _userChangeListener;
  135. }
  136. }
  137. @end
  138. NS_ASSUME_NONNULL_END