GIDSignIn.m 37 KB

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