GIDSignIn.m 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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/GIDAuthentication.h"
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  18. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  19. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  20. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDUserAuth.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 "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  28. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  29. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  30. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  31. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  32. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  33. #import "GoogleSignIn/Sources/GIDUserAuth_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)restorePreviousSignInWithCompletion:(nullable void (^)(GIDGoogleUser *_Nullable user,
  156. NSError *_Nullable error))completion {
  157. [self signInWithOptions:[GIDSignInInternalOptions silentOptionsWithCompletion:
  158. ^(GIDUserAuth *userAuth, NSError *error) {
  159. if (userAuth) {
  160. completion(userAuth.user, nil);
  161. } else {
  162. completion(nil, error);
  163. }
  164. }]];
  165. }
  166. - (BOOL)restorePreviousSignInNoRefresh {
  167. if (_currentUser) {
  168. return YES;
  169. }
  170. // Try retrieving an authorization object from the keychain.
  171. OIDAuthState *authState = [self loadAuthState];
  172. if (!authState) {
  173. return NO;
  174. }
  175. // Restore current user without refreshing the access token.
  176. OIDIDToken *idToken =
  177. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  178. GIDProfileData *profileData = [self profileDataWithIDToken:idToken];
  179. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState profileData:profileData];
  180. [self setCurrentUserWithKVO:user];
  181. return YES;
  182. }
  183. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  184. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  185. presentingViewController:(UIViewController *)presentingViewController
  186. hint:(nullable NSString *)hint
  187. completion:(nullable GIDUserAuthCompletion)completion {
  188. GIDSignInInternalOptions *options =
  189. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  190. presentingViewController:presentingViewController
  191. loginHint:hint
  192. addScopesFlow:NO
  193. completion:completion];
  194. [self signInWithOptions:options];
  195. }
  196. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  197. presentingViewController:(UIViewController *)presentingViewController
  198. hint:(nullable NSString *)hint
  199. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  200. completion:(nullable GIDUserAuthCompletion)completion {
  201. GIDSignInInternalOptions *options =
  202. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  203. presentingViewController:presentingViewController
  204. loginHint:hint
  205. addScopesFlow:NO
  206. scopes:additionalScopes
  207. completion:completion];
  208. [self signInWithOptions:options];
  209. }
  210. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  211. presentingViewController:(UIViewController *)presentingViewController
  212. completion:(nullable GIDUserAuthCompletion)completion {
  213. [self signInWithConfiguration:configuration
  214. presentingViewController:presentingViewController
  215. hint:nil
  216. completion:completion];
  217. }
  218. - (void)addScopes:(NSArray<NSString *> *)scopes
  219. presentingViewController:(UIViewController *)presentingViewController
  220. completion:(nullable GIDUserAuthCompletion)completion {
  221. // A currentUser must be available in order to complete this flow.
  222. if (!self.currentUser) {
  223. // No currentUser is set, notify callback of failure.
  224. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  225. code:kGIDSignInErrorCodeNoCurrentUser
  226. userInfo:nil];
  227. if (completion) {
  228. dispatch_async(dispatch_get_main_queue(), ^{
  229. completion(nil, error);
  230. });
  231. }
  232. return;
  233. }
  234. GIDConfiguration *configuration = self.currentUser.configuration;
  235. GIDSignInInternalOptions *options =
  236. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  237. presentingViewController:presentingViewController
  238. loginHint:self.currentUser.profile.email
  239. addScopesFlow:YES
  240. completion:completion];
  241. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  242. NSMutableSet<NSString *> *grantedScopes =
  243. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  244. // Check to see if all requested scopes have already been granted.
  245. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  246. // All requested scopes have already been granted, notify callback of failure.
  247. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  248. code:kGIDSignInErrorCodeScopesAlreadyGranted
  249. userInfo:nil];
  250. if (completion) {
  251. dispatch_async(dispatch_get_main_queue(), ^{
  252. completion(nil, error);
  253. });
  254. }
  255. return;
  256. }
  257. // Use the union of granted and requested scopes.
  258. [grantedScopes unionSet:requestedScopes];
  259. options.scopes = [grantedScopes allObjects];
  260. [self signInWithOptions:options];
  261. }
  262. #elif TARGET_OS_OSX
  263. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  264. presentingWindow:(NSWindow *)presentingWindow
  265. hint:(nullable NSString *)hint
  266. completion:(nullable GIDUserAuthCompletion)completion {
  267. GIDSignInInternalOptions *options =
  268. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  269. presentingWindow:presentingWindow
  270. loginHint:hint
  271. addScopesFlow:NO
  272. completion:completion];
  273. [self signInWithOptions:options];
  274. }
  275. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  276. presentingWindow:(NSWindow *)presentingWindow
  277. completion:(nullable GIDUserAuthCompletion)completion {
  278. [self signInWithConfiguration:configuration
  279. presentingWindow:presentingWindow
  280. hint:nil
  281. completion:completion];
  282. }
  283. - (void)signInWithConfiguration:(GIDConfiguration *)configuration
  284. presentingWindow:(NSWindow *)presentingWindow
  285. hint:(nullable NSString *)hint
  286. additionalScopes:(nullable NSArray<NSString *> *)additionalScopes
  287. completion:(nullable GIDUserAuthCompletion)completion {
  288. GIDSignInInternalOptions *options =
  289. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  290. presentingWindow:presentingWindow
  291. loginHint:hint
  292. addScopesFlow:NO
  293. scopes:additionalScopes
  294. completion:completion];
  295. [self signInWithOptions:options];
  296. }
  297. - (void)addScopes:(NSArray<NSString *> *)scopes
  298. presentingWindow:(NSWindow *)presentingWindow
  299. completion:(nullable GIDUserAuthCompletion)completion {
  300. // A currentUser must be available in order to complete this flow.
  301. if (!self.currentUser) {
  302. // No currentUser is set, notify callback of failure.
  303. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  304. code:kGIDSignInErrorCodeNoCurrentUser
  305. userInfo:nil];
  306. if (completion) {
  307. dispatch_async(dispatch_get_main_queue(), ^{
  308. completion(nil, error);
  309. });
  310. }
  311. return;
  312. }
  313. GIDConfiguration *configuration = self.currentUser.configuration;
  314. GIDSignInInternalOptions *options =
  315. [GIDSignInInternalOptions defaultOptionsWithConfiguration:configuration
  316. presentingWindow:presentingWindow
  317. loginHint:self.currentUser.profile.email
  318. addScopesFlow:YES
  319. completion:completion];
  320. NSSet<NSString *> *requestedScopes = [NSSet setWithArray:scopes];
  321. NSMutableSet<NSString *> *grantedScopes =
  322. [NSMutableSet setWithArray:self.currentUser.grantedScopes];
  323. // Check to see if all requested scopes have already been granted.
  324. if ([requestedScopes isSubsetOfSet:grantedScopes]) {
  325. // All requested scopes have already been granted, notify callback of failure.
  326. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  327. code:kGIDSignInErrorCodeScopesAlreadyGranted
  328. userInfo:nil];
  329. if (completion) {
  330. dispatch_async(dispatch_get_main_queue(), ^{
  331. completion(nil, error);
  332. });
  333. }
  334. return;
  335. }
  336. // Use the union of granted and requested scopes.
  337. [grantedScopes unionSet:requestedScopes];
  338. options.scopes = [grantedScopes allObjects];
  339. [self signInWithOptions:options];
  340. }
  341. #endif // TARGET_OS_OSX
  342. - (void)signOut {
  343. // Clear the current user if there is one.
  344. if (_currentUser) {
  345. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  346. _currentUser = nil;
  347. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  348. }
  349. // Remove all state from the keychain.
  350. [self removeAllKeychainEntries];
  351. }
  352. - (void)disconnectWithCompletion:(nullable GIDDisconnectCompletion)completion {
  353. GIDGoogleUser *user = _currentUser;
  354. OIDAuthState *authState = user.authentication.authState;
  355. if (!authState) {
  356. // Even the user is not signed in right now, we still need to remove any token saved in the
  357. // keychain.
  358. authState = [self loadAuthState];
  359. }
  360. // Either access or refresh token would work, but we won't have access token if the auth is
  361. // retrieved from keychain.
  362. NSString *token = authState.lastTokenResponse.accessToken;
  363. if (!token) {
  364. token = authState.lastTokenResponse.refreshToken;
  365. }
  366. if (!token) {
  367. [self signOut];
  368. // Nothing to do here, consider the operation successful.
  369. if (completion) {
  370. dispatch_async(dispatch_get_main_queue(), ^{
  371. completion(nil);
  372. });
  373. }
  374. return;
  375. }
  376. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  377. [GIDSignInPreferences googleAuthorizationServer], token];
  378. // Append logging parameter
  379. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@&%@=%@",
  380. revokeURLString,
  381. kSDKVersionLoggingParameter,
  382. GIDVersion(),
  383. kEnvironmentLoggingParameter,
  384. GIDEnvironment()];
  385. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  386. [self startFetchURL:revokeURL
  387. fromAuthState:authState
  388. withComment:@"GIDSignIn: revoke tokens"
  389. withCompletionHandler:^(NSData *data, NSError *error) {
  390. // Revoking an already revoked token seems always successful, which helps us here.
  391. if (!error) {
  392. [self signOut];
  393. }
  394. if (completion) {
  395. dispatch_async(dispatch_get_main_queue(), ^{
  396. completion(error);
  397. });
  398. }
  399. }];
  400. }
  401. #pragma mark - Custom getters and setters
  402. + (GIDSignIn *)sharedInstance {
  403. static dispatch_once_t once;
  404. static GIDSignIn *sharedInstance;
  405. dispatch_once(&once, ^{
  406. sharedInstance = [[self alloc] initPrivate];
  407. });
  408. return sharedInstance;
  409. }
  410. #pragma mark - Private methods
  411. - (id)initPrivate {
  412. self = [super init];
  413. if (self) {
  414. // Check to see if the 3P app is being run for the first time after a fresh install.
  415. BOOL isFreshInstall = [self isFreshInstall];
  416. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  417. if (isFreshInstall) {
  418. [self removeAllKeychainEntries];
  419. }
  420. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  421. [GIDSignInPreferences googleAuthorizationServer]];
  422. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  423. [GIDSignInPreferences googleTokenServer]];
  424. _appAuthConfiguration = [[OIDServiceConfiguration alloc]
  425. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  426. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  427. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  428. // Perform migration of auth state from old (before 5.0) versions of the SDK if needed.
  429. [GIDAuthStateMigration migrateIfNeededWithTokenURL:_appAuthConfiguration.tokenEndpoint
  430. callbackPath:kBrowserCallbackPath
  431. keychainName:kGTMAppAuthKeychainName
  432. isFreshInstall:isFreshInstall];
  433. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  434. }
  435. return self;
  436. }
  437. // Does sanity check for parameters and then authenticates if necessary.
  438. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  439. // Options for continuation are not the options we want to cache. The purpose of caching the
  440. // options in the first place is to provide continuation flows with a starting place from which to
  441. // derive suitable options for the continuation!
  442. if (!options.continuation) {
  443. _currentOptions = options;
  444. }
  445. if (options.interactive) {
  446. // Explicitly throw exception for missing client ID here. This must come before
  447. // scheme check because schemes rely on reverse client IDs.
  448. [self assertValidParameters];
  449. [self assertValidPresentingViewController];
  450. // If the application does not support the required URL schemes tell the developer so.
  451. GIDSignInCallbackSchemes *schemes =
  452. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  453. NSArray<NSString *> *unsupportedSchemes = [schemes unsupportedSchemes];
  454. if (unsupportedSchemes.count != 0) {
  455. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  456. [NSException raise:NSInvalidArgumentException
  457. format:@"Your app is missing support for the following URL schemes: %@",
  458. [unsupportedSchemes componentsJoinedByString:@", "]];
  459. }
  460. }
  461. // If this is a non-interactive flow, use cached authentication if possible.
  462. if (!options.interactive && _currentUser.authentication) {
  463. [_currentUser.authentication doWithFreshTokens:^(GIDAuthentication *unused, NSError *error) {
  464. if (error) {
  465. [self authenticateWithOptions:options];
  466. } else {
  467. if (options.completion) {
  468. self->_currentOptions = nil;
  469. dispatch_async(dispatch_get_main_queue(), ^{
  470. GIDUserAuth *userAuth = [[GIDUserAuth alloc] initWithGoogleUser:self->_currentUser serverAuthCode:nil];
  471. options.completion(userAuth, nil);
  472. });
  473. }
  474. }
  475. }];
  476. } else {
  477. [self authenticateWithOptions:options];
  478. }
  479. }
  480. #pragma mark - Authentication flow
  481. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  482. GIDSignInCallbackSchemes *schemes =
  483. [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:options.configuration.clientID];
  484. NSURL *redirectURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@",
  485. [schemes clientIdentifierScheme],
  486. kBrowserCallbackPath]];
  487. NSString *emmSupport;
  488. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  489. emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  490. #elif TARGET_OS_MACCATALYST || TARGET_OS_OSX
  491. emmSupport = nil;
  492. #endif // TARGET_OS_MACCATALYST || TARGET_OS_OSX
  493. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  494. additionalParameters[kIncludeGrantedScopesParameter] = @"true";
  495. if (options.configuration.serverClientID) {
  496. additionalParameters[kAudienceParameter] = options.configuration.serverClientID;
  497. }
  498. if (options.loginHint) {
  499. additionalParameters[kLoginHintParameter] = options.loginHint;
  500. }
  501. if (options.configuration.hostedDomain) {
  502. additionalParameters[kHostedDomainParameter] = options.configuration.hostedDomain;
  503. }
  504. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  505. [additionalParameters addEntriesFromDictionary:
  506. [GIDAuthentication parametersWithParameters:options.extraParams
  507. emmSupport:emmSupport
  508. isPasscodeInfoRequired:NO]];
  509. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  510. [additionalParameters addEntriesFromDictionary:options.extraParams];
  511. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  512. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  513. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  514. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  515. OIDAuthorizationRequest *request =
  516. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  517. clientId:options.configuration.clientID
  518. scopes:options.scopes
  519. redirectURL:redirectURL
  520. responseType:OIDResponseTypeCode
  521. additionalParameters:additionalParameters];
  522. _currentAuthorizationFlow = [OIDAuthorizationService
  523. presentAuthorizationRequest:request
  524. presentingViewController:options.presentingViewController
  525. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  526. NSError *_Nullable error) {
  527. [self processAuthorizationResponse:authorizationResponse
  528. error:error
  529. emmSupport:emmSupport];
  530. }];
  531. #elif TARGET_OS_OSX
  532. OIDAuthorizationRequest *request =
  533. [[OIDAuthorizationRequest alloc] initWithConfiguration:_appAuthConfiguration
  534. clientId:options.configuration.clientID
  535. clientSecret:@""
  536. scopes:options.scopes
  537. redirectURL:redirectURL
  538. responseType:OIDResponseTypeCode
  539. additionalParameters:additionalParameters];
  540. _currentAuthorizationFlow = [OIDAuthorizationService
  541. presentAuthorizationRequest:request
  542. presentingWindow:options.presentingWindow
  543. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  544. NSError *_Nullable error) {
  545. [self processAuthorizationResponse:authorizationResponse
  546. error:error
  547. emmSupport:emmSupport];
  548. }];
  549. #endif // TARGET_OS_OSX
  550. }
  551. - (void)processAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse
  552. error:(NSError *)error
  553. emmSupport:(NSString *)emmSupport{
  554. if (_restarting) {
  555. // The auth flow is restarting, so the work here would be performed in the next round.
  556. _restarting = NO;
  557. return;
  558. }
  559. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  560. authFlow.emmSupport = emmSupport;
  561. if (authorizationResponse) {
  562. if (authorizationResponse.authorizationCode.length) {
  563. authFlow.authState = [[OIDAuthState alloc]
  564. initWithAuthorizationResponse:authorizationResponse];
  565. // perform auth code exchange
  566. [self maybeFetchToken:authFlow fallback:nil];
  567. } else {
  568. // There was a failure, convert to appropriate error code.
  569. NSString *errorString;
  570. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  571. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  572. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  573. if (authFlow.emmSupport) {
  574. [authFlow wait];
  575. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  576. handleErrorFromResponse:params
  577. completion:^{
  578. [authFlow next];
  579. }];
  580. if (isEMMError) {
  581. errorCode = kGIDSignInErrorCodeEMM;
  582. }
  583. }
  584. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  585. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  586. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  587. errorCode = kGIDSignInErrorCodeCanceled;
  588. }
  589. authFlow.error = [self errorWithString:errorString code:errorCode];
  590. }
  591. } else {
  592. NSString *errorString = [error localizedDescription];
  593. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  594. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  595. // The user has canceled the flow at the iOS modal dialog.
  596. errorString = kUserCanceledError;
  597. errorCode = kGIDSignInErrorCodeCanceled;
  598. }
  599. authFlow.error = [self errorWithString:errorString code:errorCode];
  600. }
  601. [self addDecodeIdTokenCallback:authFlow];
  602. [self addSaveAuthCallback:authFlow];
  603. [self addCompletionCallback:authFlow];
  604. }
  605. // Perform authentication with the provided options.
  606. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  607. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  608. if (options.interactive) {
  609. [self authenticateInteractivelyWithOptions:options];
  610. return;
  611. }
  612. // Try retrieving an authorization object from the keychain.
  613. OIDAuthState *authState = [self loadAuthState];
  614. if (![authState isAuthorized]) {
  615. // No valid auth in keychain, per documentation/spec, notify callback of failure.
  616. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  617. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  618. userInfo:nil];
  619. if (options.completion) {
  620. _currentOptions = nil;
  621. dispatch_async(dispatch_get_main_queue(), ^{
  622. options.completion(nil, error);
  623. });
  624. }
  625. return;
  626. }
  627. // Complete the auth flow using saved auth in keychain.
  628. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  629. authFlow.authState = authState;
  630. [self maybeFetchToken:authFlow fallback:options.interactive ? ^() {
  631. [self authenticateInteractivelyWithOptions:options];
  632. } : nil];
  633. [self addDecodeIdTokenCallback:authFlow];
  634. [self addSaveAuthCallback:authFlow];
  635. [self addCompletionCallback:authFlow];
  636. }
  637. // Fetches the access token if necessary as part of the auth flow. If |fallback|
  638. // is provided, call it instead of continuing the auth flow in case of error.
  639. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow fallback:(nullable void (^)(void))fallback {
  640. OIDAuthState *authState = authFlow.authState;
  641. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  642. if (authFlow.error ||
  643. (authState.lastTokenResponse.accessToken &&
  644. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  645. kMinimumRestoredAccessTokenTimeToExpire)) {
  646. return;
  647. }
  648. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  649. if (_currentOptions.configuration.serverClientID) {
  650. additionalParameters[kAudienceParameter] = _currentOptions.configuration.serverClientID;
  651. }
  652. if (_currentOptions.configuration.openIDRealm) {
  653. additionalParameters[kOpenIDRealmParameter] = _currentOptions.configuration.openIDRealm;
  654. }
  655. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  656. NSDictionary<NSString *, NSObject *> *params =
  657. authState.lastAuthorizationResponse.additionalParameters;
  658. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  659. [additionalParameters addEntriesFromDictionary:
  660. [GIDAuthentication parametersWithParameters:@{}
  661. emmSupport:authFlow.emmSupport
  662. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  663. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  664. additionalParameters[kSDKVersionLoggingParameter] = GIDVersion();
  665. additionalParameters[kEnvironmentLoggingParameter] = GIDEnvironment();
  666. OIDTokenRequest *tokenRequest;
  667. if (!authState.lastTokenResponse.accessToken &&
  668. authState.lastAuthorizationResponse.authorizationCode) {
  669. tokenRequest = [authState.lastAuthorizationResponse
  670. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  671. } else {
  672. [additionalParameters
  673. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  674. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  675. }
  676. [authFlow wait];
  677. [OIDAuthorizationService
  678. performTokenRequest:tokenRequest
  679. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  680. NSError *_Nullable error) {
  681. [authState updateWithTokenResponse:tokenResponse error:error];
  682. authFlow.error = error;
  683. if (!tokenResponse.accessToken || error) {
  684. if (fallback) {
  685. [authFlow reset];
  686. fallback();
  687. return;
  688. }
  689. }
  690. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  691. if (authFlow.emmSupport) {
  692. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *error) {
  693. authFlow.error = error;
  694. [authFlow next];
  695. }];
  696. } else {
  697. [authFlow next];
  698. }
  699. #elif TARGET_OS_OSX || TARGET_OS_MACCATALYST
  700. [authFlow next];
  701. #endif // TARGET_OS_OSX || TARGET_OS_MACCATALYST
  702. }];
  703. }
  704. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  705. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  706. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  707. [authFlow addCallback:^() {
  708. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  709. OIDAuthState *authState = handlerAuthFlow.authState;
  710. if (authState && !handlerAuthFlow.error) {
  711. if (![self saveAuthState:authState]) {
  712. handlerAuthFlow.error = [self errorWithString:kKeychainError
  713. code:kGIDSignInErrorCodeKeychain];
  714. return;
  715. }
  716. if (self->_currentOptions.addScopesFlow) {
  717. [self->_currentUser updateAuthState:authState
  718. profileData:handlerAuthFlow.profileData];
  719. } else {
  720. GIDGoogleUser *user = [[GIDGoogleUser alloc] initWithAuthState:authState
  721. profileData:handlerAuthFlow.profileData];
  722. [self setCurrentUserWithKVO:user];
  723. }
  724. }
  725. }];
  726. }
  727. // Adds a callback to the auth flow to extract user data from the ID token where available and
  728. // make a userinfo request if necessary.
  729. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  730. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  731. [authFlow addCallback:^() {
  732. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  733. OIDAuthState *authState = handlerAuthFlow.authState;
  734. if (!authState || handlerAuthFlow.error) {
  735. return;
  736. }
  737. OIDIDToken *idToken =
  738. [[OIDIDToken alloc] initWithIDTokenString: authState.lastTokenResponse.idToken];
  739. // If the profile data are present in the ID token, use them.
  740. if (idToken) {
  741. handlerAuthFlow.profileData = [self profileDataWithIDToken:idToken];
  742. }
  743. // If we can't retrieve profile data from the ID token, make a userInfo request to fetch them.
  744. if (!handlerAuthFlow.profileData) {
  745. [handlerAuthFlow wait];
  746. NSURL *infoURL = [NSURL URLWithString:
  747. [NSString stringWithFormat:kUserInfoURLTemplate,
  748. [GIDSignInPreferences googleUserInfoServer],
  749. authState.lastTokenResponse.accessToken]];
  750. [self startFetchURL:infoURL
  751. fromAuthState:authState
  752. withComment:@"GIDSignIn: fetch basic profile info"
  753. withCompletionHandler:^(NSData *data, NSError *error) {
  754. if (data && !error) {
  755. NSError *jsonDeserializationError;
  756. NSDictionary<NSString *, NSString *> *profileDict =
  757. [NSJSONSerialization JSONObjectWithData:data
  758. options:NSJSONReadingMutableContainers
  759. error:&jsonDeserializationError];
  760. if (profileDict) {
  761. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  762. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  763. name:profileDict[kBasicProfileNameKey]
  764. givenName:profileDict[kBasicProfileGivenNameKey]
  765. familyName:profileDict[kBasicProfileFamilyNameKey]
  766. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  767. }
  768. }
  769. if (error) {
  770. handlerAuthFlow.error = error;
  771. }
  772. [handlerAuthFlow next];
  773. }];
  774. }
  775. }];
  776. }
  777. // Adds a callback to the auth flow to complete the flow by calling the sign-in callback.
  778. - (void)addCompletionCallback:(GIDAuthFlow *)authFlow {
  779. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  780. [authFlow addCallback:^() {
  781. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  782. if (self->_currentOptions.completion) {
  783. GIDUserAuthCompletion completion = self->_currentOptions.completion;
  784. self->_currentOptions = nil;
  785. dispatch_async(dispatch_get_main_queue(), ^{
  786. if (handlerAuthFlow.error) {
  787. completion(nil, handlerAuthFlow.error);
  788. } else {
  789. OIDAuthState *authState = handlerAuthFlow.authState;
  790. NSString *_Nullable serverAuthCode = [authState.lastTokenResponse.additionalParameters[@"server_code"] copy];
  791. GIDUserAuth *userAuth = [[GIDUserAuth alloc] initWithGoogleUser:self->_currentUser serverAuthCode:serverAuthCode];
  792. completion(userAuth, nil);
  793. }
  794. });
  795. }
  796. }];
  797. }
  798. - (void)startFetchURL:(NSURL *)URL
  799. fromAuthState:(OIDAuthState *)authState
  800. withComment:(NSString *)comment
  801. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  802. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  803. GTMSessionFetcher *fetcher;
  804. GTMAppAuthFetcherAuthorization *authorization =
  805. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  806. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  807. if (fetcherService) {
  808. fetcher = [fetcherService fetcherWithRequest:request];
  809. } else {
  810. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  811. }
  812. fetcher.retryEnabled = YES;
  813. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  814. fetcher.comment = comment;
  815. [fetcher beginFetchWithCompletionHandler:handler];
  816. }
  817. // Parse incoming URL from the Google Device Policy app.
  818. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  819. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  820. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  821. NSObject<NSCopying> *actionParam = params[@"action"];
  822. NSString *actionString =
  823. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  824. if (![@"restart_auth" isEqualToString:actionString]) {
  825. return NO;
  826. }
  827. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  828. if (!_currentOptions.presentingViewController) {
  829. return NO;
  830. }
  831. #elif TARGET_OS_OSX
  832. if (!_currentOptions.presentingWindow) {
  833. return NO;
  834. }
  835. #endif // TARGET_OS_OSX
  836. if (!_currentAuthorizationFlow) {
  837. return NO;
  838. }
  839. _restarting = YES;
  840. [_currentAuthorizationFlow cancel];
  841. _currentAuthorizationFlow = nil;
  842. _restarting = NO;
  843. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  844. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  845. // so we need to wait until the previous presentation is completely gone to ensure the right
  846. // anchor window is used here.
  847. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  848. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  849. dispatch_get_main_queue(), ^{
  850. [self signInWithOptions:[self->_currentOptions optionsWithExtraParameters:extraParameters
  851. forContinuation:YES]];
  852. });
  853. return YES;
  854. }
  855. #pragma mark - Key-Value Observing
  856. // Override |NSObject(NSKeyValueObservingCustomization)| method in order to provide custom KVO
  857. // notifications for the |currentUser| property.
  858. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  859. if ([key isEqual:NSStringFromSelector(@selector(currentUser))]) {
  860. return NO;
  861. }
  862. return [super automaticallyNotifiesObserversForKey:key];
  863. }
  864. #pragma mark - Helpers
  865. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  866. if (errorString == nil) {
  867. errorString = @"Unknown error";
  868. }
  869. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  870. return [NSError errorWithDomain:kGIDSignInErrorDomain
  871. code:code
  872. userInfo:errorDict];
  873. }
  874. + (BOOL)isOperatingSystemAtLeast9 {
  875. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  876. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  877. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  878. }
  879. // Asserts the parameters being valid.
  880. - (void)assertValidParameters {
  881. if (![_currentOptions.configuration.clientID length]) {
  882. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  883. [NSException raise:NSInvalidArgumentException
  884. format:@"You must specify |clientID| in |GIDConfiguration|"];
  885. }
  886. }
  887. // Assert that the presenting view controller has been set.
  888. - (void)assertValidPresentingViewController {
  889. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  890. if (!_currentOptions.presentingViewController) {
  891. #elif TARGET_OS_OSX
  892. if (!_currentOptions.presentingWindow) {
  893. #endif // TARGET_OS_OSX
  894. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  895. [NSException raise:NSInvalidArgumentException
  896. format:@"|presentingViewController| must be set."];
  897. }
  898. }
  899. // Checks whether or not this is the first time the app runs.
  900. - (BOOL)isFreshInstall {
  901. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  902. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  903. return NO;
  904. }
  905. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  906. return YES;
  907. }
  908. - (void)removeAllKeychainEntries {
  909. [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:kGTMAppAuthKeychainName
  910. useDataProtectionKeychain:YES];
  911. }
  912. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  913. GTMAppAuthFetcherAuthorization *authorization =
  914. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  915. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  916. toKeychainForName:kGTMAppAuthKeychainName
  917. useDataProtectionKeychain:YES];
  918. }
  919. - (OIDAuthState *)loadAuthState {
  920. GTMAppAuthFetcherAuthorization *authorization =
  921. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName
  922. useDataProtectionKeychain:YES];
  923. return authorization.authState;
  924. }
  925. // Generates user profile from OIDIDToken.
  926. - (GIDProfileData *)profileDataWithIDToken:(OIDIDToken *)idToken {
  927. if (!idToken ||
  928. !idToken.claims[kBasicProfilePictureKey] ||
  929. !idToken.claims[kBasicProfileNameKey] ||
  930. !idToken.claims[kBasicProfileGivenNameKey] ||
  931. !idToken.claims[kBasicProfileFamilyNameKey]) {
  932. return nil;
  933. }
  934. return [[GIDProfileData alloc]
  935. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  936. name:idToken.claims[kBasicProfileNameKey]
  937. givenName:idToken.claims[kBasicProfileGivenNameKey]
  938. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  939. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  940. }
  941. // Set currentUser making appropriate KVO calls.
  942. - (void)setCurrentUserWithKVO:(GIDGoogleUser *_Nullable)user {
  943. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  944. _currentUser = user;
  945. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  946. }
  947. @end
  948. NS_ASSUME_NONNULL_END