GIDSignIn.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDSignIn.h"
  15. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  16. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDAuthentication.h"
  17. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDGoogleUser.h"
  18. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDProfileData.h"
  19. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  20. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  21. #import "GoogleSignIn/Sources/GIDCallbackQueue.h"
  22. #import "GoogleSignIn/Sources/GIDScopes.h"
  23. #import "GoogleSignIn/Sources/GIDSignInCallbackSchemes.h"
  24. #import "GoogleSignIn/Sources/GIDAuthStateMigration.h"
  25. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  26. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  27. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  28. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  29. #ifdef SWIFT_PACKAGE
  30. @import AppAuth;
  31. @import GTMAppAuth;
  32. @import GTMSessionFetcherCore;
  33. #else
  34. #import <AppAuth/OIDAuthState.h>
  35. #import <AppAuth/OIDAuthorizationRequest.h>
  36. #import <AppAuth/OIDAuthorizationResponse.h>
  37. #import <AppAuth/OIDAuthorizationService.h>
  38. #import <AppAuth/OIDError.h>
  39. #import <AppAuth/OIDExternalUserAgentSession.h>
  40. #import <AppAuth/OIDIDToken.h>
  41. #import <AppAuth/OIDResponseTypes.h>
  42. #import <AppAuth/OIDServiceConfiguration.h>
  43. #import <AppAuth/OIDTokenRequest.h>
  44. #import <AppAuth/OIDTokenResponse.h>
  45. #import <AppAuth/OIDURLQueryComponent.h>
  46. #import <AppAuth/OIDAuthorizationService+IOS.h>
  47. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  48. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  49. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  50. #endif
  51. NS_ASSUME_NONNULL_BEGIN
  52. // The name of the query parameter used for logging the restart of auth from EMM callback.
  53. static NSString *const kEMMRestartAuthParameter = @"emmres";
  54. // The URL template for the authorization endpoint.
  55. static NSString *const kAuthorizationURLTemplate = @"https://%@/o/oauth2/v2/auth";
  56. // The URL template for the token endpoint.
  57. static NSString *const kTokenURLTemplate = @"https://%@/token";
  58. // The URL template for the URL to get user info.
  59. static NSString *const kUserInfoURLTemplate = @"https://%@/oauth2/v3/userinfo?access_token=%@";
  60. // The URL template for the URL to revoke the token.
  61. static NSString *const kRevokeTokenURLTemplate = @"https://%@/o/oauth2/revoke?token=%@";
  62. // Expected path in the URL scheme to be handled.
  63. static NSString *const kBrowserCallbackPath = @"/oauth2callback";
  64. // Expected path for EMM callback.
  65. static NSString *const kEMMCallbackPath = @"/emmcallback";
  66. // The EMM support version
  67. static NSString *const kEMMVersion = @"1";
  68. // The error code for Google Identity.
  69. NSString *const kGIDSignInErrorDomain = @"com.google.GIDSignIn";
  70. // Keychain constants for saving state in the authentication flow.
  71. static NSString *const kGTMAppAuthKeychainName = @"auth";
  72. // Basic profile (Fat ID Token / userinfo endpoint) keys
  73. static NSString *const kBasicProfileEmailKey = @"email";
  74. static NSString *const kBasicProfilePictureKey = @"picture";
  75. static NSString *const kBasicProfileNameKey = @"name";
  76. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  77. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  78. // Parameters in the callback URL coming back from browser.
  79. static NSString *const kAuthorizationCodeKeyName = @"code";
  80. static NSString *const kOAuth2ErrorKeyName = @"error";
  81. static NSString *const kOAuth2AccessDenied = @"access_denied";
  82. static NSString *const kEMMPasscodeInfoRequiredKeyName = @"emm_passcode_info_required";
  83. // Error string for unavailable keychain.
  84. static NSString *const kKeychainError = @"keychain error";
  85. // Error string for user cancelations.
  86. static NSString *const kUserCanceledError = @"The user canceled the sign-in flow.";
  87. // User preference key to detect fresh install of the app.
  88. static NSString *const kAppHasRunBeforeKey = @"GID_AppHasRunBefore";
  89. // Maximum retry interval in seconds for the fetcher.
  90. static const NSTimeInterval kFetcherMaxRetryInterval = 15.0;
  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. // Extra parameters for the token exchange endpoint.
  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. // The callback queue used for authentication flow.
  100. @interface GIDAuthFlow : GIDCallbackQueue
  101. @property(nonatomic, strong, nullable) OIDAuthState *authState;
  102. @property(nonatomic, strong, nullable) NSError *error;
  103. @property(nonatomic, copy, nullable) NSString *emmSupport;
  104. @property(nonatomic, nullable) GIDProfileData *profileData;
  105. @end
  106. @implementation GIDAuthFlow
  107. @end
  108. @implementation GIDSignIn {
  109. // This value is used when sign-in flows are resumed via the handling of a URL. Its value is
  110. // set when a sign-in flow is begun via |signInWithOptions:| when the options passed don't
  111. // represent a sign in continuation.
  112. GIDSignInInternalOptions *_currentOptions;
  113. // Scheme information for this sign-in instance.
  114. GIDSignInCallbackSchemes *_schemes;
  115. // AppAuth configuration object.
  116. OIDServiceConfiguration *_configuration;
  117. // AppAuth external user-agent session state.
  118. id<OIDExternalUserAgentSession> _currentAuthorizationFlow;
  119. }
  120. #pragma mark - Public methods
  121. + (GIDSignIn *)sharedInstance {
  122. static dispatch_once_t once;
  123. static GIDSignIn *sharedInstance;
  124. dispatch_once(&once, ^{
  125. sharedInstance = [[self alloc] initPrivate];
  126. });
  127. return sharedInstance;
  128. }
  129. // Invoked when the app delegate receives a callback at |application:openURL:options:| or
  130. // |application:openURL:sourceApplication:annotation|.
  131. - (BOOL)handleURL:(NSURL *)url {
  132. // Check if the callback path matches the expected one for a URL from Safari/Chrome/SafariVC.
  133. if ([url.path isEqual:kBrowserCallbackPath]) {
  134. if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) {
  135. _currentAuthorizationFlow = nil;
  136. return YES;
  137. }
  138. return NO;
  139. }
  140. // Check if the callback path matches the expected one for a URL from Google Device Policy app.
  141. if ([url.path isEqual:kEMMCallbackPath]) {
  142. return [self handleDevicePolicyAppURL:url];
  143. }
  144. return NO;
  145. }
  146. - (BOOL)hasPreviousSignIn {
  147. if ([_currentUser.authentication.authState isAuthorized]) {
  148. return YES;
  149. }
  150. OIDAuthState *authState = [self loadAuthState];
  151. return [authState isAuthorized];
  152. }
  153. - (nullable GIDGoogleUser *)restoredGoogleUserFromPreviousSignIn {
  154. OIDAuthState *authState = [self loadAuthState];
  155. if (!authState) {
  156. return nil;
  157. }
  158. return [[GIDGoogleUser alloc] initWithAuthState:authState
  159. profileData:nil];
  160. }
  161. - (void)restorePreviousSignIn {
  162. [self signInWithOptions:[GIDSignInInternalOptions silentOptions]];
  163. }
  164. // Authenticates the user by first searching the keychain, then attempting to retrieve the refresh
  165. // token from a Google Sign In app, and finally through the standard OAuth 2.0 web flow.
  166. - (void)signIn {
  167. [self signInWithOptions:[GIDSignInInternalOptions defaultOptions]];
  168. }
  169. - (void)signOut {
  170. [self signOutWithUser:_currentUser];
  171. }
  172. - (void)disconnect {
  173. [self disconnectWithUser:_currentUser];
  174. }
  175. #pragma mark - Custom getters and setters
  176. - (void)setClientID:(nullable NSString *)clientID {
  177. if (![_clientID isEqualToString:clientID]) {
  178. [self willChangeValueForKey:NSStringFromSelector(@selector(clientID))];
  179. _clientID = [clientID copy];
  180. _schemes = [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:_clientID];
  181. [self didChangeValueForKey:NSStringFromSelector(@selector(clientID))];
  182. }
  183. }
  184. - (void)setScopes:(nullable NSArray<NSString *> *)scopes {
  185. scopes = [scopes sortedArrayUsingSelector:@selector(compare:)];
  186. if (![_scopes isEqualToArray:scopes]) {
  187. _scopes = [[NSArray alloc] initWithArray:scopes copyItems:YES];
  188. }
  189. }
  190. - (void)setShouldFetchBasicProfile:(BOOL)shouldFetchBasicProfile {
  191. shouldFetchBasicProfile = !!shouldFetchBasicProfile;
  192. if (_shouldFetchBasicProfile != shouldFetchBasicProfile) {
  193. _shouldFetchBasicProfile = shouldFetchBasicProfile;
  194. }
  195. }
  196. - (void)setHostedDomain:(nullable NSString *)hostedDomain {
  197. if (!(_hostedDomain == hostedDomain || [_hostedDomain isEqualToString:hostedDomain])) {
  198. _hostedDomain = [hostedDomain copy];
  199. }
  200. }
  201. #pragma mark - Private methods
  202. - (id)initPrivate {
  203. self = [super init];
  204. if (self) {
  205. // Default scope settings.
  206. _scopes = @[];
  207. _shouldFetchBasicProfile = YES;
  208. // Check to see if the 3P app is being run for the first time after a fresh install.
  209. BOOL isFreshInstall = [self isFreshInstall];
  210. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  211. if (isFreshInstall) {
  212. [self removeAllKeychainEntries];
  213. }
  214. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  215. [GIDSignInPreferences googleAuthorizationServer]];
  216. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  217. [GIDSignInPreferences googleTokenServer]];
  218. _configuration = [[OIDServiceConfiguration alloc]
  219. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  220. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  221. // Perform migration of auth state from old versions of the SDK if needed.
  222. [GIDAuthStateMigration migrateIfNeededWithTokenURL:_configuration.tokenEndpoint
  223. callbackPath:kBrowserCallbackPath
  224. keychainName:kGTMAppAuthKeychainName
  225. isFreshInstall:isFreshInstall];
  226. }
  227. return self;
  228. }
  229. // Does sanity check for parameters and then authenticates if necessary.
  230. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  231. // Options for continuation are not the options we want to cache. The purpose of caching the
  232. // options in the first place is to provide continuation flows with a starting place from which to
  233. // derive suitable options for the continuation!
  234. if (!options.continuation) {
  235. _currentOptions = options;
  236. }
  237. // Explicitly throw exception for missing client ID (and scopes) here. This must come before
  238. // scheme check because schemes rely on reverse client IDs.
  239. [self assertValidParameters];
  240. if (options.interactive) {
  241. [self assertValidPresentingViewController];
  242. }
  243. // If the application does not support the required URL schemes tell the developer so.
  244. if (options.interactive) {
  245. NSArray<NSString *> *unsupportedSchemes = [_schemes unsupportedSchemes];
  246. if (unsupportedSchemes.count != 0) {
  247. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  248. [NSException raise:NSInvalidArgumentException
  249. format:@"Your app is missing support for the following URL schemes: %@",
  250. [unsupportedSchemes componentsJoinedByString:@", "]];
  251. }
  252. }
  253. // If this is a non-interactive flow, use cached authentication if possible.
  254. if (!options.interactive && _currentUser.authentication) {
  255. [_currentUser.authentication doWithFreshTokens:^(GIDAuthentication *unused, NSError *error) {
  256. if (error) {
  257. [self authenticateWithOptions:options];
  258. } else {
  259. [_delegate signIn:self didSignInForUser:_currentUser withError:nil];
  260. }
  261. }];
  262. } else {
  263. [self authenticateWithOptions:options];
  264. }
  265. }
  266. # pragma mark - Authentication flow
  267. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  268. NSString *emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  269. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  270. if (_serverClientID) {
  271. additionalParameters[kAudienceParameter] = _serverClientID;
  272. }
  273. if (_loginHint) {
  274. additionalParameters[@"login_hint"] = _loginHint;
  275. }
  276. if (_hostedDomain) {
  277. additionalParameters[@"hd"] = _hostedDomain;
  278. }
  279. [additionalParameters addEntriesFromDictionary:
  280. [GIDAuthentication parametersWithParameters:options.extraParams
  281. emmSupport:emmSupport
  282. isPasscodeInfoRequired:NO]];
  283. OIDAuthorizationRequest *request =
  284. [[OIDAuthorizationRequest alloc] initWithConfiguration:_configuration
  285. clientId:_clientID
  286. scopes:[self adjustedScopes]
  287. redirectURL:[self redirectURI]
  288. responseType:OIDResponseTypeCode
  289. additionalParameters:additionalParameters];
  290. _currentAuthorizationFlow = [OIDAuthorizationService
  291. presentAuthorizationRequest:request
  292. presentingViewController:_presentingViewController
  293. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  294. NSError *_Nullable error) {
  295. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  296. authFlow.emmSupport = emmSupport;
  297. if (authorizationResponse) {
  298. if (authorizationResponse.authorizationCode.length) {
  299. authFlow.authState = [[OIDAuthState alloc]
  300. initWithAuthorizationResponse:authorizationResponse];
  301. // perform auth code exchange
  302. [self maybeFetchToken:authFlow fallback:nil];
  303. } else {
  304. // There was a failure, convert to appropriate error code.
  305. NSString *errorString;
  306. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  307. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  308. if (authFlow.emmSupport) {
  309. [authFlow wait];
  310. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  311. handleErrorFromResponse:params
  312. completion:^{
  313. [authFlow next];
  314. }];
  315. if (isEMMError) {
  316. errorCode = kGIDSignInErrorCodeEMM;
  317. }
  318. }
  319. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  320. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  321. errorCode = kGIDSignInErrorCodeCanceled;
  322. }
  323. authFlow.error = [self errorWithString:errorString code:errorCode];
  324. }
  325. } else {
  326. NSString *errorString = [error localizedDescription];
  327. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  328. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  329. // The user has canceled the flow at the iOS modal dialog.
  330. errorString = kUserCanceledError;
  331. errorCode = kGIDSignInErrorCodeCanceled;
  332. }
  333. authFlow.error = [self errorWithString:errorString code:errorCode];
  334. }
  335. [self addDecodeIdTokenCallback:authFlow];
  336. [self addSaveAuthCallback:authFlow];
  337. [self addCallDelegateCallback:authFlow];
  338. }];
  339. }
  340. // Perform authentication with the provided options.
  341. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  342. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  343. if (options.interactive) {
  344. [self authenticateInteractivelyWithOptions:options];
  345. return;
  346. }
  347. // Try retrieving an authorization object from the keychain.
  348. OIDAuthState *authState = [self loadAuthState];
  349. if (![authState isAuthorized]) {
  350. // No valid auth in keychain, per documentation/spec, notify delegate of failure.
  351. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  352. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  353. userInfo:nil];
  354. [_delegate signIn:self didSignInForUser:nil withError:error];
  355. return;
  356. }
  357. // Complete the auth flow using saved auth in keychain.
  358. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  359. authFlow.authState = authState;
  360. [self maybeFetchToken:authFlow fallback:options.interactive ? ^() {
  361. [self authenticateInteractivelyWithOptions:options];
  362. } : nil];
  363. [self addDecodeIdTokenCallback:authFlow];
  364. [self addSaveAuthCallback:authFlow];
  365. [self addCallDelegateCallback:authFlow];
  366. }
  367. // Fetches the access token if necessary as part of the auth flow. If |fallback|
  368. // is provided, call it instead of continuing the auth flow in case of error.
  369. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow fallback:(nullable void (^)(void))fallback {
  370. OIDAuthState *authState = authFlow.authState;
  371. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  372. if (authFlow.error ||
  373. (authState.lastTokenResponse.accessToken &&
  374. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  375. kMinimumRestoredAccessTokenTimeToExpire)) {
  376. return;
  377. }
  378. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  379. if (_serverClientID) {
  380. additionalParameters[kAudienceParameter] = _serverClientID;
  381. }
  382. if (_openIDRealm) {
  383. additionalParameters[kOpenIDRealmParameter] = _openIDRealm;
  384. }
  385. NSDictionary<NSString *, NSObject *> *params =
  386. authState.lastAuthorizationResponse.additionalParameters;
  387. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  388. [additionalParameters addEntriesFromDictionary:
  389. [GIDAuthentication parametersWithParameters:@{}
  390. emmSupport:authFlow.emmSupport
  391. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  392. OIDTokenRequest *tokenRequest;
  393. if (!authState.lastTokenResponse.accessToken &&
  394. authState.lastAuthorizationResponse.authorizationCode) {
  395. tokenRequest = [authState.lastAuthorizationResponse
  396. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  397. } else {
  398. [additionalParameters
  399. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  400. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  401. }
  402. [authFlow wait];
  403. [OIDAuthorizationService
  404. performTokenRequest:tokenRequest
  405. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  406. NSError *_Nullable error) {
  407. [authState updateWithTokenResponse:tokenResponse error:error];
  408. authFlow.error = error;
  409. if (!tokenResponse.accessToken || error) {
  410. if (fallback) {
  411. [authFlow reset];
  412. fallback();
  413. return;
  414. }
  415. }
  416. if (authFlow.emmSupport) {
  417. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *error) {
  418. authFlow.error = error;
  419. [authFlow next];
  420. }];
  421. } else {
  422. [authFlow next];
  423. }
  424. }];
  425. }
  426. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  427. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  428. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  429. [authFlow addCallback:^() {
  430. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  431. OIDAuthState *authState = handlerAuthFlow.authState;
  432. if (authState && !handlerAuthFlow.error) {
  433. if (![self saveAuthState:authState]) {
  434. handlerAuthFlow.error = [self errorWithString:kKeychainError
  435. code:kGIDSignInErrorCodeKeychain];
  436. return;
  437. }
  438. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  439. _currentUser = [[GIDGoogleUser alloc] initWithAuthState:authState
  440. profileData:handlerAuthFlow.profileData];
  441. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  442. }
  443. }];
  444. }
  445. // Adds a callback to the auth flow to extract user data from the ID token where available and
  446. // make a userinfo request if necessary.
  447. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  448. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  449. [authFlow addCallback:^() {
  450. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  451. OIDAuthState *authState = handlerAuthFlow.authState;
  452. if (!authState || handlerAuthFlow.error) {
  453. return;
  454. }
  455. OIDIDToken *idToken =
  456. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  457. if (idToken) {
  458. if (_shouldFetchBasicProfile) {
  459. // If the picture and name fields are present in the ID token, use them, otherwise make
  460. // a userinfo request to fetch them.
  461. if (idToken.claims[kBasicProfilePictureKey] &&
  462. idToken.claims[kBasicProfileNameKey] &&
  463. idToken.claims[kBasicProfileGivenNameKey] &&
  464. idToken.claims[kBasicProfileFamilyNameKey]) {
  465. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  466. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  467. name:idToken.claims[kBasicProfileNameKey]
  468. givenName:idToken.claims[kBasicProfileGivenNameKey]
  469. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  470. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  471. } else {
  472. [handlerAuthFlow wait];
  473. NSURL *infoURL = [NSURL URLWithString:
  474. [NSString stringWithFormat:kUserInfoURLTemplate,
  475. [GIDSignInPreferences googleUserInfoServer],
  476. authState.lastTokenResponse.accessToken]];
  477. [self startFetchURL:infoURL
  478. fromAuthState:authState
  479. withComment:@"GIDSignIn: fetch basic profile info"
  480. withCompletionHandler:^(NSData *data, NSError *error) {
  481. if (data && !error) {
  482. NSError *jsonDeserializationError;
  483. NSDictionary<NSString *, NSString *> *profileDict =
  484. [NSJSONSerialization JSONObjectWithData:data
  485. options:NSJSONReadingMutableContainers
  486. error:&jsonDeserializationError];
  487. if (profileDict) {
  488. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  489. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  490. name:profileDict[kBasicProfileNameKey]
  491. givenName:profileDict[kBasicProfileGivenNameKey]
  492. familyName:profileDict[kBasicProfileFamilyNameKey]
  493. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  494. }
  495. }
  496. if (error) {
  497. handlerAuthFlow.error = error;
  498. }
  499. [handlerAuthFlow next];
  500. }];
  501. }
  502. }
  503. }
  504. }];
  505. }
  506. // Adds a callback to the auth flow to call the sign-in delegate.
  507. - (void)addCallDelegateCallback:(GIDAuthFlow *)authFlow {
  508. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  509. [authFlow addCallback:^() {
  510. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  511. [_delegate signIn:self didSignInForUser:_currentUser withError:handlerAuthFlow.error];
  512. }];
  513. }
  514. - (void)startFetchURL:(NSURL *)URL
  515. fromAuthState:(OIDAuthState *)authState
  516. withComment:(NSString *)comment
  517. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  518. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  519. GTMSessionFetcher *fetcher;
  520. GTMAppAuthFetcherAuthorization *authorization =
  521. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  522. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  523. if (fetcherService) {
  524. fetcher = [fetcherService fetcherWithRequest:request];
  525. } else {
  526. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  527. }
  528. fetcher.retryEnabled = YES;
  529. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  530. fetcher.comment = comment;
  531. [fetcher beginFetchWithCompletionHandler:handler];
  532. }
  533. - (void)didDisconnectWithUser:(GIDGoogleUser *)user
  534. error:(nullable NSError *)error {
  535. if ([_delegate respondsToSelector:@selector(signIn:didDisconnectWithUser:withError:)]) {
  536. [_delegate signIn:self didDisconnectWithUser:user withError:error];
  537. }
  538. }
  539. // Parse incoming URL from the Google Device Policy app.
  540. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  541. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  542. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  543. NSObject<NSCopying> *actionParam = params[@"action"];
  544. NSString *actionString =
  545. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  546. if (![@"restart_auth" isEqualToString:actionString]) {
  547. return NO;
  548. }
  549. if (!_presentingViewController) {
  550. return NO;
  551. }
  552. if (!_currentAuthorizationFlow) {
  553. return NO;
  554. }
  555. [_currentAuthorizationFlow cancel];
  556. _currentAuthorizationFlow = nil;
  557. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  558. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  559. // so we need to wait until the previous presentation is completely gone to ensure the right
  560. // anchor window is used here.
  561. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  562. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  563. dispatch_get_main_queue(), ^{
  564. [self signInWithOptions:[_currentOptions optionsWithExtraParameters:extraParameters
  565. forContinuation:YES]];
  566. });
  567. return YES;
  568. }
  569. #pragma mark - Key-Value Observing
  570. // Override |NSObject(NSKeyValueObservingCustomization)| method in order to provide custom KVO
  571. // notifications for |clientID| and |currentUser| properties.
  572. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  573. if ([key isEqual:NSStringFromSelector(@selector(clientID))] ||
  574. [key isEqual:NSStringFromSelector(@selector(currentUser))]) {
  575. return NO;
  576. }
  577. return [super automaticallyNotifiesObserversForKey:key];
  578. }
  579. #pragma mark - Helpers
  580. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  581. if (errorString == nil) {
  582. errorString = @"Unknown error";
  583. }
  584. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  585. return [NSError errorWithDomain:kGIDSignInErrorDomain
  586. code:code
  587. userInfo:errorDict];
  588. }
  589. + (BOOL)isOperatingSystemAtLeast9 {
  590. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  591. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  592. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  593. }
  594. // Asserts the parameters being valid.
  595. - (void)assertValidParameters {
  596. if (![_clientID length]) {
  597. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  598. [NSException raise:NSInvalidArgumentException
  599. format:@"You must specify |clientID| for |GIDSignIn|"];
  600. }
  601. if ([self adjustedScopes].count == 0) {
  602. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  603. [NSException raise:NSInvalidArgumentException
  604. format:@"You must specify |shouldFetchBasicProfile| or |scopes| for |GIDSignIn|"];
  605. }
  606. }
  607. // Assert that the UI Delegate has been set.
  608. - (void)assertValidPresentingViewController {
  609. if (!_presentingViewController) {
  610. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  611. [NSException raise:NSInvalidArgumentException format:@"presentingViewController must be set."];
  612. }
  613. }
  614. // Checks whether or not this is the first time the app runs.
  615. - (BOOL)isFreshInstall {
  616. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  617. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  618. return NO;
  619. }
  620. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  621. return YES;
  622. }
  623. - (void)removeAllKeychainEntries {
  624. [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:kGTMAppAuthKeychainName];
  625. }
  626. // Clears the saved authentication object and other user information.
  627. - (void)clearAuthentication {
  628. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  629. _currentUser = nil;
  630. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  631. }
  632. // Adds basic profile scopes to |scopes| if |shouldFetchBasicProfile| is set.
  633. - (NSArray *)adjustedScopes {
  634. NSArray<NSString *> *adjustedScopes = _scopes;
  635. if (_shouldFetchBasicProfile) {
  636. adjustedScopes = [GIDScopes scopesWithBasicProfile:adjustedScopes];
  637. }
  638. return adjustedScopes;
  639. }
  640. - (NSURL *)redirectURI {
  641. NSString *scheme = [_schemes clientIdentifierScheme];
  642. return [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@", scheme, kBrowserCallbackPath]];
  643. }
  644. - (void)signOutWithUser:(GIDGoogleUser *)user {
  645. // TODO(petea): Respond to user parameter.
  646. // TODO(petea): Mark user as signed out rather than removing auth from keychain.
  647. [self clearAuthentication];
  648. [self removeAllKeychainEntries];
  649. }
  650. - (void)disconnectWithUser:(GIDGoogleUser *)user {
  651. OIDAuthState *authState = user.authentication.authState;
  652. if (!authState) {
  653. // Even the user is not signed in right now, we still need to remove any token saved in the
  654. // keychain.
  655. authState = [self loadAuthState];
  656. }
  657. // Either access or refresh token would work, but we won't have access token if the auth is
  658. // retrieved from keychain.
  659. NSString *token = authState.lastTokenResponse.accessToken;
  660. if (!token) {
  661. token = authState.lastTokenResponse.refreshToken;
  662. }
  663. if (!token) {
  664. [self removeAllKeychainEntries];
  665. // Nothing to do here, consider the operation successful.
  666. [self didDisconnectWithUser:user error:nil];
  667. return;
  668. }
  669. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  670. [GIDSignInPreferences googleAuthorizationServer], token];
  671. // Append logging parameter
  672. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@",
  673. revokeURLString,
  674. kSDKVersionLoggingParameter,
  675. GIDVersion()];
  676. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  677. [self startFetchURL:revokeURL
  678. fromAuthState:authState
  679. withComment:@"GIDSignIn: revoke tokens"
  680. withCompletionHandler:^(NSData *data, NSError *error) {
  681. // Revoking an already revoked token seems always successful, which saves the trouble here for
  682. // us.
  683. if (error) {
  684. [self didDisconnectWithUser:user error:error];
  685. } else {
  686. [self signOutWithUser:user];
  687. [self didDisconnectWithUser:user error:nil];
  688. }
  689. }];
  690. }
  691. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  692. GTMAppAuthFetcherAuthorization *authorization =
  693. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  694. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  695. toKeychainForName:kGTMAppAuthKeychainName];
  696. }
  697. - (OIDAuthState *)loadAuthState {
  698. GTMAppAuthFetcherAuthorization *authorization =
  699. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName];
  700. return authorization.authState;
  701. }
  702. @end
  703. NS_ASSUME_NONNULL_END