GIDSignIn.m 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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 <DeviceCheck/DeviceCheck.h>
  16. #include <CommonCrypto/CommonDigest.h>
  17. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  18. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDAuthentication.h"
  19. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  20. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  21. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  22. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  23. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  24. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  25. #import "GoogleSignIn/Sources/GIDScopes.h"
  26. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  27. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  28. #import "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  29. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  30. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  31. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  32. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  33. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  34. #ifdef SWIFT_PACKAGE
  35. @import AppAuth;
  36. @import GTMAppAuth;
  37. @import GTMSessionFetcherCore;
  38. #else
  39. #import <AppAuth/OIDAuthState.h>
  40. #import <AppAuth/OIDAuthorizationRequest.h>
  41. #import <AppAuth/OIDAuthorizationResponse.h>
  42. #import <AppAuth/OIDAuthorizationService.h>
  43. #import <AppAuth/OIDError.h>
  44. #import <AppAuth/OIDExternalUserAgentSession.h>
  45. #import <AppAuth/OIDIDToken.h>
  46. #import <AppAuth/OIDResponseTypes.h>
  47. #import <AppAuth/OIDServiceConfiguration.h>
  48. #import <AppAuth/OIDTokenRequest.h>
  49. #import <AppAuth/OIDTokenResponse.h>
  50. #import <AppAuth/OIDURLQueryComponent.h>
  51. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  52. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  53. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  54. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  55. #import <AppAuth/OIDAuthorizationService+IOS.h>
  56. #elif TARGET_OS_OSX
  57. #import <AppAuth/OIDAuthorizationService+Mac.h>
  58. #endif
  59. #endif
  60. NS_ASSUME_NONNULL_BEGIN
  61. // The name of the query parameter used for logging the restart of auth from EMM callback.
  62. static NSString *const kEMMRestartAuthParameter = @"emmres";
  63. // The URL template for the authorization endpoint.
  64. static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth";
  65. // The URL template for the token endpoint.
  66. static NSString *const kTokenURLTemplate = @"https://%@/token";
  67. // The URL template for the URL to get user info.
  68. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  69. // The URL template for the URL to revoke the token.
  70. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
  71. // Expected path in the URL scheme to be handled.
  72. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  73. // Expected path for EMM callback.
  74. static NSString *const kEMMCallbackPath = @"/emmcallback";
  75. // The EMM support version
  76. static NSString *const kEMMVersion = @"1";
  77. // The error code for Google Identity.
  78. NSErrorDomain const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  79. // Keychain constants for saving state in the authentication flow.
  80. static NSString *const kGTMAppAuthKeychainName = @"auth";
  81. // Basic profile (Fat ID Token / userinfo endpoint) keys
  82. static NSString *const kBasicProfileEmailKey = @"email";
  83. static NSString *const kBasicProfilePictureKey = @"picture";
  84. static NSString *const kBasicProfileNameKey = @"name";
  85. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  86. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  87. // Parameters in the callback URL coming back from browser.
  88. static NSString *const kAuthorizationCodeKeyName = @"code";
  89. static NSString *const kOAuth2ErrorKeyName = @"error";
  90. static NSString *const kOAuth2AccessDenied = @"access_denied";
  91. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  92. // Error string for unavailable keychain.
  93. static NSString *const kKeychainError = @"keychain error";
  94. // Error string for user cancelations.
  95. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  96. // User preference key to detect fresh install of the app.
  97. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  98. // Maximum retry interval in seconds for the fetcher.
  99. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  100. // The delay before the new sign-in flow can be presented after the existing one is cancelled.
  101. static const NSTimeInterval kPresentationDelayAfterCancel = 1.0;
  102. // Parameters for the auth and token exchange endpoints.
  103. static NSString *const kAudienceParameter = @"audience";
  104. // See b/11669751 .
  105. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  106. static NSString *const kIncludeGrantedScopesParameter = @"include_granted_scopes";
  107. static NSString *const kLoginHintParameter = @"login_hint";
  108. static NSString *const kHostedDomainParameter = @"hd";
  109. // Minimum time to expiration for a restored access token.
  110. static const NSTimeInterval kMinimumRestoredAccessTokenTimeToExpire = 600.0;
  111. // The callback queue used for authentication flow.
  112. @interface GIDAuthFlow : GIDCallbackQueue
  113. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  114. @property(nonatomic, strong, nullable) NSError *error;
  115. @property(nonatomic, copy, nullable) NSString *emmSupport;
  116. @property(nonatomic, nullable) GIDProfileData *profileData;
  117. @end
  118. @implementation GIDAuthFlow
  119. @end
  120. @implementation GIDSignIn {
  121. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  122. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  123. // represent a sign in continuation.
  124. GIDSignInInternalOptions *_currentOptions;
  125. // AppAuth configuration object.
  126. OIDServiceConfiguration *_appAuthConfiguration;
  127. // AppAuth external user-agent session state.
  128. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  129. // Flag to indicate that the auth flow is restarting.
  130. BOOL _restarting;
  131. }
  132. #pragma mark - Public methods
  133. - (BOOL)handleURL:(NSURL *)url {
  134. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  135. if ([url.path isEqual:kBrowserCallbackPath]) {
  136. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  137. _currentAuthorizationFlow = nil;
  138. return YES;
  139. }
  140. return NO;
  141. }
  142. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  143. if ([url.path isEqual:kEMMCallbackPath]) {
  144. return [self handleDevicePolicyAppURL:url];
  145. }
  146. return NO;
  147. }
  148. - (BOOL)hasPreviousSignIn {
  149. if ([_currentUser.authentication.authState isAuthorized]) {
  150. return YES;
  151. }
  152. OIDAuthState *authState = [self loadAuthState];
  153. return [authState isAuthorized];
  154. }
  155. - (void)restorePreviousSignInWithCallback:(nullable GIDSignInCallback)callback {
  156. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCallback:callback]];
  157. }
  158. - (BOOL)restorePreviousSignInNoRefresh {
  159. if (_currentUser) {
  160. return YES;
  161. }
  162. // Try retrieving an authorization object from the keychain.
  163. OIDAuthState *authState = [self loadAuthState];
  164. if (!authState) {
  165. return NO;
  166. }
  167. // Restore current user without refreshing the access token.
  168. OIDIDToken *idToken =
  169. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  170. GIDProfileData *profileData = [self profileDataWithIDToken:idToken];
  171. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  172. [self setCurrentUserWithKVO:user];
  173. return YES;
  174. }
  175. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  176. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  177. presentingViewController:(UIViewController *)presentingViewController
  178. hint:(nullable NSString *)hint
  179. callback:(nullable GIDSignInCallback)callback {
  180. GIDSignInInternalOptions *options =
  181. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  182. presentingViewController:presentingViewController
  183. loginHint:hint
  184. addScopesFlow:NO
  185. callback:callback];
  186. [self signInWithOptions:options];
  187. }
  188. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  189. presentingViewController:(UIViewController *)presentingViewController
  190. hint:(nullable NSString *)hint
  191. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  192. callback:(nullable GIDSignInCallback)callback {
  193. GIDSignInInternalOptions *options =
  194. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  195. presentingViewController:presentingViewController
  196. loginHint:hint
  197. addScopesFlow:NO
  198. scopes:additionalScopes
  199. callback:callback];
  200. [self signInWithOptions:options];
  201. }
  202. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  203. presentingViewController:(UIViewController *)presentingViewController
  204. callback:(nullable GIDSignInCallback)callback {
  205. //Generate keyId and attestation object.
  206. if (@available(iOS 14.0, *)) {
  207. DCAppAttestService *attestService = DCAppAttestService.sharedService;
  208. if (attestService.supported) {
  209. // Start generating keyId.
  210. NSDate *start = [NSDate date];
  211. [attestService generateKeyWithCompletionHandler:^(NSString * _Nullable keyId, NSError * _Nullable error) {
  212. if (keyId) {
  213. NSDate *keyIdFinish = [NSDate date];
  214. NSTimeInterval executionTime = [keyIdFinish timeIntervalSinceDate:start];
  215. NSLog(@"keyId generation time = %f seconds", executionTime);
  216. NSLog(@"The length of the key Id string = %lu", [keyId length]);
  217. // Fake the server side challenge.
  218. NSUUID *uuid = [NSUUID UUID];
  219. NSString *randomID = [uuid UUIDString];
  220. NSData* challenge = [randomID dataUsingEncoding:NSUTF8StringEncoding];
  221. NSData* dataHash = [self doSha256:challenge];
  222. // Start generating attestation object.
  223. NSDate *start = [NSDate date];
  224. [attestService attestKey:keyId clientDataHash:dataHash completionHandler:^(NSData * _Nullable attestationObject, NSError * _Nullable error) {
  225. if (attestationObject) {
  226. NSDate *attestationFinish = [NSDate date];
  227. NSTimeInterval executionTime = [attestationFinish timeIntervalSinceDate:start];
  228. NSLog(@"The attestation object creation time = %f seconds", executionTime);
  229. NSString *attestationString = [attestationObject base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  230. NSLog(@"The number of bytes contained in the attestation object(NSData type) = %lu", [attestationObject length]);
  231. NSUInteger length = [attestationString length];
  232. NSLog(@"The length of the attestation string = %lu", length);
  233. // Start generating assertion object.
  234. NSDate *start = [NSDate date];
  235. [attestService generateAssertion:keyId clientDataHash:dataHash completionHandler:^(NSData * _Nullable assertionObject, NSError * _Nullable error) {
  236. if (assertionObject) {
  237. NSDate *assertionFinish = [NSDate date];
  238. NSTimeInterval executionTime = [assertionFinish timeIntervalSinceDate:start];
  239. NSLog(@"The assertion object creation time = %f seconds", executionTime);
  240. NSString *assertionString = [assertionObject base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
  241. NSLog(@"The number of bytes contained in the assertion object(NSData type) = %lu", [assertionObject length]);
  242. NSUInteger length = [assertionString length];
  243. NSLog(@"The length of the assertion string = %lu", length);
  244. [self signInWithConfiguration:configuration
  245. presentingViewController:presentingViewController
  246. hint:nil
  247. callback:callback];
  248. }
  249. }];
  250. }
  251. }];
  252. }
  253. }];
  254. return;
  255. }
  256. }
  257. [self signInWithConfiguration:configuration
  258. presentingViewController:presentingViewController
  259. hint:nil
  260. callback:callback];
  261. }
  262. // Generate SHA256 hash
  263. - (NSData *)doSha256:(NSData *)dataIn {
  264. NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
  265. CC_SHA256(dataIn.bytes, dataIn.length, macOut.mutableBytes);
  266. return macOut;
  267. }
  268. - (void)addScopes:(NSArray<NSString *> *)scopes
  269. presentingViewController:(UIViewController *)presentingViewController
  270. callback:(nullable GIDSignInCallback)callback {
  271. // A currentUser must be available in order to complete this flow.
  272. if (!self.currentUser) {
  273. // No currentUser is set, notify callback of failure.
  274. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  275. code:kGIDSignInErrorCodeNoCurrentUser
  276. userInfo:nil];
  277. if (callback) {
  278. dispatch_async(dispatch_get_main_queue(), ^{
  279. callback(nil, error);
  280. });
  281. }
  282. return;
  283. }
  284. GIDConfiguration *configuration =
  285. [[GIDConfiguration alloc] initWithClientID:self.currentUser.authentication.clientID
  286. serverClientID:self.currentUser.serverClientID
  287. hostedDomain:self.currentUser.hostedDomain
  288. openIDRealm:self.currentUser.openIDRealm];
  289. GIDSignInInternalOptions *options =
  290. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  291. presentingViewController:presentingViewController
  292. loginHint:self.currentUser.profile.email
  293. addScopesFlow:YES
  294. callback:callback];
  295. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  296. NSMutableSet<NSString *> *grantedScopes =
  297. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  298. // Check to see if all requested scopes have already been granted.
  299. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  300. // All requested scopes have already been granted, notify callback of failure.
  301. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  302. code:kGIDSignInErrorCodeScopesAlreadyGranted
  303. userInfo:nil];
  304. if (callback) {
  305. dispatch_async(dispatch_get_main_queue(), ^{
  306. callback(nil, error);
  307. });
  308. }
  309. return;
  310. }
  311. // Use the union of granted and requested scopes.
  312. [grantedScopes unionSet:requestedScopes];
  313. options.scopes = [grantedScopes allObjects];
  314. [self signInWithOptions:options];
  315. }
  316. #elif TARGET_OS_OSX
  317. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  318. presentingWindow:(NSWindow *)presentingWindow
  319. hint:(nullable NSString *)hint
  320. callback:(nullable GIDSignInCallback)callback {
  321. GIDSignInInternalOptions *options =
  322. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  323. presentingWindow:presentingWindow
  324. loginHint:hint
  325. addScopesFlow:NO
  326. callback:callback];
  327. [self signInWithOptions:options];
  328. }
  329. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  330. presentingWindow:(NSWindow *)presentingWindow
  331. callback:(nullable GIDSignInCallback)callback {
  332. [self signInWithConfiguration:configuration
  333. presentingWindow:presentingWindow
  334. hint:nil
  335. callback:callback];
  336. }
  337. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  338. presentingWindow:(NSWindow *)presentingWindow
  339. hint:(nullable NSString *)hint
  340. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  341. callback:(nullable GIDSignInCallback)callback {
  342. GIDSignInInternalOptions *options =
  343. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  344. presentingWindow:presentingWindow
  345. loginHint:hint
  346. addScopesFlow:NO
  347. scopes:additionalScopes
  348. callback:callback];
  349. [self signInWithOptions:options];
  350. }
  351. - (void)addScopes:(NSArray<NSString *> *)scopes
  352. presentingWindow:(NSWindow *)presentingWindow
  353. callback:(nullable GIDSignInCallback)callback {
  354. // A currentUser must be available in order to complete this flow.
  355. if (!self.currentUser) {
  356. // No currentUser is set, notify callback of failure.
  357. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  358. code:kGIDSignInErrorCodeNoCurrentUser
  359. userInfo:nil];
  360. if (callback) {
  361. dispatch_async(dispatch_get_main_queue(), ^{
  362. callback(nil, error);
  363. });
  364. }
  365. return;
  366. }
  367. GIDConfiguration *configuration =
  368. [[GIDConfiguration alloc] initWithClientID:self.currentUser.authentication.clientID
  369. serverClientID:self.currentUser.serverClientID
  370. hostedDomain:self.currentUser.hostedDomain
  371. openIDRealm:self.currentUser.openIDRealm];
  372. GIDSignInInternalOptions *options =
  373. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  374. presentingWindow:presentingWindow
  375. loginHint:self.currentUser.profile.email
  376. addScopesFlow:YES
  377. callback:callback];
  378. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  379. NSMutableSet<NSString *> *grantedScopes =
  380. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  381. // Check to see if all requested scopes have already been granted.
  382. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  383. // All requested scopes have already been granted, notify callback of failure.
  384. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  385. code:kGIDSignInErrorCodeScopesAlreadyGranted
  386. userInfo:nil];
  387. if (callback) {
  388. dispatch_async(dispatch_get_main_queue(), ^{
  389. callback(nil, error);
  390. });
  391. }
  392. return;
  393. }
  394. // Use the union of granted and requested scopes.
  395. [grantedScopes unionSet:requestedScopes];
  396. options.scopes = [grantedScopes allObjects];
  397. [self signInWithOptions:options];
  398. }
  399. #endif // TARGET_OS_OSX
  400. - (void)signOut {
  401. // Clear the current user if there is one.
  402. if (_currentUser) {
  403. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  404. _currentUser = nil;
  405. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  406. }
  407. // Remove all state from the keychain.
  408. [self removeAllKeychainEntries];
  409. }
  410. - (void)disconnectWithCallback:(nullable GIDDisconnectCallback)callback {
  411. GIDGoogleUser *user = _currentUser;
  412. OIDAuthState *authState = user.authentication.authState;
  413. if (!authState) {
  414. // Even the user is not signed in right now, we still need to remove any token saved in the
  415. // keychain.
  416. authState = [self loadAuthState];
  417. }
  418. // Either access or refresh token would work, but we won't have access token if the auth is
  419. // retrieved from keychain.
  420. NSString *token = authState.lastTokenResponse.accessToken;
  421. if (!token) {
  422. token = authState.lastTokenResponse.refreshToken;
  423. }
  424. if (!token) {
  425. [self signOut];
  426. // Nothing to do here, consider the operation successful.
  427. if (callback) {
  428. dispatch_async(dispatch_get_main_queue(), ^{
  429. callback(nil);
  430. });
  431. }
  432. return;
  433. }
  434. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  435. [GIDSignInPreferences googleAuthorizationServer], token];
  436. // Append logging parameter
  437. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@&%@=%@",
  438. revokeURLString,
  439. kSDKVersionLoggingParameter,
  440. GIDVersion(),
  441. kEnvironmentLoggingParameter,
  442. GIDEnvironment()];
  443. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  444. [self startFetchURL:revokeURL
  445. fromAuthState:authState
  446. withComment:@"GIDSignIn: revoke tokens"
  447. withCompletionHandler:^(NSData *data, NSError *error) {
  448. // Revoking an already revoked token seems always successful, which helps us here.
  449. if (!error) {
  450. [self signOut];
  451. }
  452. if (callback) {
  453. dispatch_async(dispatch_get_main_queue(), ^{
  454. callback(error);
  455. });
  456. }
  457. }];
  458. }
  459. #pragma mark - Custom getters and setters
  460. + (GIDSignIn *)sharedInstance {
  461. static dispatch_once_t once;
  462. static GIDSignIn *sharedInstance;
  463. dispatch_once(&once, ^{
  464. sharedInstance = [[self alloc] initPrivate];
  465. });
  466. return sharedInstance;
  467. }
  468. #pragma mark - Private methods
  469. - (id)initPrivate {
  470. self = [super init];
  471. if (self) {
  472. // Check to see if the 3P app is being run for the first time after a fresh install.
  473. BOOL isFreshInstall = [self isFreshInstall];
  474. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  475. if (isFreshInstall) {
  476. [self removeAllKeychainEntries];
  477. }
  478. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  479. [GIDSignInPreferences googleAuthorizationServer]];
  480. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  481. [GIDSignInPreferences googleTokenServer]];
  482. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  483. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  484. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  485. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  486. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  487. [GIDAuthStateMigration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  488. callbackPath:kBrowserCallbackPath
  489. keychainName:kGTMAppAuthKeychainName
  490. isFreshInstall:isFreshInstall];
  491. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  492. }
  493. return self;
  494. }
  495. // Does sanity check for parameters and then authenticates if necessary.
  496. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  497. // Options for continuation are not the options we want to cache. The purpose of caching the
  498. // options in the first place is to provide continuation flows with a starting place from which to
  499. // derive suitable options for the continuation!
  500. if (!options.continuation) {
  501. _currentOptions = options;
  502. }
  503. if (options.interactive) {
  504. // Explicitly throw exception for missing client ID here. This must come before
  505. // scheme check because schemes rely on reverse client IDs.
  506. [self assertValidParameters];
  507. [self assertValidPresentingViewController];
  508. // If the application does not support the required URL schemes tell the developer so.
  509. GIDSignInCallbackSchemes *schemes =
  510. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  511. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  512. if (unsupportedSchemes.count != 0) {
  513. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  514. [NSException raise:NSInvalidArgumentException
  515. format:@"Your app is missing support for the following URL schemes: %@",
  516. [unsupportedSchemes componentsJoinedByString:@", "]];
  517. }
  518. }
  519. // If this is a non-interactive flow, use cached authentication if possible.
  520. if (!options.interactive && _currentUser.authentication) {
  521. [_currentUser.authentication doWithFreshTokens:^(GIDAuthentication *unused, NSError *error) {
  522. if (error) {
  523. [self authenticateWithOptions:options];
  524. } else {
  525. if (options.callback) {
  526. self->_currentOptions = nil;
  527. dispatch_async(dispatch_get_main_queue(), ^{
  528. options.callback(self->_currentUser, nil);
  529. });
  530. }
  531. }
  532. }];
  533. } else {
  534. [self authenticateWithOptions:options];
  535. }
  536. }
  537. #pragma mark - Authentication flow
  538. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  539. GIDSignInCallbackSchemes *schemes =
  540. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  541. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  542. [schemes clientIdentifierScheme],
  543. kBrowserCallbackPath]];
  544. NSString *emmSupport;
  545. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  546. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  547. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  548. emmSupport = nil;
  549. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  550. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  551. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  552. if (options.configuration.serverClientID) {
  553. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  554. }
  555. if (options.loginHint) {
  556. additionalParameters[kLoginHintParameter] = options.loginHint;
  557. }
  558. if (options.configuration.hostedDomain) {
  559. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  560. }
  561. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  562. [additionalParameters addEntriesFromDictionary:
  563. [GIDAuthentication parametersWithParameters:options.extraParams
  564. emmSupport:emmSupport
  565. isPasscodeInfoRequired:NO]];
  566. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  567. [additionalParameters addEntriesFromDictionary:options.extraParams];
  568. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  569. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  570. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  571. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  572. OIDAuthorizationRequest *request =
  573. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  574. clientId:options.configuration.clientID
  575. scopes:options.scopes
  576. redirectURL:redirectURL
  577. responseType:OIDResponseTypeCode
  578. additionalParameters:additionalParameters];
  579. _currentAuthorizationFlow = [OIDAuthorizationService
  580. presentAuthorizationRequest:request
  581. presentingViewController:options.presentingViewController
  582. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  583. NSError *_Nullable error) {
  584. [self processAuthorizationResponse:authorizationResponse
  585. error:error
  586. emmSupport:emmSupport];
  587. }];
  588. #elif TARGET_OS_OSX
  589. OIDAuthorizationRequest *request =
  590. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  591. clientId:options.configuration.clientID
  592. clientSecret:@""
  593. scopes:options.scopes
  594. redirectURL:redirectURL
  595. responseType:OIDResponseTypeCode
  596. additionalParameters:additionalParameters];
  597. _currentAuthorizationFlow = [OIDAuthorizationService
  598. presentAuthorizationRequest:request
  599. presentingWindow:options.presentingWindow
  600. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  601. NSError *_Nullable error) {
  602. [self processAuthorizationResponse:authorizationResponse
  603. error:error
  604. emmSupport:emmSupport];
  605. }];
  606. #endif // TARGET_OS_OSX
  607. }
  608. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  609. error:(NSError *)error
  610. emmSupport:(NSString *)emmSupport{
  611. if (_restarting) {
  612. // The auth flow is restarting, so the work here would be performed in the next round.
  613. _restarting = NO;
  614. return;
  615. }
  616. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  617. authFlow.emmSupport = emmSupport;
  618. if (authorizationResponse) {
  619. if (authorizationResponse.authorizationCode.length) {
  620. authFlow.authState = [[OIDAuthState alloc]
  621. initWithAuthorizationResponse:authorizationResponse];
  622. // perform auth code exchange
  623. [self maybeFetchToken:authFlow fallback:nil];
  624. } else {
  625. // There was a failure, convert to appropriate error code.
  626. NSString *errorString;
  627. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  628. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  629. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  630. if (authFlow.emmSupport) {
  631. [authFlow wait];
  632. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  633. handleErrorFromResponse:params
  634. completion:^{
  635. [authFlow next];
  636. }];
  637. if (isEMMError) {
  638. errorCode = kGIDSignInErrorCodeEMM;
  639. }
  640. }
  641. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  642. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  643. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  644. errorCode = kGIDSignInErrorCodeCanceled;
  645. }
  646. authFlow.error = [self errorWithString:errorString code:errorCode];
  647. }
  648. } else {
  649. NSString *errorString = [error localizedDescription];
  650. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  651. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  652. // The user has canceled the flow at the iOS modal dialog.
  653. errorString = kUserCanceledError;
  654. errorCode = kGIDSignInErrorCodeCanceled;
  655. }
  656. authFlow.error = [self errorWithString:errorString code:errorCode];
  657. }
  658. [self addDecodeIdTokenCallback:authFlow];
  659. [self addSaveAuthCallback:authFlow];
  660. [self addCompletionCallback:authFlow];
  661. }
  662. // Perform authentication with the provided options.
  663. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  664. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  665. if (options.interactive) {
  666. [self authenticateInteractivelyWithOptions:options];
  667. return;
  668. }
  669. // Try retrieving an authorization object from the keychain.
  670. OIDAuthState *authState = [self loadAuthState];
  671. if (![authState isAuthorized]) {
  672. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  673. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  674. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  675. userInfo:nil];
  676. if (options.callback) {
  677. _currentOptions = nil;
  678. dispatch_async(dispatch_get_main_queue(), ^{
  679. options.callback(nil, error);
  680. });
  681. }
  682. return;
  683. }
  684. // Complete the auth flow using saved auth in keychain.
  685. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  686. authFlow.authState = authState;
  687. [self maybeFetchToken:authFlow fallback:options.interactive ? ^() {
  688. [self authenticateInteractivelyWithOptions:options];
  689. } : nil];
  690. [self addDecodeIdTokenCallback:authFlow];
  691. [self addSaveAuthCallback:authFlow];
  692. [self addCompletionCallback:authFlow];
  693. }
  694. // Fetches the access token if necessary as part of the auth flow. If |fallback|
  695. // is provided, call it instead of continuing the auth flow in case of error.
  696. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow fallback:(nullable void (^)(void))fallback {
  697. OIDAuthState *authState = authFlow.authState;
  698. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  699. if (authFlow.error ||
  700. (authState.lastTokenResponse.accessToken &&
  701. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  702. kMinimumRestoredAccessTokenTimeToExpire)) {
  703. return;
  704. }
  705. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  706. if (_currentOptions.configuration.serverClientID) {
  707. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  708. }
  709. if (_currentOptions.configuration.openIDRealm) {
  710. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  711. }
  712. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  713. NSDictionary<NSString *, NSObject *> *params =
  714. authState.lastAuthorizationResponse.additionalParameters;
  715. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  716. [additionalParameters addEntriesFromDictionary:
  717. [GIDAuthentication parametersWithParameters:@{}
  718. emmSupport:authFlow.emmSupport
  719. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  720. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  721. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  722. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  723. OIDTokenRequest *tokenRequest;
  724. if (!authState.lastTokenResponse.accessToken &&
  725. authState.lastAuthorizationResponse.authorizationCode) {
  726. tokenRequest = [authState.lastAuthorizationResponse
  727. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  728. } else {
  729. [additionalParameters
  730. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  731. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  732. }
  733. [authFlow wait];
  734. [OIDAuthorizationService
  735. performTokenRequest:tokenRequest
  736. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  737. NSError *_Nullable error) {
  738. [authState updateWithTokenResponse:tokenResponse error:error];
  739. authFlow.error = error;
  740. if (!tokenResponse.accessToken || error) {
  741. if (fallback) {
  742. [authFlow reset];
  743. fallback();
  744. return;
  745. }
  746. }
  747. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  748. if (authFlow.emmSupport) {
  749. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *error) {
  750. authFlow.error = error;
  751. [authFlow next];
  752. }];
  753. } else {
  754. [authFlow next];
  755. }
  756. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  757. [authFlow next];
  758. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  759. }];
  760. }
  761. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  762. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  763. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  764. [authFlow addCallback:^() {
  765. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  766. OIDAuthState *authState = handlerAuthFlow.authState;
  767. if (authState && !handlerAuthFlow.error) {
  768. if (![self saveAuthState:authState]) {
  769. handlerAuthFlow.error = [self errorWithString:kKeychainError
  770. code:kGIDSignInErrorCodeKeychain];
  771. return;
  772. }
  773. if (self->_currentOptions.addScopesFlow) {
  774. [self->_currentUser updateAuthState:authState
  775. profileData:handlerAuthFlow.profileData];
  776. } else {
  777. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  778. profileData:handlerAuthFlow.profileData];
  779. [self setCurrentUserWithKVO:user];
  780. }
  781. }
  782. }];
  783. }
  784. // Adds a callback to the auth flow to extract user data from the ID token where available and
  785. // make a userinfo request if necessary.
  786. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  787. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  788. [authFlow addCallback:^() {
  789. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  790. OIDAuthState *authState = handlerAuthFlow.authState;
  791. if (!authState || handlerAuthFlow.error) {
  792. return;
  793. }
  794. OIDIDToken *idToken =
  795. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  796. // If the profile data are present in the ID token, use them.
  797. if (idToken) {
  798. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  799. }
  800. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  801. if (!handlerAuthFlow.profileData) {
  802. [handlerAuthFlow wait];
  803. NSURL *infoURL = [NSURL URLWithString:
  804. [NSString stringWithFormat:kUserInfoURLTemplate,
  805. [GIDSignInPreferences googleUserInfoServer],
  806. authState.lastTokenResponse.accessToken]];
  807. [self startFetchURL:infoURL
  808. fromAuthState:authState
  809. withComment:@"GIDSignIn: fetch basic profile info"
  810. withCompletionHandler:^(NSData *data, NSError *error) {
  811. if (data && !error) {
  812. NSError *jsonDeserializationError;
  813. NSDictionary<NSString *, NSString *> *profileDict =
  814. [NSJSONSerialization JSONObjectWithData:data
  815. options:NSJSONReadingMutableContainers
  816. error:&jsonDeserializationError];
  817. if (profileDict) {
  818. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  819. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  820. name:profileDict[kBasicProfileNameKey]
  821. givenName:profileDict[kBasicProfileGivenNameKey]
  822. familyName:profileDict[kBasicProfileFamilyNameKey]
  823. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  824. }
  825. }
  826. if (error) {
  827. handlerAuthFlow.error = error;
  828. }
  829. [handlerAuthFlow next];
  830. }];
  831. }
  832. }];
  833. }
  834. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  835. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  836. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  837. [authFlow addCallback:^() {
  838. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  839. if (self->_currentOptions.callback) {
  840. GIDSignInCallback callback = self->_currentOptions.callback;
  841. self->_currentOptions = nil;
  842. dispatch_async(dispatch_get_main_queue(), ^{
  843. callback(self->_currentUser, handlerAuthFlow.error);
  844. });
  845. }
  846. }];
  847. }
  848. - (void)startFetchURL:(NSURL *)URL
  849. fromAuthState:(OIDAuthState *)authState
  850. withComment:(NSString *)comment
  851. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  852. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  853. GTMSessionFetcher *fetcher;
  854. GTMAppAuthFetcherAuthorization *authorization =
  855. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  856. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  857. if (fetcherService) {
  858. fetcher = [fetcherService fetcherWithRequest:request];
  859. } else {
  860. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  861. }
  862. fetcher.retryEnabled = YES;
  863. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  864. fetcher.comment = comment;
  865. [fetcher beginFetchWithCompletionHandler:handler];
  866. }
  867. // Parse incoming URL from the Google Device Policy app.
  868. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  869. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  870. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  871. NSObject<NSCopying> *actionParam = params[@"action"];
  872. NSString *actionString =
  873. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  874. if (![@"restart_auth" isEqualToString:actionString]) {
  875. return NO;
  876. }
  877. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  878. if (!_currentOptions.presentingViewController) {
  879. return NO;
  880. }
  881. #elif TARGET_OS_OSX
  882. if (!_currentOptions.presentingWindow) {
  883. return NO;
  884. }
  885. #endif // TARGET_OS_OSX
  886. if (!_currentAuthorizationFlow) {
  887. return NO;
  888. }
  889. _restarting = YES;
  890. [_currentAuthorizationFlow cancel];
  891. _currentAuthorizationFlow = nil;
  892. _restarting = NO;
  893. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  894. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  895. // so we need to wait until the previous presentation is completely gone to ensure the right
  896. // anchor window is used here.
  897. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  898. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  899. dispatch_get_main_queue(), ^{
  900. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  901. forContinuation:YES]];
  902. });
  903. return YES;
  904. }
  905. #pragma mark - Key-Value Observing
  906. // Override |NSObject(NSKeyValueObservingCustomization)| method in order to provide custom KVO
  907. // notifications for the |currentUser| property.
  908. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  909. if ([key isEqual:NSStringFromSelector(@selector(currentUser))]) {
  910. return NO;
  911. }
  912. return [super automaticallyNotifiesObserversForKey:key];
  913. }
  914. #pragma mark - Helpers
  915. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  916. if (errorString == nil) {
  917. errorString = @"Unknown error";
  918. }
  919. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  920. return [NSError errorWithDomain:kGIDSignInErrorDomain
  921. code:code
  922. userInfo:errorDict];
  923. }
  924. + (BOOL)isOperatingSystemAtLeast9 {
  925. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  926. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  927. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  928. }
  929. // Asserts the parameters being valid.
  930. - (void)assertValidParameters {
  931. if (![_currentOptions.configuration.clientID length]) {
  932. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  933. [NSException raise:NSInvalidArgumentException
  934. format:@"You must specify |clientID| in |GIDConfiguration|"];
  935. }
  936. }
  937. // Assert that the presenting view controller has been set.
  938. - (void)assertValidPresentingViewController {
  939. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  940. if (!_currentOptions.presentingViewController) {
  941. #elif TARGET_OS_OSX
  942. if (!_currentOptions.presentingWindow) {
  943. #endif // TARGET_OS_OSX
  944. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  945. [NSException raise:NSInvalidArgumentException
  946. format:@"|presentingViewController| must be set."];
  947. }
  948. }
  949. // Checks whether or not this is the first time the app runs.
  950. - (BOOL)isFreshInstall {
  951. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  952. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  953. return NO;
  954. }
  955. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  956. return YES;
  957. }
  958. - (void)removeAllKeychainEntries {
  959. [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:kGTMAppAuthKeychainName
  960. useDataProtectionKeychain:YES];
  961. }
  962. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  963. GTMAppAuthFetcherAuthorization *authorization =
  964. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  965. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  966. toKeychainForName:kGTMAppAuthKeychainName
  967. useDataProtectionKeychain:YES];
  968. }
  969. - (OIDAuthState *)loadAuthState {
  970. GTMAppAuthFetcherAuthorization *authorization =
  971. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName
  972. useDataProtectionKeychain:YES];
  973. return authorization.authState;
  974. }
  975. // Generates user profile from OIDIDToken.
  976. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  977. if (!idToken ||
  978. !idToken.claims[kBasicProfilePictureKey] ||
  979. !idToken.claims[kBasicProfileNameKey] ||
  980. !idToken.claims[kBasicProfileGivenNameKey] ||
  981. !idToken.claims[kBasicProfileFamilyNameKey]) {
  982. return nil;
  983. }
  984. return [[GIDProfileData alloc]
  985. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  986. name:idToken.claims[kBasicProfileNameKey]
  987. givenName:idToken.claims[kBasicProfileGivenNameKey]
  988. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  989. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  990. }
  991. // Set currentUser making appropriate KVO calls.
  992. - (void)setCurrentUserWithKVO:(GIDGoogleUser *_Nullable)user {
  993. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  994. _currentUser = user;
  995. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  996. }
  997. @end
  998. NS_ASSUME_NONNULL_END