GIDSignIn.m 49 KB

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