GIDSignIn.m 43 KB

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