GIDSignIn.m 51 KB

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