GIDSignIn.m 35 KB

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