GIDSignIn.m 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  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/Public/GoogleSignIn/GIDVerifiableAccountDetail.h"
  21. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDVerifyAccountDetail.h"
  22. #import "GoogleSignIn/Sources/GIDAuthorizationResponse/GIDAuthorizationResponseHelper.h"
  23. #import "GoogleSignIn/Sources/GIDAuthorizationResponse/Implementations/GIDAuthorizationResponseHandler.h"
  24. #import "GoogleSignIn/Sources/GIDAuthFlow.h"
  25. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  26. #import "GoogleSignIn/Sources/GIDRestrictedScopesRegistry.h"
  27. #import "GoogleSignIn/Sources/GIDSignInConstants.h"
  28. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  29. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  30. #import "GoogleSignIn/Sources/GIDScopes.h"
  31. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  32. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  33. #import <AppCheckCore/GACAppCheckToken.h>
  34. #import "GoogleSignIn/Sources/GIDAppCheck/Implementations/GIDAppCheck.h"
  35. #import "GoogleSignIn/Sources/GIDAppCheck/UI/GIDActivityIndicatorViewController.h"
  36. #import "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  37. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  38. #import "GoogleSignIn/Sources/GIDTimedLoader/GIDTimedLoader.h"
  39. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  40. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  41. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  42. #import "GoogleSignIn/Sources/GIDSignInResult_Private.h"
  43. @import GTMAppAuth;
  44. #ifdef SWIFT_PACKAGE
  45. @import AppAuth;
  46. @import GTMSessionFetcherCore;
  47. #else
  48. #import <AppAuth/OIDAuthState.h>
  49. #import <AppAuth/OIDAuthorizationRequest.h>
  50. #import <AppAuth/OIDAuthorizationResponse.h>
  51. #import <AppAuth/OIDAuthorizationService.h>
  52. #import <AppAuth/OIDError.h>
  53. #import <AppAuth/OIDExternalUserAgentSession.h>
  54. #import <AppAuth/OIDIDToken.h>
  55. #import <AppAuth/OIDResponseTypes.h>
  56. #import <AppAuth/OIDServiceConfiguration.h>
  57. #import <AppAuth/OIDURLQueryComponent.h>
  58. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  59. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  60. #import <AppAuth/OIDAuthorizationService+IOS.h>
  61. #elif TARGET_OS_OSX
  62. #import <AppAuth/OIDAuthorizationService+Mac.h>
  63. #endif
  64. #endif
  65. NS_ASSUME_NONNULL_BEGIN
  66. // The name of the query parameter used for logging the restart of auth from EMM callback.
  67. static NSString *const kEMMRestartAuthParameter = @"emmres";
  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 for EMM callback.
  73. static NSString *const kEMMCallbackPath = @"/emmcallback";
  74. // The EMM support version
  75. static NSString *const kEMMVersion = @"1";
  76. // The error code for Google Identity.
  77. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  78. // Keychain constants for saving state in the authentication flow.
  79. static NSString *const kGTMAppAuthKeychainName = @"auth";
  80. // Basic profile (Fat ID Token / userinfo endpoint) keys
  81. static NSString *const kBasicProfileEmailKey = @"email";
  82. static NSString *const kBasicProfilePictureKey = @"picture";
  83. static NSString *const kBasicProfileNameKey = @"name";
  84. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  85. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  86. // Parameters in the callback URL coming back from browser.
  87. static NSString *const kAuthorizationCodeKeyName = @"code";
  88. // Error string for unavailable keychain.
  89. static NSString *const kKeychainError = @"keychain error";
  90. // User preference key to detect fresh install of the app.
  91. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  92. // Maximum retry interval in seconds for the fetcher.
  93. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  94. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  95. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  96. // Parameters for auth and token exchange endpoints using App Attest.
  97. static NSString *const kClientAssertionParameter = @"client_assertion";
  98. static NSString *const kClientAssertionTypeParameter = @"client_assertion_type";
  99. static NSString *const kClientAssertionTypeParameterValue =
  100. @"urn:ietf:params:oauth:client-assertion-type:appcheck";
  101. @implementation GIDSignIn {
  102. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  103. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  104. // represent a sign in continuation.
  105. GIDSignInInternalOptions *_currentOptions;
  106. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  107. GIDAppCheck *_appCheck API_AVAILABLE(ios(14));
  108. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  109. // AppAuth configuration object.
  110. OIDServiceConfiguration *_appAuthConfiguration;
  111. // AppAuth external user-agent session state.
  112. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  113. // Flag to indicate that the auth flow is restarting.
  114. BOOL _restarting;
  115. // Keychain manager for GTMAppAuth
  116. GTMKeychainStore *_keychainStore;
  117. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  118. // The class used to manage presenting the loading screen for fetching app check tokens.
  119. GIDTimedLoader *_timedLoader;
  120. // Flag indicating developer's intent to use App Check.
  121. BOOL _configureAppCheckCalled;
  122. // The class used to manage restricted scopes and their associated handling classes.
  123. GIDRestrictedScopesRegistry *_registry;
  124. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  125. }
  126. #pragma mark - Public methods
  127. // Handles the custom scheme URL opened by SFSafariViewController or the Device Policy App.
  128. //
  129. // For SFSafariViewController invoked via AppAuth, this method is used on iOS 10.
  130. // For the Device Policy App (EMM flow) this method is used on all iOS versions.
  131. - (BOOL)handleURL:(NSURL *)url {
  132. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  133. if ([url.path isEqual:kBrowserCallbackPath]) {
  134. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  135. _currentAuthorizationFlow = nil;
  136. return YES;
  137. }
  138. return NO;
  139. }
  140. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  141. if ([url.path isEqual:kEMMCallbackPath]) {
  142. return [self handleDevicePolicyAppURL:url];
  143. }
  144. return NO;
  145. }
  146. - (BOOL)hasPreviousSignIn {
  147. if ([_currentUser.authState isAuthorized]) {
  148. return YES;
  149. }
  150. OIDAuthState *authState = [self loadAuthState];
  151. return [authState isAuthorized];
  152. }
  153. - (void)restorePreviousSignInWithCompletion:(nullable void (^)(GIDGoogleUser *_Nullable user,
  154. NSError *_Nullable error))completion {
  155. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCompletion:
  156. ^(GIDSignInResult *signInResult, NSError *error) {
  157. if (!completion) {
  158. return;
  159. }
  160. if (signInResult) {
  161. completion(signInResult.user, nil);
  162. } else {
  163. completion(nil, error);
  164. }
  165. }]];
  166. }
  167. - (BOOL)restorePreviousSignInNoRefresh {
  168. if (_currentUser) {
  169. return YES;
  170. }
  171. // Try retrieving an authorization object from the keychain.
  172. OIDAuthState *authState = [self loadAuthState];
  173. if (!authState) {
  174. return NO;
  175. }
  176. // Restore current user without refreshing the access token.
  177. OIDIDToken *idToken =
  178. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  179. GIDProfileData *profileData = [self profileDataWithIDToken:idToken];
  180. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  181. self.currentUser = user;
  182. return YES;
  183. }
  184. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  185. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  186. hint:(nullable NSString *)hint
  187. completion:(nullable GIDSignInCompletion)completion {
  188. GIDSignInInternalOptions *options =
  189. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  190. presentingViewController:presentingViewController
  191. loginHint:hint
  192. addScopesFlow:NO
  193. completion:completion];
  194. [self signInWithOptions:options];
  195. }
  196. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  197. hint:(nullable NSString *)hint
  198. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  199. completion:(nullable GIDSignInCompletion)completion {
  200. [self signInWithPresentingViewController:presentingViewController
  201. hint:hint
  202. additionalScopes:additionalScopes
  203. nonce:nil
  204. completion:completion];
  205. }
  206. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  207. hint:(nullable NSString *)hint
  208. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  209. nonce:(nullable NSString *)nonce
  210. completion:(nullable GIDSignInCompletion)completion {
  211. GIDSignInInternalOptions *options =
  212. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  213. presentingViewController:presentingViewController
  214. loginHint:hint
  215. addScopesFlow:NO
  216. scopes:additionalScopes
  217. nonce:nonce
  218. completion:completion];
  219. [self signInWithOptions:options];
  220. }
  221. - (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
  222. completion:(nullable GIDSignInCompletion)completion {
  223. [self signInWithPresentingViewController:presentingViewController
  224. hint:nil
  225. completion:completion];
  226. }
  227. - (void)addScopes:(NSArray<NSString *> *)scopes
  228. presentingViewController:(UIViewController *)presentingViewController
  229. completion:(nullable GIDSignInCompletion)completion {
  230. GIDConfiguration *configuration = self.currentUser.configuration;
  231. GIDSignInInternalOptions *options =
  232. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  233. presentingViewController:presentingViewController
  234. loginHint:self.currentUser.profile.email
  235. addScopesFlow:YES
  236. completion:completion];
  237. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  238. // Explicitly throw an exception for invalid or restricted scopes in the request.
  239. [self assertValidScopes:scopes];
  240. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  241. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  242. NSMutableSet<NSString *> *grantedScopes =
  243. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  244. // Check to see if all requested scopes have already been granted.
  245. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  246. // All requested scopes have already been granted, notify callback of failure.
  247. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  248. code:kGIDSignInErrorCodeScopesAlreadyGranted
  249. userInfo:nil];
  250. if (completion) {
  251. dispatch_async(dispatch_get_main_queue(), ^{
  252. completion(nil, error);
  253. });
  254. }
  255. return;
  256. }
  257. // Previously granted scopes will still be included since we pass `include_granted_scopes=true`.
  258. options.scopes = [requestedScopes allObjects];
  259. [self signInWithOptions:options];
  260. }
  261. #elif TARGET_OS_OSX
  262. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  263. hint:(nullable NSString *)hint
  264. completion:(nullable GIDSignInCompletion)completion {
  265. GIDSignInInternalOptions *options =
  266. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  267. presentingWindow:presentingWindow
  268. loginHint:hint
  269. addScopesFlow:NO
  270. completion:completion];
  271. [self signInWithOptions:options];
  272. }
  273. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  274. completion:(nullable GIDSignInCompletion)completion {
  275. [self signInWithPresentingWindow:presentingWindow
  276. hint:nil
  277. completion:completion];
  278. }
  279. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  280. hint:(nullable NSString *)hint
  281. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  282. completion:(nullable GIDSignInCompletion)completion {
  283. [self signInWithPresentingWindow:presentingWindow
  284. hint:hint
  285. additionalScopes:additionalScopes
  286. nonce:nil
  287. completion:completion];
  288. }
  289. - (void)signInWithPresentingWindow:(NSWindow *)presentingWindow
  290. hint:(nullable NSString *)hint
  291. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  292. nonce:(nullable NSString *)nonce
  293. completion:(nullable GIDSignInCompletion)completion {
  294. GIDSignInInternalOptions *options =
  295. [GIDSignInInternalOptions defaultOptionsWithConfiguration:_configuration
  296. presentingWindow:presentingWindow
  297. loginHint:hint
  298. addScopesFlow:NO
  299. scopes:additionalScopes
  300. nonce:nonce
  301. completion:completion];
  302. [self signInWithOptions:options];
  303. }
  304. - (void)addScopes:(NSArray<NSString *> *)scopes
  305. presentingWindow:(NSWindow *)presentingWindow
  306. completion:(nullable GIDSignInCompletion)completion {
  307. GIDConfiguration *configuration = self.currentUser.configuration;
  308. GIDSignInInternalOptions *options =
  309. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  310. presentingWindow:presentingWindow
  311. loginHint:self.currentUser.profile.email
  312. addScopesFlow:YES
  313. completion:completion];
  314. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  315. NSMutableSet<NSString *> *grantedScopes =
  316. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  317. // Check to see if all requested scopes have already been granted.
  318. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  319. // All requested scopes have already been granted, notify callback of failure.
  320. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  321. code:kGIDSignInErrorCodeScopesAlreadyGranted
  322. userInfo:nil];
  323. if (completion) {
  324. dispatch_async(dispatch_get_main_queue(), ^{
  325. completion(nil, error);
  326. });
  327. }
  328. return;
  329. }
  330. // Use the union of granted and requested scopes.
  331. [grantedScopes unionSet:requestedScopes];
  332. options.scopes = [grantedScopes allObjects];
  333. [self signInWithOptions:options];
  334. }
  335. #endif // TARGET_OS_OSX
  336. - (void)signOut {
  337. // Clear the current user if there is one.
  338. if (_currentUser) {
  339. self.currentUser = nil;
  340. }
  341. // Remove all state from the keychain.
  342. [self removeAllKeychainEntries];
  343. }
  344. - (void)disconnectWithCompletion:(nullable GIDDisconnectCompletion)completion {
  345. OIDAuthState *authState = _currentUser.authState;
  346. if (!authState) {
  347. // Even the user is not signed in right now, we still need to remove any token saved in the
  348. // keychain.
  349. authState = [self loadAuthState];
  350. }
  351. // Either access or refresh token would work, but we won't have access token if the auth is
  352. // retrieved from keychain.
  353. NSString *token = authState.lastTokenResponse.accessToken;
  354. if (!token) {
  355. token = authState.lastTokenResponse.refreshToken;
  356. }
  357. if (!token) {
  358. [self signOut];
  359. // Nothing to do here, consider the operation successful.
  360. if (completion) {
  361. dispatch_async(dispatch_get_main_queue(), ^{
  362. completion(nil);
  363. });
  364. }
  365. return;
  366. }
  367. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  368. [GIDSignInPreferences googleAuthorizationServer], token];
  369. // Append logging parameter
  370. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@&%@=%@",
  371. revokeURLString,
  372. kSDKVersionLoggingParameter,
  373. GIDVersion(),
  374. kEnvironmentLoggingParameter,
  375. GIDEnvironment()];
  376. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  377. [self startFetchURL:revokeURL
  378. fromAuthState:authState
  379. withComment:@"GIDSignIn: revoke tokens"
  380. withCompletionHandler:^(NSData *data, NSError *error) {
  381. // Revoking an already revoked token seems always successful, which helps us here.
  382. if (!error) {
  383. [self signOut];
  384. }
  385. if (completion) {
  386. dispatch_async(dispatch_get_main_queue(), ^{
  387. completion(error);
  388. });
  389. }
  390. }];
  391. }
  392. #pragma mark - Custom getters and setters
  393. + (GIDSignIn *)sharedInstance {
  394. static dispatch_once_t once;
  395. static GIDSignIn *sharedInstance;
  396. dispatch_once(&once, ^{
  397. GTMKeychainStore *keychainStore =
  398. [[GTMKeychainStore alloc] initWithItemName:kGTMAppAuthKeychainName];
  399. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  400. if (@available(iOS 14.0, *)) {
  401. GIDAppCheck *appCheck = [GIDAppCheck appCheckUsingAppAttestProvider];
  402. sharedInstance = [[self alloc] initWithKeychainStore:keychainStore
  403. appCheck:appCheck];
  404. }
  405. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  406. if (!sharedInstance) {
  407. sharedInstance = [[self alloc] initWithKeychainStore:keychainStore];
  408. }
  409. });
  410. return sharedInstance;
  411. }
  412. #pragma mark - Configuring and pre-warming
  413. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  414. - (void)configureWithCompletion:(nullable void (^)(NSError * _Nullable))completion {
  415. @synchronized(self) {
  416. _configureAppCheckCalled = YES;
  417. [_appCheck prepareForAppCheckWithCompletion:^(NSError * _Nullable error) {
  418. if (completion) {
  419. completion(error);
  420. }
  421. }];
  422. }
  423. }
  424. - (void)configureDebugProviderWithAPIKey:(NSString *)APIKey
  425. completion:(nullable void (^)(NSError * _Nullable))completion {
  426. @synchronized(self) {
  427. _appCheck = [GIDAppCheck appCheckUsingDebugProviderWithAPIKey:APIKey];
  428. [_appCheck prepareForAppCheckWithCompletion:^(NSError * _Nullable error) {
  429. if (completion) {
  430. completion(error);
  431. }
  432. }];
  433. }
  434. }
  435. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  436. #pragma mark - Private methods
  437. - (instancetype)initWithKeychainStore:(GTMKeychainStore *)keychainStore {
  438. self = [super init];
  439. if (self) {
  440. // Get the bundle of the current executable.
  441. NSBundle *bundle = NSBundle.mainBundle;
  442. // If we have a bundle, try to set the active configuration from the bundle's Info.plist.
  443. if (bundle) {
  444. _configuration = [GIDConfiguration configurationFromBundle:bundle];
  445. }
  446. // Check to see if the 3P app is being run for the first time after a fresh install.
  447. BOOL isFreshInstall = [self isFreshInstall];
  448. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  449. if (isFreshInstall) {
  450. [self removeAllKeychainEntries];
  451. }
  452. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  453. [GIDSignInPreferences googleAuthorizationServer]];
  454. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  455. [GIDSignInPreferences googleTokenServer]];
  456. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  457. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  458. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  459. _keychainStore = keychainStore;
  460. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  461. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  462. GIDAuthStateMigration *migration =
  463. [[GIDAuthStateMigration alloc] initWithKeychainStore:_keychainStore];
  464. [migration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  465. callbackPath:kBrowserCallbackPath
  466. keychainName:kGTMAppAuthKeychainName
  467. isFreshInstall:isFreshInstall];
  468. _registry = [[GIDRestrictedScopesRegistry alloc] init];
  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. if (token) {
  584. additionalParameters[kClientAssertionTypeParameter] = kClientAssertionTypeParameterValue;
  585. additionalParameters[kClientAssertionParameter] = token.token;
  586. }
  587. #if DEBUG
  588. if (error) {
  589. NSLog(@"[Google Sign-In iOS]: Error retrieving App Check limited use token: %@", error);
  590. }
  591. #endif
  592. OIDAuthorizationRequest *request = [self authorizationRequestWithOptions:options
  593. additionalParameters:additionalParameters];
  594. if (self->_timedLoader.animationStatus == GIDTimedLoaderAnimationStatusAnimating) {
  595. [self->_timedLoader stopTimingWithCompletion:^{
  596. completion(request, error);
  597. }];
  598. } else {
  599. completion(request, error);
  600. }
  601. }];
  602. }
  603. }
  604. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  605. if (shouldCreateAuthRequest) {
  606. OIDAuthorizationRequest *request = [self authorizationRequestWithOptions:options
  607. additionalParameters:additionalParameters];
  608. completion(request, nil);
  609. }
  610. }
  611. - (OIDAuthorizationRequest *)
  612. authorizationRequestWithOptions:(GIDSignInInternalOptions *)options
  613. additionalParameters:(NSDictionary<NSString *, NSString *> *)additionalParameters {
  614. OIDAuthorizationRequest *request;
  615. if (options.nonce) {
  616. request = [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  617. clientId:options.configuration.clientID
  618. scopes:options.scopes
  619. redirectURL:[self redirectURLWithOptions:options]
  620. responseType:OIDResponseTypeCode
  621. nonce:options.nonce
  622. additionalParameters:additionalParameters];
  623. } else {
  624. request = [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  625. clientId:options.configuration.clientID
  626. scopes:options.scopes
  627. redirectURL:[self redirectURLWithOptions:options]
  628. responseType:OIDResponseTypeCode
  629. additionalParameters:additionalParameters];
  630. }
  631. return request;
  632. }
  633. - (NSMutableDictionary<NSString *, NSString *> *)
  634. additionalParametersFromOptions:(GIDSignInInternalOptions *)options {
  635. NSString *emmSupport;
  636. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  637. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  638. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  639. emmSupport = nil;
  640. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  641. NSMutableDictionary<NSString *, NSString *> *additionalParameters =
  642. [[NSMutableDictionary alloc] init];
  643. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  644. if (options.configuration.serverClientID) {
  645. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  646. }
  647. if (options.loginHint) {
  648. additionalParameters[kLoginHintParameter] = options.loginHint;
  649. }
  650. if (options.configuration.hostedDomain) {
  651. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  652. }
  653. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  654. [additionalParameters addEntriesFromDictionary:
  655. [GIDEMMSupport parametersWithParameters:options.extraParams
  656. emmSupport:emmSupport
  657. isPasscodeInfoRequired:NO]];
  658. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  659. [additionalParameters addEntriesFromDictionary:options.extraParams];
  660. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  661. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  662. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  663. return additionalParameters;
  664. }
  665. - (NSURL *)redirectURLWithOptions:(GIDSignInInternalOptions *)options {
  666. GIDSignInCallbackSchemes *schemes =
  667. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  668. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  669. [schemes clientIdentifierScheme],
  670. kBrowserCallbackPath]];
  671. return redirectURL;
  672. }
  673. - (void)processAuthorizationResponse:(nullable OIDAuthorizationResponse *)authorizationResponse
  674. error:(nullable NSError *)error
  675. emmSupport:(NSString *)emmSupport {
  676. if (_restarting) {
  677. // The auth flow is restarting, so the work here would be performed in the next round.
  678. _restarting = NO;
  679. return;
  680. }
  681. GIDAuthorizationResponseHandler *responseHandler =
  682. [[GIDAuthorizationResponseHandler alloc] initWithAuthorizationResponse:authorizationResponse
  683. emmSupport:emmSupport
  684. flowName:GIDFlowNameSignIn
  685. configuration:
  686. _currentOptions.configuration
  687. error:error];
  688. GIDAuthorizationResponseHelper *responseHelper =
  689. [[GIDAuthorizationResponseHelper alloc] initWithAuthorizationResponseHandler:responseHandler];
  690. GIDAuthFlow *authFlow = [responseHelper fetchAuthFlowFromProcessedResponse];
  691. if (authFlow) {
  692. [self addDecodeIdTokenCallback:authFlow];
  693. [self addSaveAuthCallback:authFlow];
  694. [self addCompletionCallback:authFlow];
  695. }
  696. }
  697. // Perform authentication with the provided options.
  698. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  699. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  700. if (options.interactive) {
  701. [self authenticateInteractivelyWithOptions:options];
  702. return;
  703. }
  704. // Try retrieving an authorization object from the keychain.
  705. OIDAuthState *authState = [self loadAuthState];
  706. if (![authState isAuthorized]) {
  707. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  708. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  709. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  710. userInfo:nil];
  711. if (options.completion) {
  712. _currentOptions = nil;
  713. dispatch_async(dispatch_get_main_queue(), ^{
  714. options.completion(nil, error);
  715. });
  716. }
  717. return;
  718. }
  719. // Complete the auth flow using saved auth in keychain.
  720. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] initWithAuthState:authState
  721. error:nil
  722. emmSupport:nil
  723. profileData:nil];
  724. GIDAuthorizationResponseHandler *responseHandler =
  725. [[GIDAuthorizationResponseHandler alloc] initWithAuthorizationResponse:nil
  726. emmSupport:nil
  727. flowName:GIDFlowNameSignIn
  728. configuration:
  729. _currentOptions.configuration
  730. error:nil];
  731. GIDAuthorizationResponseHelper *responseHelper =
  732. [[GIDAuthorizationResponseHelper alloc] initWithAuthorizationResponseHandler:responseHandler];
  733. [responseHelper fetchTokenWithAuthFlow:authFlow];
  734. [self addDecodeIdTokenCallback:authFlow];
  735. [self addSaveAuthCallback:authFlow];
  736. [self addCompletionCallback:authFlow];
  737. }
  738. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  739. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  740. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  741. [authFlow addCallback:^() {
  742. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  743. OIDAuthState *authState = handlerAuthFlow.authState;
  744. if (authState && !handlerAuthFlow.error) {
  745. if (![self saveAuthState:authState]) {
  746. handlerAuthFlow.error = [self errorWithString:kKeychainError
  747. code:kGIDSignInErrorCodeKeychain];
  748. return;
  749. }
  750. if (self->_currentOptions.addScopesFlow) {
  751. [self->_currentUser updateWithTokenResponse:authState.lastTokenResponse
  752. authorizationResponse:authState.lastAuthorizationResponse
  753. profileData:handlerAuthFlow.profileData];
  754. } else {
  755. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  756. profileData:handlerAuthFlow.profileData];
  757. self.currentUser = user;
  758. }
  759. }
  760. }];
  761. }
  762. // Adds a callback to the auth flow to extract user data from the ID token where available and
  763. // make a userinfo request if necessary.
  764. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  765. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  766. [authFlow addCallback:^() {
  767. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  768. OIDAuthState *authState = handlerAuthFlow.authState;
  769. if (!authState || handlerAuthFlow.error) {
  770. return;
  771. }
  772. OIDIDToken *idToken =
  773. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  774. // If the profile data are present in the ID token, use them.
  775. if (idToken) {
  776. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  777. }
  778. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  779. if (!handlerAuthFlow.profileData) {
  780. [handlerAuthFlow wait];
  781. NSURL *infoURL = [NSURL URLWithString:
  782. [NSString stringWithFormat:kUserInfoURLTemplate,
  783. [GIDSignInPreferences googleUserInfoServer],
  784. authState.lastTokenResponse.accessToken]];
  785. [self startFetchURL:infoURL
  786. fromAuthState:authState
  787. withComment:@"GIDSignIn: fetch basic profile info"
  788. withCompletionHandler:^(NSData *data, NSError *error) {
  789. if (data && !error) {
  790. NSError *jsonDeserializationError;
  791. NSDictionary<NSString *, NSString *> *profileDict =
  792. [NSJSONSerialization JSONObjectWithData:data
  793. options:NSJSONReadingMutableContainers
  794. error:&jsonDeserializationError];
  795. if (profileDict) {
  796. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  797. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  798. name:profileDict[kBasicProfileNameKey]
  799. givenName:profileDict[kBasicProfileGivenNameKey]
  800. familyName:profileDict[kBasicProfileFamilyNameKey]
  801. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  802. }
  803. }
  804. if (error) {
  805. handlerAuthFlow.error = error;
  806. }
  807. [handlerAuthFlow next];
  808. }];
  809. }
  810. }];
  811. }
  812. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  813. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  814. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  815. [authFlow addCallback:^() {
  816. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  817. if (self->_currentOptions.completion) {
  818. GIDSignInCompletion completion = self->_currentOptions.completion;
  819. self->_currentOptions = nil;
  820. dispatch_async(dispatch_get_main_queue(), ^{
  821. if (handlerAuthFlow.error) {
  822. completion(nil, handlerAuthFlow.error);
  823. } else {
  824. OIDAuthState *authState = handlerAuthFlow.authState;
  825. NSString *_Nullable serverAuthCode =
  826. [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  827. GIDSignInResult *signInResult =
  828. [[GIDSignInResult alloc] initWithGoogleUser:self->_currentUser
  829. serverAuthCode:serverAuthCode];
  830. completion(signInResult, nil);
  831. }
  832. });
  833. }
  834. }];
  835. }
  836. - (void)startFetchURL:(NSURL *)URL
  837. fromAuthState:(OIDAuthState *)authState
  838. withComment:(NSString *)comment
  839. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  840. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  841. GTMSessionFetcher *fetcher;
  842. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  843. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  844. if (fetcherService) {
  845. fetcher = [fetcherService fetcherWithRequest:request];
  846. } else {
  847. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  848. }
  849. fetcher.retryEnabled = YES;
  850. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  851. fetcher.comment = comment;
  852. [fetcher beginFetchWithCompletionHandler:handler];
  853. }
  854. // Parse incoming URL from the Google Device Policy app.
  855. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  856. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  857. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  858. NSObject<NSCopying> *actionParam = params[@"action"];
  859. NSString *actionString =
  860. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  861. if (![@"restart_auth" isEqualToString:actionString]) {
  862. return NO;
  863. }
  864. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  865. if (!_currentOptions.presentingViewController) {
  866. return NO;
  867. }
  868. #elif TARGET_OS_OSX
  869. if (!_currentOptions.presentingWindow) {
  870. return NO;
  871. }
  872. #endif // TARGET_OS_OSX
  873. if (!_currentAuthorizationFlow) {
  874. return NO;
  875. }
  876. _restarting = YES;
  877. [_currentAuthorizationFlow cancel];
  878. _currentAuthorizationFlow = nil;
  879. _restarting = NO;
  880. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  881. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  882. // so we need to wait until the previous presentation is completely gone to ensure the right
  883. // anchor window is used here.
  884. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  885. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  886. dispatch_get_main_queue(), ^{
  887. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  888. forContinuation:YES]];
  889. });
  890. return YES;
  891. }
  892. #pragma mark - Helpers
  893. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  894. if (errorString == nil) {
  895. errorString = @"Unknown error";
  896. }
  897. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  898. return [NSError errorWithDomain:kGIDSignInErrorDomain
  899. code:code
  900. userInfo:errorDict];
  901. }
  902. + (BOOL)isOperatingSystemAtLeast9 {
  903. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  904. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  905. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  906. }
  907. // Asserts the parameters being valid.
  908. - (void)assertValidParameters {
  909. if (![_currentOptions.configuration.clientID length]) {
  910. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  911. [NSException raise:NSInvalidArgumentException
  912. format:@"You must specify |clientID| in |GIDConfiguration|"];
  913. }
  914. }
  915. // Assert that the presenting view controller has been set.
  916. - (void)assertValidPresentingViewController {
  917. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  918. if (!_currentOptions.presentingViewController)
  919. #elif TARGET_OS_OSX
  920. if (!_currentOptions.presentingWindow)
  921. #endif // TARGET_OS_OSX
  922. {
  923. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  924. [NSException raise:NSInvalidArgumentException
  925. format:@"|presentingViewController| must be set."];
  926. }
  927. }
  928. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  929. - (void)assertValidScopes:(NSArray<NSString *> *)scopes {
  930. NSDictionary<NSString *, Class> *restrictedScopesMapping =
  931. [_registry restrictedScopesToClassMappingInSet:[NSSet setWithArray:scopes]];
  932. if (restrictedScopesMapping.count > 0) {
  933. NSMutableString *errorMessage =
  934. [NSMutableString stringWithString:@"The following scopes are not supported in the 'addScopes' flow. "
  935. "Please use the appropriate classes to handle these:\n"];
  936. [restrictedScopesMapping enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull restrictedScope,
  937. Class _Nonnull handlingClass,
  938. BOOL * _Nonnull stop) {
  939. [errorMessage appendFormat:@"%@ -> %@\n", restrictedScope, NSStringFromClass(handlingClass)];
  940. }];
  941. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  942. [NSException raise:NSInvalidArgumentException
  943. format:@"%@", errorMessage];
  944. }
  945. }
  946. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  947. // Checks whether or not this is the first time the app runs.
  948. - (BOOL)isFreshInstall {
  949. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  950. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  951. return NO;
  952. }
  953. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  954. return YES;
  955. }
  956. - (void)removeAllKeychainEntries {
  957. [_keychainStore removeAuthSessionWithError:nil];
  958. }
  959. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  960. GTMAuthSession *authorization = [[GTMAuthSession alloc] initWithAuthState:authState];
  961. NSError *error;
  962. [_keychainStore saveAuthSession:authorization error:&error];
  963. return error == nil;
  964. }
  965. - (OIDAuthState *)loadAuthState {
  966. GTMAuthSession *authorization = [_keychainStore retrieveAuthSessionWithError:nil];
  967. return authorization.authState;
  968. }
  969. // Generates user profile from OIDIDToken.
  970. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  971. if (!idToken ||
  972. !idToken.claims[kBasicProfilePictureKey] ||
  973. !idToken.claims[kBasicProfileNameKey] ||
  974. !idToken.claims[kBasicProfileGivenNameKey] ||
  975. !idToken.claims[kBasicProfileFamilyNameKey]) {
  976. return nil;
  977. }
  978. return [[GIDProfileData alloc]
  979. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  980. name:idToken.claims[kBasicProfileNameKey]
  981. givenName:idToken.claims[kBasicProfileGivenNameKey]
  982. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  983. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  984. }
  985. @end
  986. NS_ASSUME_NONNULL_END