GIDSignIn.m 43 KB

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