GIDSignIn.m 43 KB

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