GIDSignIn.m 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. [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. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  425. if (@available(iOS 14.0, *)) {
  426. GIDAppCheck *appCheck = [GIDAppCheck appCheckUsingAppAttestProvider];
  427. sharedInstance = [[self alloc] initWithKeychainStore:keychainStore
  428. appCheck:appCheck];
  429. }
  430. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  431. if (!sharedInstance) {
  432. sharedInstance = [[self alloc] initWithKeychainStore:keychainStore];
  433. }
  434. });
  435. return sharedInstance;
  436. }
  437. #pragma mark - Configuring and pre-warming
  438. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  439. - (void)configureWithCompletion:(nullable void (^)(NSError * _Nullable))completion {
  440. @synchronized(self) {
  441. _configureAppCheckCalled = YES;
  442. [_appCheck prepareForAppCheckWithCompletion:^(NSError * _Nullable error) {
  443. if (completion) {
  444. completion(error);
  445. }
  446. }];
  447. }
  448. }
  449. - (void)configureDebugProviderWithAPIKey:(NSString *)APIKey
  450. completion:(nullable void (^)(NSError * _Nullable))completion {
  451. @synchronized(self) {
  452. _appCheck = [GIDAppCheck appCheckUsingDebugProviderWithAPIKey:APIKey];
  453. [_appCheck prepareForAppCheckWithCompletion:^(NSError * _Nullable error) {
  454. if (completion) {
  455. completion(error);
  456. }
  457. }];
  458. }
  459. }
  460. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  461. #pragma mark - Private methods
  462. - (instancetype)initWithKeychainStore:(GTMKeychainStore *)keychainStore {
  463. self = [super init];
  464. if (self) {
  465. // Get the bundle of the current executable.
  466. NSBundle *bundle = NSBundle.mainBundle;
  467. // If we have a bundle, try to set the active configuration from the bundle's Info.plist.
  468. if (bundle) {
  469. _configuration = [GIDSignIn configurationFromBundle:bundle];
  470. }
  471. // Check to see if the 3P app is being run for the first time after a fresh install.
  472. BOOL isFreshInstall = [self isFreshInstall];
  473. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  474. if (isFreshInstall) {
  475. [self removeAllKeychainEntries];
  476. }
  477. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  478. [GIDSignInPreferences googleAuthorizationServer]];
  479. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  480. [GIDSignInPreferences googleTokenServer]];
  481. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  482. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  483. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  484. _keychainStore = keychainStore;
  485. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  486. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  487. GIDAuthStateMigration *migration =
  488. [[GIDAuthStateMigration alloc] initWithKeychainStore:_keychainStore];
  489. [migration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  490. callbackPath:kBrowserCallbackPath
  491. keychainName:kGTMAppAuthKeychainName
  492. isFreshInstall:isFreshInstall];
  493. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  494. }
  495. return self;
  496. }
  497. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  498. - (instancetype)initWithKeychainStore:(GTMKeychainStore *)keychainStore
  499. appCheck:(GIDAppCheck *)appCheck {
  500. self = [self initWithKeychainStore:keychainStore];
  501. if (self) {
  502. _appCheck = appCheck;
  503. _configureAppCheckCalled = NO;
  504. }
  505. return self;
  506. }
  507. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  508. // Does sanity check for parameters and then authenticates if necessary.
  509. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  510. // Options for continuation are not the options we want to cache. The purpose of caching the
  511. // options in the first place is to provide continuation flows with a starting place from which to
  512. // derive suitable options for the continuation!
  513. if (!options.continuation) {
  514. _currentOptions = options;
  515. }
  516. if (options.interactive) {
  517. // Ensure that a configuration has been provided.
  518. if (!_configuration) {
  519. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  520. [NSException raise:NSInvalidArgumentException
  521. format:@"No active configuration. Make sure GIDClientID is set in Info.plist."];
  522. return;
  523. }
  524. // Explicitly throw exception for missing client ID here. This must come before
  525. // scheme check because schemes rely on reverse client IDs.
  526. [self assertValidParameters];
  527. [self assertValidPresentingViewController];
  528. // If the application does not support the required URL schemes tell the developer so.
  529. GIDSignInCallbackSchemes *schemes =
  530. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  531. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  532. if (unsupportedSchemes.count != 0) {
  533. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  534. [NSException raise:NSInvalidArgumentException
  535. format:@"Your app is missing support for the following URL schemes: %@",
  536. [unsupportedSchemes componentsJoinedByString:@", "]];
  537. }
  538. }
  539. // If this is a non-interactive flow, use cached authentication if possible.
  540. if (!options.interactive && _currentUser) {
  541. [_currentUser refreshTokensIfNeededWithCompletion:^(GIDGoogleUser *unused, NSError *error) {
  542. if (error) {
  543. [self authenticateWithOptions:options];
  544. } else {
  545. if (options.completion) {
  546. self->_currentOptions = nil;
  547. dispatch_async(dispatch_get_main_queue(), ^{
  548. GIDSignInResult *signInResult =
  549. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser serverAuthCode:nil];
  550. options.completion(signInResult, nil);
  551. });
  552. }
  553. }
  554. }];
  555. } else {
  556. [self authenticateWithOptions:options];
  557. }
  558. }
  559. #pragma mark - Authentication flow
  560. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  561. NSString *emmSupport;
  562. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  563. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  564. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  565. emmSupport = nil;
  566. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  567. [self authorizationRequestWithOptions:options
  568. completion:^(OIDAuthorizationRequest * _Nullable request,
  569. NSError * _Nullable error) {
  570. self->_currentAuthorizationFlow =
  571. [OIDAuthorizationService presentAuthorizationRequest:request
  572. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  573. presentingViewController:options.presentingViewController
  574. #elif TARGET_OS_OSX
  575. presentingWindow:options.presentingWindow
  576. #endif // TARGET_OS_OSX
  577. callback:
  578. ^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  579. NSError *_Nullable error) {
  580. [self processAuthorizationResponse:authorizationResponse
  581. error:error
  582. emmSupport:emmSupport];
  583. }];
  584. }];
  585. }
  586. - (void)authorizationRequestWithOptions:(GIDSignInInternalOptions *)options completion:
  587. (void (^)(OIDAuthorizationRequest *_Nullable request, NSError *_Nullable error))completion {
  588. BOOL shouldCreateAuthRequest = YES;
  589. NSMutableDictionary<NSString *, NSString *> *additionalParameters =
  590. [self additionalParametersFromOptions:options];
  591. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  592. if (@available(iOS 14.0, *)) {
  593. // Only use `_appCheck` (created via singleton `+[GIDSignIn sharedInstance]` call) if
  594. // `GIDAppCheck` has been successfully prepared OR if the developer has attempted to configure.
  595. // If former is false and the latter true, then preparation step failed for some reason; we
  596. // still want to try to pass along the app check token (it just may take longer since the
  597. // pre-warm step failed).
  598. if ([_appCheck isPrepared] || _configureAppCheckCalled) {
  599. shouldCreateAuthRequest = NO;
  600. UIViewController *presentingVC = options.presentingViewController;
  601. if (!_timedLoader) {
  602. _timedLoader = [[GIDTimedLoader alloc] initWithPresentingViewController:presentingVC];
  603. }
  604. [_timedLoader startTiming];
  605. [self->_appCheck getLimitedUseTokenWithCompletion:^(GACAppCheckToken * _Nullable token,
  606. NSError * _Nullable error) {
  607. if (token) {
  608. additionalParameters[kClientAssertionTypeParameter] = kClientAssertionTypeParameterValue;
  609. additionalParameters[kClientAssertionParameter] = token.token;
  610. }
  611. #if DEBUG
  612. if (error) {
  613. NSLog(@"[Google Sign-In iOS]: Error retrieving App Check limited use token: %@", error);
  614. }
  615. #endif
  616. OIDAuthorizationRequest *request = [self authorizationRequestWithOptions:options
  617. additionalParameters:additionalParameters];
  618. if (self->_timedLoader.animationStatus == GIDTimedLoaderAnimationStatusAnimating) {
  619. [self->_timedLoader stopTimingWithCompletion:^{
  620. completion(request, error);
  621. }];
  622. } else {
  623. completion(request, error);
  624. }
  625. }];
  626. }
  627. }
  628. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  629. if (shouldCreateAuthRequest) {
  630. OIDAuthorizationRequest *request = [self authorizationRequestWithOptions:options
  631. additionalParameters:additionalParameters];
  632. completion(request, nil);
  633. }
  634. }
  635. - (OIDAuthorizationRequest *)
  636. authorizationRequestWithOptions:(GIDSignInInternalOptions *)options
  637. additionalParameters:(NSDictionary<NSString *, NSString *> *)additionalParameters {
  638. OIDAuthorizationRequest *request;
  639. if (options.nonce) {
  640. request = [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  641. clientId:options.configuration.clientID
  642. scopes:options.scopes
  643. redirectURL:[self redirectURLWithOptions:options]
  644. responseType:OIDResponseTypeCode
  645. nonce:options.nonce
  646. additionalParameters:additionalParameters];
  647. } else {
  648. request = [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  649. clientId:options.configuration.clientID
  650. scopes:options.scopes
  651. redirectURL:[self redirectURLWithOptions:options]
  652. responseType:OIDResponseTypeCode
  653. additionalParameters:additionalParameters];
  654. }
  655. return request;
  656. }
  657. - (NSMutableDictionary<NSString *, NSString *> *)
  658. additionalParametersFromOptions:(GIDSignInInternalOptions *)options {
  659. NSString *emmSupport;
  660. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  661. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  662. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  663. emmSupport = nil;
  664. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  665. NSMutableDictionary<NSString *, NSString *> *additionalParameters =
  666. [[NSMutableDictionary alloc] init];
  667. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  668. if (options.configuration.serverClientID) {
  669. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  670. }
  671. if (options.loginHint) {
  672. additionalParameters[kLoginHintParameter] = options.loginHint;
  673. }
  674. if (options.configuration.hostedDomain) {
  675. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  676. }
  677. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  678. [additionalParameters addEntriesFromDictionary:
  679. [GIDEMMSupport parametersWithParameters:options.extraParams
  680. emmSupport:emmSupport
  681. isPasscodeInfoRequired:NO]];
  682. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  683. [additionalParameters addEntriesFromDictionary:options.extraParams];
  684. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  685. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  686. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  687. return additionalParameters;
  688. }
  689. - (NSURL *)redirectURLWithOptions:(GIDSignInInternalOptions *)options {
  690. GIDSignInCallbackSchemes *schemes =
  691. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  692. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  693. [schemes clientIdentifierScheme],
  694. kBrowserCallbackPath]];
  695. return redirectURL;
  696. }
  697. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  698. error:(NSError *)error
  699. emmSupport:(NSString *)emmSupport {
  700. if (_restarting) {
  701. // The auth flow is restarting, so the work here would be performed in the next round.
  702. _restarting = NO;
  703. return;
  704. }
  705. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  706. authFlow.emmSupport = emmSupport;
  707. if (authorizationResponse) {
  708. if (authorizationResponse.authorizationCode.length) {
  709. authFlow.authState = [[OIDAuthState alloc]
  710. initWithAuthorizationResponse:authorizationResponse];
  711. // perform auth code exchange
  712. [self maybeFetchToken:authFlow];
  713. } else {
  714. // There was a failure, convert to appropriate error code.
  715. NSString *errorString;
  716. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  717. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  718. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  719. if (authFlow.emmSupport) {
  720. [authFlow wait];
  721. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  722. handleErrorFromResponse:params
  723. completion:^{
  724. [authFlow next];
  725. }];
  726. if (isEMMError) {
  727. errorCode = kGIDSignInErrorCodeEMM;
  728. }
  729. }
  730. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  731. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  732. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  733. errorCode = kGIDSignInErrorCodeCanceled;
  734. }
  735. authFlow.error = [self errorWithString:errorString code:errorCode];
  736. }
  737. } else {
  738. NSString *errorString = [error localizedDescription];
  739. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  740. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow ||
  741. error.code == OIDErrorCodeProgramCanceledAuthorizationFlow) {
  742. // The user has canceled the flow at the iOS modal dialog.
  743. errorString = kUserCanceledError;
  744. errorCode = kGIDSignInErrorCodeCanceled;
  745. }
  746. authFlow.error = [self errorWithString:errorString code:errorCode];
  747. }
  748. [self addDecodeIdTokenCallback:authFlow];
  749. [self addSaveAuthCallback:authFlow];
  750. [self addCompletionCallback:authFlow];
  751. }
  752. // Perform authentication with the provided options.
  753. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  754. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  755. if (options.interactive) {
  756. [self authenticateInteractivelyWithOptions:options];
  757. return;
  758. }
  759. // Try retrieving an authorization object from the keychain.
  760. OIDAuthState *authState = [self loadAuthState];
  761. if (![authState isAuthorized]) {
  762. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  763. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  764. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  765. userInfo:nil];
  766. if (options.completion) {
  767. _currentOptions = nil;
  768. dispatch_async(dispatch_get_main_queue(), ^{
  769. options.completion(nil, error);
  770. });
  771. }
  772. return;
  773. }
  774. // Complete the auth flow using saved auth in keychain.
  775. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  776. authFlow.authState = authState;
  777. [self maybeFetchToken:authFlow];
  778. [self addDecodeIdTokenCallback:authFlow];
  779. [self addSaveAuthCallback:authFlow];
  780. [self addCompletionCallback:authFlow];
  781. }
  782. // Fetches the access token if necessary as part of the auth flow.
  783. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow {
  784. OIDAuthState *authState = authFlow.authState;
  785. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  786. if (authFlow.error ||
  787. (authState.lastTokenResponse.accessToken &&
  788. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  789. kMinimumRestoredAccessTokenTimeToExpire)) {
  790. return;
  791. }
  792. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  793. if (_currentOptions.configuration.serverClientID) {
  794. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  795. }
  796. if (_currentOptions.configuration.openIDRealm) {
  797. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  798. }
  799. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  800. NSDictionary<NSString *, NSObject *> *params =
  801. authState.lastAuthorizationResponse.additionalParameters;
  802. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  803. [additionalParameters addEntriesFromDictionary:
  804. [GIDEMMSupport parametersWithParameters:@{}
  805. emmSupport:authFlow.emmSupport
  806. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  807. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  808. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  809. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  810. OIDTokenRequest *tokenRequest;
  811. if (!authState.lastTokenResponse.accessToken &&
  812. authState.lastAuthorizationResponse.authorizationCode) {
  813. tokenRequest = [authState.lastAuthorizationResponse
  814. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  815. } else {
  816. [additionalParameters
  817. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  818. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  819. }
  820. [authFlow wait];
  821. [OIDAuthorizationService performTokenRequest:tokenRequest
  822. originalAuthorizationResponse:authFlow.authState.lastAuthorizationResponse
  823. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  824. NSError *_Nullable error) {
  825. [authState updateWithTokenResponse:tokenResponse error:error];
  826. authFlow.error = error;
  827. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  828. if (authFlow.emmSupport) {
  829. [GIDEMMSupport handleTokenFetchEMMError:error completion:^(NSError *error) {
  830. authFlow.error = error;
  831. [authFlow next];
  832. }];
  833. } else {
  834. [authFlow next];
  835. }
  836. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  837. [authFlow next];
  838. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  839. }];
  840. }
  841. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  842. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  843. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  844. [authFlow addCallback:^() {
  845. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  846. OIDAuthState *authState = handlerAuthFlow.authState;
  847. if (authState && !handlerAuthFlow.error) {
  848. if (![self saveAuthState:authState]) {
  849. handlerAuthFlow.error = [self errorWithString:kKeychainError
  850. code:kGIDSignInErrorCodeKeychain];
  851. return;
  852. }
  853. if (self->_currentOptions.addScopesFlow) {
  854. [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  855. authorizationResponse:authState.lastAuthorizationResponse
  856. profileData:handlerAuthFlow.profileData];
  857. } else {
  858. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  859. profileData:handlerAuthFlow.profileData];
  860. self.currentUser = user;
  861. }
  862. }
  863. }];
  864. }
  865. // Adds a callback to the auth flow to extract user data from the ID token where available and
  866. // make a userinfo request if necessary.
  867. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  868. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  869. [authFlow addCallback:^() {
  870. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  871. OIDAuthState *authState = handlerAuthFlow.authState;
  872. if (!authState || handlerAuthFlow.error) {
  873. return;
  874. }
  875. OIDIDToken *idToken =
  876. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  877. // If the profile data are present in the ID token, use them.
  878. if (idToken) {
  879. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  880. }
  881. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  882. if (!handlerAuthFlow.profileData) {
  883. [handlerAuthFlow wait];
  884. NSURL *infoURL = [NSURL URLWithString:
  885. [NSString stringWithFormat:kUserInfoURLTemplate,
  886. [GIDSignInPreferences googleUserInfoServer],
  887. authState.lastTokenResponse.accessToken]];
  888. [self startFetchURL:infoURL
  889. fromAuthState:authState
  890. withComment:@"GIDSignIn: fetch basic profile info"
  891. withCompletionHandler:^(NSData *data, NSError *error) {
  892. if (data && !error) {
  893. NSError *jsonDeserializationError;
  894. NSDictionary<NSString *, NSString *> *profileDict =
  895. [NSJSONSerialization JSONObjectWithData:data
  896. options:NSJSONReadingMutableContainers
  897. error:&jsonDeserializationError];
  898. if (profileDict) {
  899. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  900. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  901. name:profileDict[kBasicProfileNameKey]
  902. givenName:profileDict[kBasicProfileGivenNameKey]
  903. familyName:profileDict[kBasicProfileFamilyNameKey]
  904. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  905. }
  906. }
  907. if (error) {
  908. handlerAuthFlow.error = error;
  909. }
  910. [handlerAuthFlow next];
  911. }];
  912. }
  913. }];
  914. }
  915. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  916. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  917. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  918. [authFlow addCallback:^() {
  919. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  920. if (self->_currentOptions.completion) {
  921. GIDSignInCompletion completion = self->_currentOptions.completion;
  922. self->_currentOptions = nil;
  923. dispatch_async(dispatch_get_main_queue(), ^{
  924. if (handlerAuthFlow.error) {
  925. completion(nil, handlerAuthFlow.error);
  926. } else {
  927. OIDAuthState *authState = handlerAuthFlow.authState;
  928. NSString *_Nullable serverAuthCode =
  929. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  930. GIDSignInResult *signInResult =
  931. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser
  932. serverAuthCode:serverAuthCode];
  933. completion(signInResult, nil);
  934. }
  935. });
  936. }
  937. }];
  938. }
  939. - (void)startFetchURL:(NSURL *)URL
  940. fromAuthState:(OIDAuthState *)authState
  941. withComment:(NSString *)comment
  942. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  943. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  944. GTMSessionFetcher *fetcher;
  945. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  946. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  947. if (fetcherService) {
  948. fetcher = [fetcherService fetcherWithRequest:request];
  949. } else {
  950. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  951. }
  952. fetcher.retryEnabled = YES;
  953. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  954. fetcher.comment = comment;
  955. [fetcher beginFetchWithCompletionHandler:handler];
  956. }
  957. // Parse incoming URL from the Google Device Policy app.
  958. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  959. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  960. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  961. NSObject<NSCopying> *actionParam = params[@"action"];
  962. NSString *actionString =
  963. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  964. if (![@"restart_auth" isEqualToString:actionString]) {
  965. return NO;
  966. }
  967. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  968. if (!_currentOptions.presentingViewController) {
  969. return NO;
  970. }
  971. #elif TARGET_OS_OSX
  972. if (!_currentOptions.presentingWindow) {
  973. return NO;
  974. }
  975. #endif // TARGET_OS_OSX
  976. if (!_currentAuthorizationFlow) {
  977. return NO;
  978. }
  979. _restarting = YES;
  980. [_currentAuthorizationFlow cancel];
  981. _currentAuthorizationFlow = nil;
  982. _restarting = NO;
  983. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  984. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  985. // so we need to wait until the previous presentation is completely gone to ensure the right
  986. // anchor window is used here.
  987. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  988. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  989. dispatch_get_main_queue(), ^{
  990. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  991. forContinuation:YES]];
  992. });
  993. return YES;
  994. }
  995. #pragma mark - Helpers
  996. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  997. if (errorString == nil) {
  998. errorString = @"Unknown error";
  999. }
  1000. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  1001. return [NSError errorWithDomain:kGIDSignInErrorDomain
  1002. code:code
  1003. userInfo:errorDict];
  1004. }
  1005. + (BOOL)isOperatingSystemAtLeast9 {
  1006. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  1007. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  1008. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  1009. }
  1010. // Asserts the parameters being valid.
  1011. - (void)assertValidParameters {
  1012. if (![_currentOptions.configuration.clientID length]) {
  1013. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  1014. [NSException raise:NSInvalidArgumentException
  1015. format:@"You must specify |clientID| in |GIDConfiguration|"];
  1016. }
  1017. }
  1018. // Assert that the presenting view controller has been set.
  1019. - (void)assertValidPresentingViewController {
  1020. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1021. if (!_currentOptions.presentingViewController)
  1022. #elif TARGET_OS_OSX
  1023. if (!_currentOptions.presentingWindow)
  1024. #endif // TARGET_OS_OSX
  1025. {
  1026. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  1027. [NSException raise:NSInvalidArgumentException
  1028. format:@"|presentingViewController| must be set."];
  1029. }
  1030. }
  1031. // Checks whether or not this is the first time the app runs.
  1032. - (BOOL)isFreshInstall {
  1033. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  1034. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  1035. return NO;
  1036. }
  1037. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  1038. return YES;
  1039. }
  1040. - (void)removeAllKeychainEntries {
  1041. [_keychainStore removeAuthSessionWithError:nil];
  1042. }
  1043. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  1044. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  1045. NSError *error;
  1046. [_keychainStore saveAuthSession:authorization error:&error];
  1047. return error == nil;
  1048. }
  1049. - (OIDAuthState *)loadAuthState {
  1050. GTMAuthSession *authorization = [_keychainStore retrieveAuthSessionWithError:nil];
  1051. return authorization.authState;
  1052. }
  1053. // Generates user profile from OIDIDToken.
  1054. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  1055. if (!idToken ||
  1056. !idToken.claims[kBasicProfilePictureKey] ||
  1057. !idToken.claims[kBasicProfileNameKey] ||
  1058. !idToken.claims[kBasicProfileGivenNameKey] ||
  1059. !idToken.claims[kBasicProfileFamilyNameKey]) {
  1060. return nil;
  1061. }
  1062. return [[GIDProfileData alloc]
  1063. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  1064. name:idToken.claims[kBasicProfileNameKey]
  1065. givenName:idToken.claims[kBasicProfileGivenNameKey]
  1066. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  1067. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  1068. }
  1069. // Try to retrieve a configuration value from an |NSBundle|'s Info.plist for a given key.
  1070. + (nullable NSString *)configValueFromBundle:(NSBundle *)bundle forKey:(NSString *)key {
  1071. NSString *value;
  1072. id configValue = [bundle objectForInfoDictionaryKey:key];
  1073. if ([configValue isKindOfClass:[NSString class]]) {
  1074. value = configValue;
  1075. }
  1076. return value;
  1077. }
  1078. // Try to generate a |GIDConfiguration| from an |NSBundle|'s Info.plist.
  1079. + (nullable GIDConfiguration *)configurationFromBundle:(NSBundle *)bundle {
  1080. GIDConfiguration *configuration;
  1081. // Retrieve any valid config parameters from the bundle's Info.plist.
  1082. NSString *clientID = [GIDSignIn configValueFromBundle:bundle forKey:kConfigClientIDKey];
  1083. NSString *serverClientID = [GIDSignIn configValueFromBundle:bundle
  1084. forKey:kConfigServerClientIDKey];
  1085. NSString *hostedDomain = [GIDSignIn configValueFromBundle:bundle forKey:kConfigHostedDomainKey];
  1086. NSString *openIDRealm = [GIDSignIn configValueFromBundle:bundle forKey:kConfigOpenIDRealmKey];
  1087. // If we have at least a client ID, try to construct a configuration.
  1088. if (clientID) {
  1089. configuration = [[GIDConfiguration alloc] initWithClientID:clientID
  1090. serverClientID:serverClientID
  1091. hostedDomain:hostedDomain
  1092. openIDRealm:openIDRealm];
  1093. }
  1094. return configuration;
  1095. }
  1096. @end
  1097. NS_ASSUME_NONNULL_END