GIDSignIn.m 44 KB

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