GIDUserAuthFlowController.m 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. #import "GoogleSignIn/Sources/GIDUserAuthFlowController.h"
  2. #ifdef SWIFT_PACKAGE
  3. @import AppAuth;
  4. #else
  5. #import <AppAuth/AppAuth.h>
  6. #endif
  7. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  8. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  9. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  10. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  11. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  12. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDUserAuth.h"
  13. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  14. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  15. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  16. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  17. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  18. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  19. #import "GoogleSignIn/Sources/GIDUserAuth_Private.h"
  20. // The URL template for the URL to get user info.
  21. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  22. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  23. // Expected path in the URL scheme to be handled.
  24. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  25. // Expected path for EMM callback.
  26. static NSString *const kEMMCallbackPath = @"/emmcallback";
  27. // The EMM support version
  28. static NSString *const kEMMVersion = @"1";
  29. // Basic profile (Fat ID Token / userinfo endpoint) keys
  30. static NSString *const kBasicProfileEmailKey = @"email";
  31. static NSString *const kBasicProfilePictureKey = @"picture";
  32. static NSString *const kBasicProfileNameKey = @"name";
  33. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  34. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  35. // Parameters for the auth and token exchange endpoints.
  36. static NSString *const kAudienceParameter = @"audience";
  37. // See b/11669751 .
  38. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  39. static NSString *const kIncludeGrantedScopesParameter = @"include_granted_scopes";
  40. static NSString *const kLoginHintParameter = @"login_hint";
  41. static NSString *const kHostedDomainParameter = @"hd";
  42. // Error string for unavailable keychain.
  43. static NSString *const kKeychainError = @"keychain error";
  44. // Maximum retry interval in seconds for the fetcher.
  45. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  46. // Minimum time to expiration for a restored access token.
  47. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  48. // The callback queue used for authentication flow.
  49. @interface GIDAuthFlow_TEMP : GIDCallbackQueue
  50. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  51. @property(nonatomic, strong, nullable) NSError *error;
  52. @property(nonatomic, copy, nullable) NSString *emmSupport;
  53. @property(nonatomic, nullable) GIDProfileData *profileData;
  54. @end
  55. @implementation GIDAuthFlow_TEMP
  56. @end
  57. // Keychain constants for saving state in the authentication flow.
  58. static NSString *const kGTMAppAuthKeychainName = @"auth";
  59. @implementation GIDUserAuthFlowResult
  60. - (instancetype)initWithAuthState:(OIDAuthState *)authState
  61. profileData:(GIDProfileData *)profileData
  62. serverAuthCode:(nullable NSString *)serverAuthCode{
  63. self = [super init];
  64. if (self) {
  65. _authState = authState;
  66. _profileData = profileData;
  67. _serverAuthCode = [serverAuthCode copy];
  68. }
  69. return self;
  70. };
  71. @end
  72. @implementation GIDUserAuthFlowController {
  73. // represent a sign in continuation.
  74. GIDSignInInternalOptions *_currentOptions;
  75. // AppAuth external user-agent session state.
  76. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  77. // Flag to indicate that the auth flow is restarting.
  78. BOOL _restarting;
  79. }
  80. #pragma mark - Public methods
  81. - (BOOL)handleURL:(NSURL *)url {
  82. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  83. if ([url.path isEqual:kBrowserCallbackPath]) {
  84. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  85. _currentAuthorizationFlow = nil;
  86. return YES;
  87. }
  88. return NO;
  89. }
  90. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  91. if ([url.path isEqual:kEMMCallbackPath]) {
  92. return [self handleDevicePolicyAppURL:url];
  93. }
  94. return NO;
  95. }
  96. - (void)signInWithOptions:(GIDSignInInternalOptions *)options
  97. completion:(GIDUserAuthFlowCompletion)completion {
  98. // Options for continuation are not the options we want to cache. The purpose of caching the
  99. // options in the first place is to provide continuation flows with a starting place from which to
  100. // derive suitable options for the continuation!
  101. if (!options.continuation) {
  102. _currentOptions = options;
  103. }
  104. [self authenticateWithOptions:options completion:completion];
  105. }
  106. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options
  107. completion:(GIDUserAuthFlowCompletion)completion {
  108. //If this is an interactive flow, we're not going to try to restore any saved auth state.
  109. if (options.interactive) {
  110. [self authenticateInteractivelyWithOptions:options
  111. completion:completion];
  112. return;
  113. }
  114. // Try retrieving an authorization object from the keychain.
  115. OIDAuthState *authState = [self loadAuthState];
  116. if (![authState isAuthorized]) {
  117. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  118. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  119. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  120. userInfo:nil];
  121. if (options.completion) {
  122. _currentOptions = nil;
  123. dispatch_async(dispatch_get_main_queue(), ^{
  124. options.completion(nil, error);
  125. });
  126. }
  127. return;
  128. }
  129. // Complete the auth flow using saved auth in keychain.
  130. GIDAuthFlow_TEMP *authFlow = [[GIDAuthFlow_TEMP alloc] init];
  131. authFlow.authState = authState;
  132. [self maybeFetchToken:authFlow];
  133. [self addDecodeIdTokenCallback:authFlow];
  134. [self addSaveAuthCallback:authFlow];
  135. [self addCompletionCallback:authFlow completion:completion];
  136. }
  137. // Fetches the access token if necessary as part of the auth flow.
  138. - (void)maybeFetchToken:(GIDAuthFlow_TEMP *)authFlow {
  139. OIDAuthState *authState = authFlow.authState;
  140. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  141. if (authFlow.error ||
  142. (authState.lastTokenResponse.accessToken &&
  143. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  144. kMinimumRestoredAccessTokenTimeToExpire)) {
  145. return;
  146. }
  147. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  148. if (_currentOptions.configuration.serverClientID) {
  149. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  150. }
  151. if (_currentOptions.configuration.openIDRealm) {
  152. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  153. }
  154. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  155. NSDictionary<NSString *, NSObject *> *params =
  156. authState.lastAuthorizationResponse.additionalParameters;
  157. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  158. [additionalParameters addEntriesFromDictionary:
  159. [GIDEMMSupport parametersWithParameters:@{}
  160. emmSupport:authFlow.emmSupport
  161. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  162. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  163. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  164. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  165. OIDTokenRequest *tokenRequest;
  166. if (!authState.lastTokenResponse.accessToken &&
  167. authState.lastAuthorizationResponse.authorizationCode) {
  168. tokenRequest = [authState.lastAuthorizationResponse
  169. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  170. } else {
  171. [additionalParameters
  172. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  173. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  174. }
  175. [authFlow wait];
  176. [OIDAuthorizationService
  177. performTokenRequest:tokenRequest
  178. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  179. NSError *_Nullable error) {
  180. [authState updateWithTokenResponse:tokenResponse error:error];
  181. authFlow.error = error;
  182. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  183. if (authFlow.emmSupport) {
  184. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *error) {
  185. authFlow.error = error;
  186. [authFlow next];
  187. }];
  188. } else {
  189. [authFlow next];
  190. }
  191. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  192. [authFlow next];
  193. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  194. }];
  195. }
  196. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options
  197. completion:(GIDUserAuthFlowCompletion)completion{
  198. GIDSignInCallbackSchemes *schemes =
  199. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  200. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  201. [schemes clientIdentifierScheme],
  202. kBrowserCallbackPath]];
  203. NSString *emmSupport;
  204. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  205. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  206. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  207. emmSupport = nil;
  208. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  209. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  210. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  211. if (options.configuration.serverClientID) {
  212. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  213. }
  214. if (options.loginHint) {
  215. additionalParameters[kLoginHintParameter] = options.loginHint;
  216. }
  217. if (options.configuration.hostedDomain) {
  218. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  219. }
  220. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  221. [additionalParameters addEntriesFromDictionary:
  222. [GIDEMMSupport parametersWithParameters:options.extraParams
  223. emmSupport:emmSupport
  224. isPasscodeInfoRequired:NO]];
  225. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  226. [additionalParameters addEntriesFromDictionary:options.extraParams];
  227. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  228. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  229. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  230. OIDServiceConfiguration *appAuthConfiguration = [GIDSignInPreferences appAuthConfiguration];
  231. OIDAuthorizationRequest *request =
  232. [[OIDAuthorizationRequest alloc] initWithConfiguration:appAuthConfiguration
  233. clientId:options.configuration.clientID
  234. scopes:options.scopes
  235. redirectURL:redirectURL
  236. responseType:OIDResponseTypeCode
  237. additionalParameters:additionalParameters];
  238. _currentAuthorizationFlow = [OIDAuthorizationService
  239. presentAuthorizationRequest:request
  240. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  241. presentingViewController:options.presentingViewController
  242. #elif TARGET_OS_OSX
  243. presentingWindow:options.presentingWindow
  244. #endif // TARGET_OS_OSX
  245. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  246. NSError *_Nullable error) {
  247. [self processAuthorizationResponse:authorizationResponse
  248. error:error
  249. emmSupport:emmSupport
  250. completion:completion];
  251. }];
  252. }
  253. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  254. error:(NSError *)error
  255. emmSupport:(NSString *)emmSupport
  256. completion:(GIDUserAuthFlowCompletion)completion {
  257. if (_restarting) {
  258. // The auth flow is restarting, so the work here would be performed in the next round.
  259. _restarting = NO;
  260. return;
  261. }
  262. GIDAuthFlow_TEMP *authFlow = [[GIDAuthFlow_TEMP alloc] init];
  263. authFlow.emmSupport = emmSupport;
  264. if (authorizationResponse) {
  265. if (authorizationResponse.authorizationCode.length) {
  266. authFlow.authState = [[OIDAuthState alloc]
  267. initWithAuthorizationResponse:authorizationResponse];
  268. // perform auth code exchange
  269. [self maybeFetchToken:authFlow];
  270. } else {
  271. // There was a failure, convert to appropriate error code.
  272. NSString *errorString;
  273. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  274. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  275. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  276. if (authFlow.emmSupport) {
  277. [authFlow wait];
  278. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  279. handleErrorFromResponse:params
  280. completion:^{
  281. [authFlow next];
  282. }];
  283. if (isEMMError) {
  284. errorCode = kGIDSignInErrorCodeEMM;
  285. }
  286. }
  287. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  288. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  289. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  290. errorCode = kGIDSignInErrorCodeCanceled;
  291. }
  292. authFlow.error = [self errorWithString:errorString code:errorCode];
  293. }
  294. } else {
  295. NSString *errorString = [error localizedDescription];
  296. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  297. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  298. // The user has canceled the flow at the iOS modal dialog.
  299. errorString = kUserCanceledError;
  300. errorCode = kGIDSignInErrorCodeCanceled;
  301. }
  302. authFlow.error = [self errorWithString:errorString code:errorCode];
  303. }
  304. [self addDecodeIdTokenCallback:authFlow];
  305. [self addSaveAuthCallback:authFlow];
  306. [self addCompletionCallback:authFlow
  307. completion:completion];
  308. }
  309. // Adds a callback to the auth flow to extract user data from the ID token where available and
  310. // make a userinfo request if necessary.
  311. - (void)addDecodeIdTokenCallback:(GIDAuthFlow_TEMP *)authFlow {
  312. __weak GIDAuthFlow_TEMP *weakAuthFlow = authFlow;
  313. [authFlow addCallback:^() {
  314. GIDAuthFlow_TEMP *handlerAuthFlow = weakAuthFlow;
  315. OIDAuthState *authState = handlerAuthFlow.authState;
  316. if (!authState || handlerAuthFlow.error) {
  317. return;
  318. }
  319. OIDIDToken *idToken =
  320. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  321. // If the profile data are present in the ID token, use them.
  322. if (idToken) {
  323. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  324. }
  325. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  326. if (!handlerAuthFlow.profileData) {
  327. [handlerAuthFlow wait];
  328. NSURL *infoURL = [NSURL URLWithString:
  329. [NSString stringWithFormat:kUserInfoURLTemplate,
  330. [GIDSignInPreferences googleUserInfoServer],
  331. authState.lastTokenResponse.accessToken]];
  332. [self startFetchURL:infoURL
  333. fromAuthState:authState
  334. withComment:@"GIDSignIn: fetch basic profile info"
  335. withCompletionHandler:^(NSData *data, NSError *error) {
  336. if (data && !error) {
  337. NSError *jsonDeserializationError;
  338. NSDictionary<NSString *, NSString *> *profileDict =
  339. [NSJSONSerialization JSONObjectWithData:data
  340. options:NSJSONReadingMutableContainers
  341. error:&jsonDeserializationError];
  342. if (profileDict) {
  343. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  344. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  345. name:profileDict[kBasicProfileNameKey]
  346. givenName:profileDict[kBasicProfileGivenNameKey]
  347. familyName:profileDict[kBasicProfileFamilyNameKey]
  348. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  349. }
  350. }
  351. if (error) {
  352. handlerAuthFlow.error = error;
  353. }
  354. [handlerAuthFlow next];
  355. }];
  356. }
  357. }];
  358. }
  359. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  360. - (void)addSaveAuthCallback:(GIDAuthFlow_TEMP *)authFlow {
  361. __weak GIDAuthFlow_TEMP *weakAuthFlow = authFlow;
  362. [authFlow addCallback:^() {
  363. GIDAuthFlow_TEMP *handlerAuthFlow = weakAuthFlow;
  364. OIDAuthState *authState = handlerAuthFlow.authState;
  365. if (authState && !handlerAuthFlow.error) {
  366. if (![self saveAuthState:authState]) {
  367. handlerAuthFlow.error = [self errorWithString:kKeychainError
  368. code:kGIDSignInErrorCodeKeychain];
  369. }
  370. // if (self->_currentOptions.addScopesFlow) {
  371. // [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  372. // authorizationResponse:authState.lastAuthorizationResponse
  373. // profileData:handlerAuthFlow.profileData];
  374. // } else {
  375. // GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  376. // profileData:handlerAuthFlow.profileData];
  377. // self.currentUser = user;
  378. // }
  379. }
  380. }];
  381. }
  382. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  383. - (void)addCompletionCallback:(GIDAuthFlow_TEMP *)authFlow
  384. completion:(GIDUserAuthFlowCompletion)completion {
  385. __weak GIDAuthFlow_TEMP *weakAuthFlow = authFlow;
  386. [authFlow addCallback:^() {
  387. GIDAuthFlow_TEMP *handlerAuthFlow = weakAuthFlow;
  388. if (completion) {
  389. dispatch_async(dispatch_get_main_queue(), ^{
  390. if (handlerAuthFlow.error) {
  391. completion(nil, handlerAuthFlow.error);
  392. } else {
  393. OIDAuthState *authState = handlerAuthFlow.authState;
  394. GIDProfileData *profileData = handlerAuthFlow.profileData;
  395. NSString *_Nullable serverAuthCode =
  396. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  397. GIDUserAuthFlowResult *authFlowResult =
  398. [[GIDUserAuthFlowResult alloc] initWithAuthState:authState
  399. profileData:profileData
  400. serverAuthCode:serverAuthCode];
  401. completion(authFlowResult, nil);
  402. }
  403. });
  404. }
  405. }];
  406. }
  407. - (void)startFetchURL:(NSURL *)URL
  408. fromAuthState:(OIDAuthState *)authState
  409. withComment:(NSString *)comment
  410. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  411. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  412. GTMSessionFetcher *fetcher;
  413. GTMAppAuthFetcherAuthorization *authorization =
  414. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  415. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  416. if (fetcherService) {
  417. fetcher = [fetcherService fetcherWithRequest:request];
  418. } else {
  419. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  420. }
  421. fetcher.retryEnabled = YES;
  422. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  423. fetcher.comment = comment;
  424. [fetcher beginFetchWithCompletionHandler:handler];
  425. }
  426. // Parse incoming URL from the Google Device Policy app.
  427. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  428. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  429. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  430. NSObject<NSCopying> *actionParam = params[@"action"];
  431. NSString *actionString =
  432. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  433. if (![@"restart_auth" isEqualToString:actionString]) {
  434. return NO;
  435. }
  436. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  437. if (!_currentOptions.presentingViewController) {
  438. return NO;
  439. }
  440. #elif TARGET_OS_OSX
  441. if (!_currentOptions.presentingWindow) {
  442. return NO;
  443. }
  444. #endif // TARGET_OS_OSX
  445. if (!_currentAuthorizationFlow) {
  446. return NO;
  447. }
  448. _restarting = YES;
  449. [_currentAuthorizationFlow cancel];
  450. _currentAuthorizationFlow = nil;
  451. _restarting = NO;
  452. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  453. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  454. // so we need to wait until the previous presentation is completely gone to ensure the right
  455. // anchor window is used here.
  456. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  457. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  458. dispatch_get_main_queue(), ^{
  459. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  460. forContinuation:YES]];
  461. });
  462. return YES;
  463. }
  464. # pragma mark - Helpers
  465. + (BOOL)isOperatingSystemAtLeast9 {
  466. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  467. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  468. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  469. }
  470. // Asserts the parameters being valid.
  471. - (void)assertValidParameters {
  472. if (![_currentOptions.configuration.clientID length]) {
  473. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  474. [NSException raise:NSInvalidArgumentException
  475. format:@"You must specify |clientID| in |GIDConfiguration|"];
  476. }
  477. }
  478. // Assert that the presenting view controller has been set.
  479. - (void)assertValidPresentingViewController {
  480. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  481. if (!_currentOptions.presentingViewController)
  482. #elif TARGET_OS_OSX
  483. if (!_currentOptions.presentingWindow)
  484. #endif // TARGET_OS_OSX
  485. {
  486. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  487. [NSException raise:NSInvalidArgumentException
  488. format:@"|presentingViewController| must be set."];
  489. }
  490. }
  491. - (OIDAuthState *)loadAuthState {
  492. GTMAppAuthFetcherAuthorization *authorization =
  493. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName
  494. useDataProtectionKeychain:YES];
  495. return authorization.authState;
  496. }
  497. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  498. GTMAppAuthFetcherAuthorization *authorization =
  499. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  500. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  501. toKeychainForName:kGTMAppAuthKeychainName
  502. useDataProtectionKeychain:YES];
  503. }
  504. // Generates user profile from OIDIDToken.
  505. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  506. if (!idToken ||
  507. !idToken.claims[kBasicProfilePictureKey] ||
  508. !idToken.claims[kBasicProfileNameKey] ||
  509. !idToken.claims[kBasicProfileGivenNameKey] ||
  510. !idToken.claims[kBasicProfileFamilyNameKey]) {
  511. return nil;
  512. }
  513. return [[GIDProfileData alloc]
  514. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  515. name:idToken.claims[kBasicProfileNameKey]
  516. givenName:idToken.claims[kBasicProfileGivenNameKey]
  517. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  518. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  519. }
  520. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  521. if (errorString == nil) {
  522. errorString = @"Unknown error";
  523. }
  524. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  525. return [NSError errorWithDomain:kGIDSignInErrorDomain
  526. code:code
  527. userInfo:errorDict];
  528. }
  529. @end