GIDSignIn.m 51 KB

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