GIDSignIn.m 51 KB

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