GIDGoogleUser.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  15. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  16. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  18. #import "GoogleSignIn/Sources/GIDAuthentication.h"
  19. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  20. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  21. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  22. #import "GoogleSignIn/Sources/GIDSignInConstants.h"
  23. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  24. #import "GoogleSignIn/Sources/GIDToken_Private.h"
  25. @import GTMAppAuth;
  26. #ifdef SWIFT_PACKAGE
  27. @import AppAuth;
  28. #else
  29. #import <AppAuth/AppAuth.h>
  30. #endif
  31. NS_ASSUME_NONNULL_BEGIN
  32. // The ID Token claim key for the hosted domain value.
  33. static NSString *const kHostedDomainIDTokenClaimKey = @"hd";
  34. // Key constants used for encode and decode.
  35. static NSString *const kProfileDataKey = @"profileData";
  36. static NSString *const kAuthStateKey = @"authState";
  37. // Additional parameter names for EMM.
  38. static NSString *const kEMMSupportParameterName = @"emm_support";
  39. // Minimal time interval before expiration for the access token or it needs to be refreshed.
  40. static NSTimeInterval const kMinimalTimeToExpire = 60.0;
  41. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  42. @interface GIDGoogleUser ()
  43. @property (nonatomic, strong) id<GTMAuthSessionDelegate> authSessionDelegate;
  44. @end
  45. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  46. @implementation GIDGoogleUser {
  47. GIDConfiguration *_cachedConfiguration;
  48. // A queue for pending token refresh handlers so we don't fire multiple requests in parallel.
  49. // Access to this ivar should be synchronized.
  50. NSMutableArray<GIDGoogleUserCompletion> *_tokenRefreshHandlerQueue;
  51. }
  52. - (nullable NSString *)userID {
  53. NSString *idTokenString = self.idToken.tokenString;
  54. if (idTokenString) {
  55. OIDIDToken *idTokenDecoded = [[OIDIDToken alloc] initWithIDTokenString:idTokenString];
  56. if (idTokenDecoded && idTokenDecoded.subject) {
  57. return [idTokenDecoded.subject copy];
  58. }
  59. }
  60. return nil;
  61. }
  62. - (nullable NSArray<NSString *> *)grantedScopes {
  63. NSArray<NSString *> *grantedScopes;
  64. NSString *grantedScopeString = self.authState.lastTokenResponse.scope;
  65. if (grantedScopeString) {
  66. // If we have a 'scope' parameter from the backend, this is authoritative.
  67. // Remove leading and trailing whitespace.
  68. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  69. [NSCharacterSet whitespaceCharacterSet]];
  70. // Tokenize with space as a delimiter.
  71. NSMutableArray<NSString *> *parsedScopes =
  72. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  73. // Remove empty strings.
  74. [parsedScopes removeObject:@""];
  75. grantedScopes = [parsedScopes copy];
  76. }
  77. return grantedScopes;
  78. }
  79. - (GIDConfiguration *)configuration {
  80. @synchronized(self) {
  81. // Caches the configuration since it would not change for one GIDGoogleUser instance.
  82. if (!_cachedConfiguration) {
  83. NSString *clientID = self.authState.lastAuthorizationResponse.request.clientID;
  84. NSString *serverClientID =
  85. self.authState.lastTokenResponse.request.additionalParameters[kAudienceParameter];
  86. NSString *openIDRealm =
  87. self.authState.lastTokenResponse.request.additionalParameters[kOpenIDRealmParameter];
  88. _cachedConfiguration = [[GIDConfiguration alloc] initWithClientID:clientID
  89. serverClientID:serverClientID
  90. hostedDomain:[self hostedDomain]
  91. openIDRealm:openIDRealm];
  92. };
  93. }
  94. return _cachedConfiguration;
  95. }
  96. - (void)refreshTokensIfNeededWithCompletion:(GIDGoogleUserCompletion)completion {
  97. if (!([self.accessToken.expirationDate timeIntervalSinceNow] < kMinimalTimeToExpire ||
  98. (self.idToken && [self.idToken.expirationDate timeIntervalSinceNow] < kMinimalTimeToExpire))) {
  99. dispatch_async(dispatch_get_main_queue(), ^{
  100. completion(self, nil);
  101. });
  102. return;
  103. }
  104. @synchronized (_tokenRefreshHandlerQueue) {
  105. // Push the handler into the callback queue.
  106. [_tokenRefreshHandlerQueue addObject:[completion copy]];
  107. if (_tokenRefreshHandlerQueue.count > 1) {
  108. // This is not the first handler in the queue, no fetch is needed.
  109. return;
  110. }
  111. }
  112. // This is the first handler in the queue, a fetch is needed.
  113. NSMutableDictionary *additionalParameters = [@{} mutableCopy];
  114. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  115. [additionalParameters addEntriesFromDictionary:
  116. [GIDEMMSupport updatedEMMParametersWithParameters:
  117. self.authState.lastTokenResponse.request.additionalParameters]];
  118. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  119. [additionalParameters addEntriesFromDictionary:
  120. self.authState.lastTokenResponse.request.additionalParameters];
  121. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  122. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  123. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  124. OIDTokenRequest *tokenRefreshRequest =
  125. [self.authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  126. [OIDAuthorizationService performTokenRequest:tokenRefreshRequest
  127. originalAuthorizationResponse:self.authState.lastAuthorizationResponse
  128. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  129. NSError *_Nullable error) {
  130. if (tokenResponse) {
  131. [self.authState updateWithTokenResponse:tokenResponse error:nil];
  132. } else {
  133. if (error.domain == OIDOAuthTokenErrorDomain) {
  134. [self.authState updateWithAuthorizationError:error];
  135. }
  136. }
  137. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  138. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *_Nullable error) {
  139. // Process the handler queue to call back.
  140. NSArray<GIDGoogleUserCompletion> *refreshTokensHandlerQueue;
  141. @synchronized(self->_tokenRefreshHandlerQueue) {
  142. refreshTokensHandlerQueue = [self->_tokenRefreshHandlerQueue copy];
  143. [self->_tokenRefreshHandlerQueue removeAllObjects];
  144. }
  145. for (GIDGoogleUserCompletion completion in refreshTokensHandlerQueue) {
  146. dispatch_async(dispatch_get_main_queue(), ^{
  147. completion(error ? nil : self, error);
  148. });
  149. }
  150. }];
  151. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  152. NSArray<GIDGoogleUserCompletion> *refreshTokensHandlerQueue;
  153. @synchronized(self->_tokenRefreshHandlerQueue) {
  154. refreshTokensHandlerQueue = [self->_tokenRefreshHandlerQueue copy];
  155. [self->_tokenRefreshHandlerQueue removeAllObjects];
  156. }
  157. for (GIDGoogleUserCompletion completion in refreshTokensHandlerQueue) {
  158. dispatch_async(dispatch_get_main_queue(), ^{
  159. completion(error ? nil : self, error);
  160. });
  161. }
  162. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  163. }];
  164. }
  165. - (OIDAuthState *)authState {
  166. return ((GTMAuthSession *)self.fetcherAuthorizer).authState;
  167. }
  168. - (void)addScopes:(NSArray<NSString *> *)scopes
  169. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  170. presentingViewController:(UIViewController *)presentingViewController
  171. #elif TARGET_OS_OSX
  172. presentingWindow:(NSWindow *)presentingWindow
  173. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  174. completion:(nullable void (^)(GIDSignInResult *_Nullable signInResult,
  175. NSError *_Nullable error))completion {
  176. if (self != GIDSignIn.sharedInstance.currentUser) {
  177. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  178. code:kGIDSignInErrorCodeMismatchWithCurrentUser
  179. userInfo:nil];
  180. if (completion) {
  181. dispatch_async(dispatch_get_main_queue(), ^{
  182. completion(nil, error);
  183. });
  184. }
  185. return;
  186. }
  187. [GIDSignIn.sharedInstance addScopes:scopes
  188. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  189. presentingViewController:presentingViewController
  190. #elif TARGET_OS_OSX
  191. presentingWindow:presentingWindow
  192. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  193. completion:completion];
  194. }
  195. #pragma mark - Private Methods
  196. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  197. - (nullable NSString *)emmSupport {
  198. return self.authState.lastAuthorizationResponse
  199. .request.additionalParameters[kEMMSupportParameterName];
  200. }
  201. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  202. - (instancetype)initWithAuthState:(OIDAuthState *)authState
  203. profileData:(nullable GIDProfileData *)profileData {
  204. self = [super init];
  205. if (self) {
  206. _tokenRefreshHandlerQueue = [[NSMutableArray alloc] init];
  207. _profile = profileData;
  208. GTMAuthSession *authSession = [[GTMAuthSession alloc] initWithAuthState:authState];
  209. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  210. _authSessionDelegate = [[GIDEMMSupport alloc] init];
  211. authSession.delegate = _authSessionDelegate;
  212. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  213. authSession.authState.stateChangeDelegate = self;
  214. _fetcherAuthorizer = authSession;
  215. [self updateTokensWithAuthState:authState];
  216. }
  217. return self;
  218. }
  219. - (void)updateWithTokenResponse:(OIDTokenResponse *)tokenResponse
  220. authorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  221. profileData:(nullable GIDProfileData *)profileData {
  222. @synchronized(self) {
  223. _profile = profileData;
  224. // We don't want to trigger the delegate before we update authState completely. So we unset the
  225. // delegate before the first update. Also the order of updates is important because
  226. // `updateWithAuthorizationResponse` would clear the last token reponse and refresh token.
  227. // TODO: Rewrite authState update logic when the issue is addressed.(openid/AppAuth-iOS#728)
  228. self.authState.stateChangeDelegate = nil;
  229. [self.authState updateWithAuthorizationResponse:authorizationResponse error:nil];
  230. self.authState.stateChangeDelegate = self;
  231. [self.authState updateWithTokenResponse:tokenResponse error:nil];
  232. }
  233. }
  234. - (void)updateTokensWithAuthState:(OIDAuthState *)authState {
  235. GIDToken *accessToken =
  236. [[GIDToken alloc] initWithTokenString:authState.lastTokenResponse.accessToken
  237. expirationDate:authState.lastTokenResponse.accessTokenExpirationDate];
  238. if (![self.accessToken isEqualToToken:accessToken]) {
  239. self.accessToken = accessToken;
  240. }
  241. GIDToken *refreshToken = [[GIDToken alloc] initWithTokenString:authState.refreshToken
  242. expirationDate:nil];
  243. if (![self.refreshToken isEqualToToken:refreshToken]) {
  244. self.refreshToken = refreshToken;
  245. }
  246. GIDToken *idToken;
  247. NSString *idTokenString = authState.lastTokenResponse.idToken;
  248. if (idTokenString) {
  249. NSDate *idTokenExpirationDate =
  250. [[[OIDIDToken alloc] initWithIDTokenString:idTokenString] expiresAt];
  251. idToken = [[GIDToken alloc] initWithTokenString:idTokenString
  252. expirationDate:idTokenExpirationDate];
  253. } else {
  254. idToken = nil;
  255. }
  256. if ((self.idToken || idToken) && ![self.idToken isEqualToToken:idToken]) {
  257. self.idToken = idToken;
  258. }
  259. }
  260. #pragma mark - Helpers
  261. - (nullable NSString *)hostedDomain {
  262. NSString *idTokenString = self.idToken.tokenString;
  263. if (idTokenString) {
  264. OIDIDToken *idTokenDecoded = [[OIDIDToken alloc] initWithIDTokenString:idTokenString];
  265. if (idTokenDecoded && idTokenDecoded.claims[kHostedDomainIDTokenClaimKey]) {
  266. return idTokenDecoded.claims[kHostedDomainIDTokenClaimKey];
  267. }
  268. }
  269. return nil;
  270. }
  271. #pragma mark - OIDAuthStateChangeDelegate
  272. - (void)didChangeState:(OIDAuthState *)state {
  273. [self updateTokensWithAuthState:state];
  274. }
  275. #pragma mark - NSSecureCoding
  276. + (BOOL)supportsSecureCoding {
  277. return YES;
  278. }
  279. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  280. self = [super init];
  281. if (self) {
  282. GIDProfileData *profile =
  283. [decoder decodeObjectOfClass:[GIDProfileData class] forKey:kProfileDataKey];
  284. OIDAuthState *authState;
  285. if ([decoder containsValueForKey:kAuthStateKey]) { // Current encoding
  286. authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey];
  287. } else { // Old encoding
  288. GIDAuthentication *authentication = [decoder decodeObjectOfClass:[GIDAuthentication class]
  289. forKey:@"authentication"];
  290. authState = authentication.authState;
  291. }
  292. self = [self initWithAuthState:authState profileData:profile];
  293. }
  294. return self;
  295. }
  296. - (void)encodeWithCoder:(NSCoder *)encoder {
  297. [encoder encodeObject:_profile forKey:kProfileDataKey];
  298. [encoder encodeObject:self.authState forKey:kAuthStateKey];
  299. }
  300. @end
  301. NS_ASSUME_NONNULL_END