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