GIDSignIn.m 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  1. // Copyright 2021 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/GIDSignIn.h"
  15. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  16. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDAuthentication.h"
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  18. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  19. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  20. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  21. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  22. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  23. #import "GoogleSignIn/Sources/GIDScopes.h"
  24. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  25. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  26. #import "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  27. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  28. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  29. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  30. #endif
  31. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  32. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  33. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  34. #ifdef SWIFT_PACKAGE
  35. @import AppAuth;
  36. @import GTMAppAuth;
  37. @import GTMSessionFetcherCore;
  38. #else
  39. #import <AppAuth/OIDAuthState.h>
  40. #import <AppAuth/OIDAuthorizationRequest.h>
  41. #import <AppAuth/OIDAuthorizationResponse.h>
  42. #import <AppAuth/OIDAuthorizationService.h>
  43. #import <AppAuth/OIDError.h>
  44. #import <AppAuth/OIDExternalUserAgentSession.h>
  45. #import <AppAuth/OIDIDToken.h>
  46. #import <AppAuth/OIDResponseTypes.h>
  47. #import <AppAuth/OIDServiceConfiguration.h>
  48. #import <AppAuth/OIDTokenRequest.h>
  49. #import <AppAuth/OIDTokenResponse.h>
  50. #import <AppAuth/OIDURLQueryComponent.h>
  51. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  52. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  53. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  54. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  55. #import <AppAuth/OIDAuthorizationService+IOS.h>
  56. #elif TARGET_OS_OSX
  57. #import <AppAuth/OIDAuthorizationService+Mac.h>
  58. #endif
  59. #endif
  60. NS_ASSUME_NONNULL_BEGIN
  61. // The name of the query parameter used for logging the restart of auth from EMM callback.
  62. static NSString *const kEMMRestartAuthParameter = @"emmres";
  63. // The URL template for the authorization endpoint.
  64. static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth";
  65. // The URL template for the token endpoint.
  66. static NSString *const kTokenURLTemplate = @"https://%@/token";
  67. // The URL template for the URL to get user info.
  68. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  69. // The URL template for the URL to revoke the token.
  70. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
  71. // Expected path in the URL scheme to be handled.
  72. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  73. // Expected path for EMM callback.
  74. static NSString *const kEMMCallbackPath = @"/emmcallback";
  75. // The EMM support version
  76. static NSString *const kEMMVersion = @"1";
  77. // The error code for Google Identity.
  78. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  79. // Keychain constants for saving state in the authentication flow.
  80. static NSString *const kGTMAppAuthKeychainName = @"auth";
  81. // Basic profile (Fat ID Token / userinfo endpoint) keys
  82. static NSString *const kBasicProfileEmailKey = @"email";
  83. static NSString *const kBasicProfilePictureKey = @"picture";
  84. static NSString *const kBasicProfileNameKey = @"name";
  85. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  86. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  87. // Parameters in the callback URL coming back from browser.
  88. static NSString *const kAuthorizationCodeKeyName = @"code";
  89. static NSString *const kOAuth2ErrorKeyName = @"error";
  90. static NSString *const kOAuth2AccessDenied = @"access_denied";
  91. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  92. // Error string for unavailable keychain.
  93. static NSString *const kKeychainError = @"keychain error";
  94. // Error string for user cancelations.
  95. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  96. // User preference key to detect fresh install of the app.
  97. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  98. // Maximum retry interval in seconds for the fetcher.
  99. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  100. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  101. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  102. // Parameters for the auth and token exchange endpoints.
  103. static NSString *const kAudienceParameter = @"audience";
  104. // See b/11669751 .
  105. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  106. static NSString *const kIncludeGrantedScopesParameter = @"include_granted_scopes";
  107. static NSString *const kLoginHintParameter = @"login_hint";
  108. static NSString *const kHostedDomainParameter = @"hd";
  109. // Minimum time to expiration for a restored access token.
  110. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  111. // The callback queue used for authentication flow.
  112. @interface GIDAuthFlow : GIDCallbackQueue
  113. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  114. @property(nonatomic, strong, nullable) NSError *error;
  115. @property(nonatomic, copy, nullable) NSString *emmSupport;
  116. @property(nonatomic, nullable) GIDProfileData *profileData;
  117. @end
  118. @implementation GIDAuthFlow
  119. @end
  120. @implementation GIDSignIn {
  121. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  122. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  123. // represent a sign in continuation.
  124. GIDSignInInternalOptions *_currentOptions;
  125. // AppAuth configuration object.
  126. OIDServiceConfiguration *_appAuthConfiguration;
  127. // AppAuth external user-agent session state.
  128. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  129. // Flag to indicate that the auth flow is restarting.
  130. BOOL _restarting;
  131. }
  132. #pragma mark - Public methods
  133. - (BOOL)handleURL:(NSURL *)url {
  134. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  135. if ([url.path isEqual:kBrowserCallbackPath]) {
  136. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  137. _currentAuthorizationFlow = nil;
  138. return YES;
  139. }
  140. return NO;
  141. }
  142. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  143. if ([url.path isEqual:kEMMCallbackPath]) {
  144. return [self handleDevicePolicyAppURL:url];
  145. }
  146. return NO;
  147. }
  148. - (BOOL)hasPreviousSignIn {
  149. if ([_currentUser.authentication.authState isAuthorized]) {
  150. return YES;
  151. }
  152. OIDAuthState *authState = [self loadAuthState];
  153. return [authState isAuthorized];
  154. }
  155. - (void)restorePreviousSignInWithCallback:(nullable GIDSignInCallback)callback {
  156. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCallback:callback]];
  157. }
  158. - (BOOL)restorePreviousSignInNoRefresh {
  159. if (_currentUser) {
  160. return YES;
  161. }
  162. // Try retrieving an authorization object from the keychain.
  163. OIDAuthState *authState = [self loadAuthState];
  164. if (!authState) {
  165. return NO;
  166. }
  167. // Restore current user without refreshing the access token.
  168. OIDIDToken *idToken =
  169. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  170. GIDProfileData *profileData = [self profileDataWithIDToken:idToken];
  171. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  172. [self setCurrentUserWithKVO:user];
  173. return YES;
  174. }
  175. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  176. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  177. presentingViewController:(UIViewController *)presentingViewController
  178. hint:(nullable NSString *)hint
  179. callback:(nullable GIDSignInCallback)callback {
  180. GIDSignInInternalOptions *options =
  181. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  182. presentingViewController:presentingViewController
  183. loginHint:hint
  184. addScopesFlow:NO
  185. callback:callback];
  186. [self signInWithOptions:options];
  187. }
  188. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  189. presentingViewController:(UIViewController *)presentingViewController
  190. hint:(nullable NSString *)hint
  191. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  192. callback:(nullable GIDSignInCallback)callback {
  193. GIDSignInInternalOptions *options =
  194. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  195. presentingViewController:presentingViewController
  196. loginHint:hint
  197. addScopesFlow:NO
  198. scopes:additionalScopes
  199. callback:callback];
  200. [self signInWithOptions:options];
  201. }
  202. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  203. presentingViewController:(UIViewController *)presentingViewController
  204. callback:(nullable GIDSignInCallback)callback {
  205. [self signInWithConfiguration:configuration
  206. presentingViewController:presentingViewController
  207. hint:nil
  208. callback:callback];
  209. }
  210. - (void)addScopes:(NSArray<NSString *> *)scopes
  211. presentingViewController:(UIViewController *)presentingViewController
  212. callback:(nullable GIDSignInCallback)callback {
  213. // A currentUser must be available in order to complete this flow.
  214. if (!self.currentUser) {
  215. // No currentUser is set, notify callback of failure.
  216. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  217. code:kGIDSignInErrorCodeNoCurrentUser
  218. userInfo:nil];
  219. if (callback) {
  220. dispatch_async(dispatch_get_main_queue(), ^{
  221. callback(nil, error);
  222. });
  223. }
  224. return;
  225. }
  226. GIDConfiguration *configuration =
  227. [[GIDConfiguration alloc] initWithClientID:self.currentUser.authentication.clientID
  228. serverClientID:self.currentUser.serverClientID
  229. hostedDomain:self.currentUser.hostedDomain
  230. openIDRealm:self.currentUser.openIDRealm];
  231. GIDSignInInternalOptions *options =
  232. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  233. presentingViewController:presentingViewController
  234. loginHint:self.currentUser.profile.email
  235. addScopesFlow:YES
  236. callback:callback];
  237. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  238. NSMutableSet<NSString *> *grantedScopes =
  239. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  240. // Check to see if all requested scopes have already been granted.
  241. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  242. // All requested scopes have already been granted, notify callback of failure.
  243. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  244. code:kGIDSignInErrorCodeScopesAlreadyGranted
  245. userInfo:nil];
  246. if (callback) {
  247. dispatch_async(dispatch_get_main_queue(), ^{
  248. callback(nil, error);
  249. });
  250. }
  251. return;
  252. }
  253. // Use the union of granted and requested scopes.
  254. [grantedScopes unionSet:requestedScopes];
  255. options.scopes = [grantedScopes allObjects];
  256. [self signInWithOptions:options];
  257. }
  258. #elif TARGET_OS_OSX
  259. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  260. presentingWindow:(NSWindow *)presentingWindow
  261. hint:(nullable NSString *)hint
  262. callback:(nullable GIDSignInCallback)callback {
  263. GIDSignInInternalOptions *options =
  264. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  265. presentingWindow:presentingWindow
  266. loginHint:hint
  267. addScopesFlow:NO
  268. callback:callback];
  269. [self signInWithOptions:options];
  270. }
  271. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  272. presentingWindow:(NSWindow *)presentingWindow
  273. callback:(nullable GIDSignInCallback)callback {
  274. [self signInWithConfiguration:configuration
  275. presentingWindow:presentingWindow
  276. hint:nil
  277. callback:callback];
  278. }
  279. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  280. presentingWindow:(NSWindow *)presentingWindow
  281. hint:(nullable NSString *)hint
  282. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  283. callback:(nullable GIDSignInCallback)callback {
  284. GIDSignInInternalOptions *options =
  285. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  286. presentingWindow:presentingWindow
  287. loginHint:hint
  288. addScopesFlow:NO
  289. scopes:additionalScopes
  290. callback:callback];
  291. [self signInWithOptions:options];
  292. }
  293. - (void)addScopes:(NSArray<NSString *> *)scopes
  294. presentingWindow:(NSWindow *)presentingWindow
  295. callback:(nullable GIDSignInCallback)callback {
  296. // A currentUser must be available in order to complete this flow.
  297. if (!self.currentUser) {
  298. // No currentUser is set, notify callback of failure.
  299. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  300. code:kGIDSignInErrorCodeNoCurrentUser
  301. userInfo:nil];
  302. if (callback) {
  303. dispatch_async(dispatch_get_main_queue(), ^{
  304. callback(nil, error);
  305. });
  306. }
  307. return;
  308. }
  309. GIDConfiguration *configuration =
  310. [[GIDConfiguration alloc] initWithClientID:self.currentUser.authentication.clientID
  311. serverClientID:self.currentUser.serverClientID
  312. hostedDomain:self.currentUser.hostedDomain
  313. openIDRealm:self.currentUser.openIDRealm];
  314. GIDSignInInternalOptions *options =
  315. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  316. presentingWindow:presentingWindow
  317. loginHint:self.currentUser.profile.email
  318. addScopesFlow:YES
  319. callback:callback];
  320. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  321. NSMutableSet<NSString *> *grantedScopes =
  322. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  323. // Check to see if all requested scopes have already been granted.
  324. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  325. // All requested scopes have already been granted, notify callback of failure.
  326. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  327. code:kGIDSignInErrorCodeScopesAlreadyGranted
  328. userInfo:nil];
  329. if (callback) {
  330. dispatch_async(dispatch_get_main_queue(), ^{
  331. callback(nil, error);
  332. });
  333. }
  334. return;
  335. }
  336. // Use the union of granted and requested scopes.
  337. [grantedScopes unionSet:requestedScopes];
  338. options.scopes = [grantedScopes allObjects];
  339. [self signInWithOptions:options];
  340. }
  341. #endif
  342. - (void)signOut {
  343. // Clear the current user if there is one.
  344. if (_currentUser) {
  345. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  346. _currentUser = nil;
  347. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  348. }
  349. // Remove all state from the keychain.
  350. [self removeAllKeychainEntries];
  351. }
  352. - (void)disconnectWithCallback:(nullable GIDDisconnectCallback)callback {
  353. GIDGoogleUser *user = _currentUser;
  354. OIDAuthState *authState = user.authentication.authState;
  355. if (!authState) {
  356. // Even the user is not signed in right now, we still need to remove any token saved in the
  357. // keychain.
  358. authState = [self loadAuthState];
  359. }
  360. // Either access or refresh token would work, but we won't have access token if the auth is
  361. // retrieved from keychain.
  362. NSString *token = authState.lastTokenResponse.accessToken;
  363. if (!token) {
  364. token = authState.lastTokenResponse.refreshToken;
  365. }
  366. if (!token) {
  367. [self signOut];
  368. // Nothing to do here, consider the operation successful.
  369. if (callback) {
  370. dispatch_async(dispatch_get_main_queue(), ^{
  371. callback(nil);
  372. });
  373. }
  374. return;
  375. }
  376. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  377. [GIDSignInPreferences googleAuthorizationServer], token];
  378. // Append logging parameter
  379. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@&%@=%@",
  380. revokeURLString,
  381. kSDKVersionLoggingParameter,
  382. GIDVersion(),
  383. kEnvironmentLoggingParameter,
  384. GIDEnvironment()];
  385. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  386. [self startFetchURL:revokeURL
  387. fromAuthState:authState
  388. withComment:@"GIDSignIn: revoke tokens"
  389. withCompletionHandler:^(NSData *data, NSError *error) {
  390. // Revoking an already revoked token seems always successful, which helps us here.
  391. if (!error) {
  392. [self signOut];
  393. }
  394. if (callback) {
  395. dispatch_async(dispatch_get_main_queue(), ^{
  396. callback(error);
  397. });
  398. }
  399. }];
  400. }
  401. #pragma mark - Custom getters and setters
  402. + (GIDSignIn *)sharedInstance {
  403. static dispatch_once_t once;
  404. static GIDSignIn *sharedInstance;
  405. dispatch_once(&once, ^{
  406. sharedInstance = [[self alloc] initPrivate];
  407. });
  408. return sharedInstance;
  409. }
  410. #pragma mark - Private methods
  411. - (id)initPrivate {
  412. self = [super init];
  413. if (self) {
  414. // Check to see if the 3P app is being run for the first time after a fresh install.
  415. BOOL isFreshInstall = [self isFreshInstall];
  416. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  417. if (isFreshInstall) {
  418. [self removeAllKeychainEntries];
  419. }
  420. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  421. [GIDSignInPreferences googleAuthorizationServer]];
  422. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  423. [GIDSignInPreferences googleTokenServer]];
  424. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  425. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  426. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  427. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  428. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  429. [GIDAuthStateMigration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  430. callbackPath:kBrowserCallbackPath
  431. keychainName:kGTMAppAuthKeychainName
  432. isFreshInstall:isFreshInstall];
  433. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  434. }
  435. return self;
  436. }
  437. // Does sanity check for parameters and then authenticates if necessary.
  438. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  439. // Options for continuation are not the options we want to cache. The purpose of caching the
  440. // options in the first place is to provide continuation flows with a starting place from which to
  441. // derive suitable options for the continuation!
  442. if (!options.continuation) {
  443. _currentOptions = options;
  444. }
  445. if (options.interactive) {
  446. // Explicitly throw exception for missing client ID here. This must come before
  447. // scheme check because schemes rely on reverse client IDs.
  448. [self assertValidParameters];
  449. [self assertValidPresentingViewController];
  450. // If the application does not support the required URL schemes tell the developer so.
  451. GIDSignInCallbackSchemes *schemes =
  452. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  453. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  454. if (unsupportedSchemes.count != 0) {
  455. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  456. [NSException raise:NSInvalidArgumentException
  457. format:@"Your app is missing support for the following URL schemes: %@",
  458. [unsupportedSchemes componentsJoinedByString:@", "]];
  459. }
  460. }
  461. // If this is a non-interactive flow, use cached authentication if possible.
  462. if (!options.interactive && _currentUser.authentication) {
  463. [_currentUser.authentication doWithFreshTokens:^(GIDAuthentication *unused, NSError *error) {
  464. if (error) {
  465. [self authenticateWithOptions:options];
  466. } else {
  467. if (options.callback) {
  468. self->_currentOptions = nil;
  469. dispatch_async(dispatch_get_main_queue(), ^{
  470. options.callback(self->_currentUser, nil);
  471. });
  472. }
  473. }
  474. }];
  475. } else {
  476. [self authenticateWithOptions:options];
  477. }
  478. }
  479. #pragma mark - Authentication flow
  480. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  481. GIDSignInCallbackSchemes *schemes =
  482. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  483. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  484. [schemes clientIdentifierScheme],
  485. kBrowserCallbackPath]];
  486. NSString *emmSupport;
  487. #if TARGET_OS_MACCATALYST || TARGET_OS_OSX
  488. emmSupport = nil;
  489. #elif TARGET_OS_IOS
  490. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  491. #endif
  492. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  493. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  494. if (options.configuration.serverClientID) {
  495. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  496. }
  497. if (options.loginHint) {
  498. additionalParameters[kLoginHintParameter] = options.loginHint;
  499. }
  500. if (options.configuration.hostedDomain) {
  501. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  502. }
  503. #if TARGET_OS_IOS
  504. [additionalParameters addEntriesFromDictionary:
  505. [GIDAuthentication parametersWithParameters:options.extraParams
  506. emmSupport:emmSupport
  507. isPasscodeInfoRequired:NO]];
  508. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  509. [additionalParameters addEntriesFromDictionary:options.extraParams];
  510. #endif
  511. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  512. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  513. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  514. OIDAuthorizationRequest *request =
  515. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  516. clientId:options.configuration.clientID
  517. scopes:options.scopes
  518. redirectURL:redirectURL
  519. responseType:OIDResponseTypeCode
  520. additionalParameters:additionalParameters];
  521. _currentAuthorizationFlow = [OIDAuthorizationService
  522. presentAuthorizationRequest:request
  523. presentingViewController:options.presentingViewController
  524. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  525. NSError *_Nullable error) {
  526. [self processAuthorizationResponse:authorizationResponse
  527. error:error
  528. emmSupport:emmSupport];
  529. }];
  530. #elif TARGET_OS_OSX
  531. OIDAuthorizationRequest *request =
  532. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  533. clientId:options.configuration.clientID
  534. clientSecret:@""
  535. scopes:options.scopes
  536. redirectURL:redirectURL
  537. responseType:OIDResponseTypeCode
  538. additionalParameters:additionalParameters];
  539. _currentAuthorizationFlow = [OIDAuthorizationService
  540. presentAuthorizationRequest:request
  541. presentingWindow:options.presentingWindow
  542. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  543. NSError *_Nullable error) {
  544. [self processAuthorizationResponse:authorizationResponse
  545. error:error
  546. emmSupport:emmSupport];
  547. }];
  548. #endif
  549. }
  550. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  551. error:(NSError *)error
  552. emmSupport:(NSString *)emmSupport{
  553. if (_restarting) {
  554. // The auth flow is restarting, so the work here would be performed in the next round.
  555. _restarting = NO;
  556. return;
  557. }
  558. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  559. authFlow.emmSupport = emmSupport;
  560. if (authorizationResponse) {
  561. if (authorizationResponse.authorizationCode.length) {
  562. authFlow.authState = [[OIDAuthState alloc]
  563. initWithAuthorizationResponse:authorizationResponse];
  564. // perform auth code exchange
  565. [self maybeFetchToken:authFlow fallback:nil];
  566. } else {
  567. // There was a failure, convert to appropriate error code.
  568. NSString *errorString;
  569. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  570. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  571. #if TARGET_OS_IOS
  572. if (authFlow.emmSupport) {
  573. [authFlow wait];
  574. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  575. handleErrorFromResponse:params
  576. completion:^{
  577. [authFlow next];
  578. }];
  579. if (isEMMError) {
  580. errorCode = kGIDSignInErrorCodeEMM;
  581. }
  582. }
  583. #endif
  584. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  585. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  586. errorCode = kGIDSignInErrorCodeCanceled;
  587. }
  588. authFlow.error = [self errorWithString:errorString code:errorCode];
  589. }
  590. } else {
  591. NSString *errorString = [error localizedDescription];
  592. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  593. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  594. // The user has canceled the flow at the iOS modal dialog.
  595. errorString = kUserCanceledError;
  596. errorCode = kGIDSignInErrorCodeCanceled;
  597. }
  598. authFlow.error = [self errorWithString:errorString code:errorCode];
  599. }
  600. [self addDecodeIdTokenCallback:authFlow];
  601. [self addSaveAuthCallback:authFlow];
  602. [self addCompletionCallback:authFlow];
  603. }
  604. // Perform authentication with the provided options.
  605. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  606. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  607. if (options.interactive) {
  608. [self authenticateInteractivelyWithOptions:options];
  609. return;
  610. }
  611. // Try retrieving an authorization object from the keychain.
  612. OIDAuthState *authState = [self loadAuthState];
  613. if (![authState isAuthorized]) {
  614. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  615. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  616. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  617. userInfo:nil];
  618. if (options.callback) {
  619. _currentOptions = nil;
  620. dispatch_async(dispatch_get_main_queue(), ^{
  621. options.callback(nil, error);
  622. });
  623. }
  624. return;
  625. }
  626. // Complete the auth flow using saved auth in keychain.
  627. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  628. authFlow.authState = authState;
  629. [self maybeFetchToken:authFlow fallback:options.interactive ? ^() {
  630. [self authenticateInteractivelyWithOptions:options];
  631. } : nil];
  632. [self addDecodeIdTokenCallback:authFlow];
  633. [self addSaveAuthCallback:authFlow];
  634. [self addCompletionCallback:authFlow];
  635. }
  636. // Fetches the access token if necessary as part of the auth flow. If |fallback|
  637. // is provided, call it instead of continuing the auth flow in case of error.
  638. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow fallback:(nullable void (^)(void))fallback {
  639. OIDAuthState *authState = authFlow.authState;
  640. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  641. if (authFlow.error ||
  642. (authState.lastTokenResponse.accessToken &&
  643. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  644. kMinimumRestoredAccessTokenTimeToExpire)) {
  645. return;
  646. }
  647. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  648. if (_currentOptions.configuration.serverClientID) {
  649. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  650. }
  651. if (_currentOptions.configuration.openIDRealm) {
  652. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  653. }
  654. #if TARGET_OS_IOS
  655. NSDictionary<NSString *, NSObject *> *params =
  656. authState.lastAuthorizationResponse.additionalParameters;
  657. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  658. [additionalParameters addEntriesFromDictionary:
  659. [GIDAuthentication parametersWithParameters:@{}
  660. emmSupport:authFlow.emmSupport
  661. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  662. #endif
  663. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  664. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  665. OIDTokenRequest *tokenRequest;
  666. if (!authState.lastTokenResponse.accessToken &&
  667. authState.lastAuthorizationResponse.authorizationCode) {
  668. tokenRequest = [authState.lastAuthorizationResponse
  669. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  670. } else {
  671. [additionalParameters
  672. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  673. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  674. }
  675. [authFlow wait];
  676. [OIDAuthorizationService
  677. performTokenRequest:tokenRequest
  678. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  679. NSError *_Nullable error) {
  680. [authState updateWithTokenResponse:tokenResponse error:error];
  681. authFlow.error = error;
  682. if (!tokenResponse.accessToken || error) {
  683. if (fallback) {
  684. [authFlow reset];
  685. fallback();
  686. return;
  687. }
  688. }
  689. #if TARGET_OS_IOS
  690. if (authFlow.emmSupport) {
  691. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *error) {
  692. authFlow.error = error;
  693. [authFlow next];
  694. }];
  695. } else {
  696. [authFlow next];
  697. }
  698. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  699. [authFlow next];
  700. #endif
  701. }];
  702. }
  703. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  704. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  705. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  706. [authFlow addCallback:^() {
  707. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  708. OIDAuthState *authState = handlerAuthFlow.authState;
  709. if (authState && !handlerAuthFlow.error) {
  710. if (![self saveAuthState:authState]) {
  711. handlerAuthFlow.error = [self errorWithString:kKeychainError
  712. code:kGIDSignInErrorCodeKeychain];
  713. return;
  714. }
  715. if (self->_currentOptions.addScopesFlow) {
  716. [self->_currentUser updateAuthState:authState
  717. profileData:handlerAuthFlow.profileData];
  718. } else {
  719. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  720. profileData:handlerAuthFlow.profileData];
  721. [self setCurrentUserWithKVO:user];
  722. }
  723. }
  724. }];
  725. }
  726. // Adds a callback to the auth flow to extract user data from the ID token where available and
  727. // make a userinfo request if necessary.
  728. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  729. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  730. [authFlow addCallback:^() {
  731. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  732. OIDAuthState *authState = handlerAuthFlow.authState;
  733. if (!authState || handlerAuthFlow.error) {
  734. return;
  735. }
  736. OIDIDToken *idToken =
  737. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  738. // If the profile data are present in the ID token, use them.
  739. if (idToken) {
  740. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  741. }
  742. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  743. if (!handlerAuthFlow.profileData) {
  744. [handlerAuthFlow wait];
  745. NSURL *infoURL = [NSURL URLWithString:
  746. [NSString stringWithFormat:kUserInfoURLTemplate,
  747. [GIDSignInPreferences googleUserInfoServer],
  748. authState.lastTokenResponse.accessToken]];
  749. [self startFetchURL:infoURL
  750. fromAuthState:authState
  751. withComment:@"GIDSignIn: fetch basic profile info"
  752. withCompletionHandler:^(NSData *data, NSError *error) {
  753. if (data && !error) {
  754. NSError *jsonDeserializationError;
  755. NSDictionary<NSString *, NSString *> *profileDict =
  756. [NSJSONSerialization JSONObjectWithData:data
  757. options:NSJSONReadingMutableContainers
  758. error:&jsonDeserializationError];
  759. if (profileDict) {
  760. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  761. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  762. name:profileDict[kBasicProfileNameKey]
  763. givenName:profileDict[kBasicProfileGivenNameKey]
  764. familyName:profileDict[kBasicProfileFamilyNameKey]
  765. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  766. }
  767. }
  768. if (error) {
  769. handlerAuthFlow.error = error;
  770. }
  771. [handlerAuthFlow next];
  772. }];
  773. }
  774. }];
  775. }
  776. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  777. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  778. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  779. [authFlow addCallback:^() {
  780. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  781. if (self->_currentOptions.callback) {
  782. GIDSignInCallback callback = self->_currentOptions.callback;
  783. self->_currentOptions = nil;
  784. dispatch_async(dispatch_get_main_queue(), ^{
  785. callback(self->_currentUser, handlerAuthFlow.error);
  786. });
  787. }
  788. }];
  789. }
  790. - (void)startFetchURL:(NSURL *)URL
  791. fromAuthState:(OIDAuthState *)authState
  792. withComment:(NSString *)comment
  793. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  794. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  795. GTMSessionFetcher *fetcher;
  796. GTMAppAuthFetcherAuthorization *authorization =
  797. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  798. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  799. if (fetcherService) {
  800. fetcher = [fetcherService fetcherWithRequest:request];
  801. } else {
  802. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  803. }
  804. fetcher.retryEnabled = YES;
  805. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  806. fetcher.comment = comment;
  807. [fetcher beginFetchWithCompletionHandler:handler];
  808. }
  809. // Parse incoming URL from the Google Device Policy app.
  810. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  811. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  812. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  813. NSObject<NSCopying> *actionParam = params[@"action"];
  814. NSString *actionString =
  815. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  816. if (![@"restart_auth" isEqualToString:actionString]) {
  817. return NO;
  818. }
  819. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  820. if (!_currentOptions.presentingViewController) {
  821. return NO;
  822. }
  823. #elif TARGET_OS_OSX
  824. if (!_currentOptions.presentingWindow) {
  825. return NO;
  826. }
  827. #endif
  828. if (!_currentAuthorizationFlow) {
  829. return NO;
  830. }
  831. _restarting = YES;
  832. [_currentAuthorizationFlow cancel];
  833. _currentAuthorizationFlow = nil;
  834. _restarting = NO;
  835. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  836. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  837. // so we need to wait until the previous presentation is completely gone to ensure the right
  838. // anchor window is used here.
  839. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  840. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  841. dispatch_get_main_queue(), ^{
  842. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  843. forContinuation:YES]];
  844. });
  845. return YES;
  846. }
  847. #pragma mark - Key-Value Observing
  848. // Override |NSObject(NSKeyValueObservingCustomization)| method in order to provide custom KVO
  849. // notifications for the |currentUser| property.
  850. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  851. if ([key isEqual:NSStringFromSelector(@selector(currentUser))]) {
  852. return NO;
  853. }
  854. return [super automaticallyNotifiesObserversForKey:key];
  855. }
  856. #pragma mark - Helpers
  857. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  858. if (errorString == nil) {
  859. errorString = @"Unknown error";
  860. }
  861. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  862. return [NSError errorWithDomain:kGIDSignInErrorDomain
  863. code:code
  864. userInfo:errorDict];
  865. }
  866. + (BOOL)isOperatingSystemAtLeast9 {
  867. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  868. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  869. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  870. }
  871. // Asserts the parameters being valid.
  872. - (void)assertValidParameters {
  873. if (![_currentOptions.configuration.clientID length]) {
  874. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  875. [NSException raise:NSInvalidArgumentException
  876. format:@"You must specify |clientID| in |GIDConfiguration|"];
  877. }
  878. }
  879. // Assert that the presenting view controller has been set.
  880. - (void)assertValidPresentingViewController {
  881. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  882. if (!_currentOptions.presentingViewController) {
  883. #elif TARGET_OS_OSX
  884. if (!_currentOptions.presentingWindow) {
  885. #endif
  886. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  887. [NSException raise:NSInvalidArgumentException
  888. format:@"|presentingViewController| must be set."];
  889. }
  890. }
  891. // Checks whether or not this is the first time the app runs.
  892. - (BOOL)isFreshInstall {
  893. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  894. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  895. return NO;
  896. }
  897. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  898. return YES;
  899. }
  900. - (void)removeAllKeychainEntries {
  901. [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:kGTMAppAuthKeychainName
  902. useDataProtectionKeychain:YES];
  903. }
  904. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  905. GTMAppAuthFetcherAuthorization *authorization =
  906. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  907. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  908. toKeychainForName:kGTMAppAuthKeychainName
  909. useDataProtectionKeychain:YES];
  910. }
  911. - (OIDAuthState *)loadAuthState {
  912. GTMAppAuthFetcherAuthorization *authorization =
  913. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName
  914. useDataProtectionKeychain:YES];
  915. return authorization.authState;
  916. }
  917. // Generates user profile from OIDIDToken.
  918. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  919. if (!idToken ||
  920. !idToken.claims[kBasicProfilePictureKey] ||
  921. !idToken.claims[kBasicProfileNameKey] ||
  922. !idToken.claims[kBasicProfileGivenNameKey] ||
  923. !idToken.claims[kBasicProfileFamilyNameKey]) {
  924. return nil;
  925. }
  926. return [[GIDProfileData alloc]
  927. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  928. name:idToken.claims[kBasicProfileNameKey]
  929. givenName:idToken.claims[kBasicProfileGivenNameKey]
  930. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  931. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  932. }
  933. // Set currentUser making appropriate KVO calls.
  934. - (void)setCurrentUserWithKVO:(GIDGoogleUser *_Nullable)user {
  935. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  936. _currentUser = user;
  937. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  938. }
  939. @end
  940. NS_ASSUME_NONNULL_END