FSTCredentialsProvider.mm 5.7 KB

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