GIDSignIn.m 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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. - (void)restorePreviousSignIn {
  154. [self signInWithOptions:[GIDSignInInternalOptions silentOptions]];
  155. }
  156. // Authenticates the user by first searching the keychain, then attempting to retrieve the refresh
  157. // token from a Google Sign In app, and finally through the standard OAuth 2.0 web flow.
  158. - (void)signIn {
  159. [self signInWithOptions:[GIDSignInInternalOptions defaultOptions]];
  160. }
  161. - (void)signOut {
  162. [self signOutWithUser:_currentUser];
  163. }
  164. - (void)disconnect {
  165. [self disconnectWithUser:_currentUser];
  166. }
  167. #pragma mark - Custom getters and setters
  168. - (void)setClientID:(nullable NSString *)clientID {
  169. if (![_clientID isEqualToString:clientID]) {
  170. [self willChangeValueForKey:NSStringFromSelector(@selector(clientID))];
  171. _clientID = [clientID copy];
  172. _schemes = [[GIDSignInCallbackSchemes alloc] initWithClientIdentifier:_clientID];
  173. [self didChangeValueForKey:NSStringFromSelector(@selector(clientID))];
  174. }
  175. }
  176. - (void)setScopes:(nullable NSArray<NSString *> *)scopes {
  177. scopes = [scopes sortedArrayUsingSelector:@selector(compare:)];
  178. if (![_scopes isEqualToArray:scopes]) {
  179. _scopes = [[NSArray alloc] initWithArray:scopes copyItems:YES];
  180. }
  181. }
  182. - (void)setShouldFetchBasicProfile:(BOOL)shouldFetchBasicProfile {
  183. shouldFetchBasicProfile = !!shouldFetchBasicProfile;
  184. if (_shouldFetchBasicProfile != shouldFetchBasicProfile) {
  185. _shouldFetchBasicProfile = shouldFetchBasicProfile;
  186. }
  187. }
  188. - (void)setHostedDomain:(nullable NSString *)hostedDomain {
  189. if (!(_hostedDomain == hostedDomain || [_hostedDomain isEqualToString:hostedDomain])) {
  190. _hostedDomain = [hostedDomain copy];
  191. }
  192. }
  193. #pragma mark - Private methods
  194. - (id)initPrivate {
  195. self = [super init];
  196. if (self) {
  197. // Default scope settings.
  198. _scopes = @[];
  199. _shouldFetchBasicProfile = YES;
  200. // Check to see if the 3P app is being run for the first time after a fresh install.
  201. BOOL isFreshInstall = [self isFreshInstall];
  202. // If this is a fresh install, ensure that any pre-existing keychain data is purged.
  203. if (isFreshInstall) {
  204. [self removeAllKeychainEntries];
  205. }
  206. NSString *authorizationEnpointURL = [NSString stringWithFormat:kAuthorizationURLTemplate,
  207. [GIDSignInPreferences googleAuthorizationServer]];
  208. NSString *tokenEndpointURL = [NSString stringWithFormat:kTokenURLTemplate,
  209. [GIDSignInPreferences googleTokenServer]];
  210. _configuration = [[OIDServiceConfiguration alloc]
  211. initWithAuthorizationEndpoint:[NSURL URLWithString:authorizationEnpointURL]
  212. tokenEndpoint:[NSURL URLWithString:tokenEndpointURL]];
  213. // Perform migration of auth state from old versions of the SDK if needed.
  214. [GIDAuthStateMigration migrateIfNeededWithTokenURL:_configuration.tokenEndpoint
  215. callbackPath:kBrowserCallbackPath
  216. keychainName:kGTMAppAuthKeychainName
  217. isFreshInstall:isFreshInstall];
  218. }
  219. return self;
  220. }
  221. // Does sanity check for parameters and then authenticates if necessary.
  222. - (void)signInWithOptions:(GIDSignInInternalOptions *)options {
  223. // Options for continuation are not the options we want to cache. The purpose of caching the
  224. // options in the first place is to provide continuation flows with a starting place from which to
  225. // derive suitable options for the continuation!
  226. if (!options.continuation) {
  227. _currentOptions = options;
  228. }
  229. // Explicitly throw exception for missing client ID (and scopes) here. This must come before
  230. // scheme check because schemes rely on reverse client IDs.
  231. [self assertValidParameters];
  232. if (options.interactive) {
  233. [self assertValidPresentingViewController];
  234. }
  235. // If the application does not support the required URL schemes tell the developer so.
  236. if (options.interactive) {
  237. NSArray<NSString *> *unsupportedSchemes = [_schemes unsupportedSchemes];
  238. if (unsupportedSchemes.count != 0) {
  239. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  240. [NSException raise:NSInvalidArgumentException
  241. format:@"Your app is missing support for the following URL schemes: %@",
  242. [unsupportedSchemes componentsJoinedByString:@", "]];
  243. }
  244. }
  245. // If this is a non-interactive flow, use cached authentication if possible.
  246. if (!options.interactive && _currentUser.authentication) {
  247. [_currentUser.authentication doWithFreshTokens:^(GIDAuthentication *unused, NSError *error) {
  248. if (error) {
  249. [self authenticateWithOptions:options];
  250. } else {
  251. [_delegate signIn:self didSignInForUser:_currentUser withError:nil];
  252. }
  253. }];
  254. } else {
  255. [self authenticateWithOptions:options];
  256. }
  257. }
  258. # pragma mark - Authentication flow
  259. - (void)authenticateInteractivelyWithOptions:(GIDSignInInternalOptions *)options {
  260. NSString *emmSupport = [[self class] isOperatingSystemAtLeast9] ? kEMMVersion : nil;
  261. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  262. if (_serverClientID) {
  263. additionalParameters[kAudienceParameter] = _serverClientID;
  264. }
  265. if (_loginHint) {
  266. additionalParameters[@"login_hint"] = _loginHint;
  267. }
  268. if (_hostedDomain) {
  269. additionalParameters[@"hd"] = _hostedDomain;
  270. }
  271. [additionalParameters addEntriesFromDictionary:
  272. [GIDAuthentication parametersWithParameters:options.extraParams
  273. emmSupport:emmSupport
  274. isPasscodeInfoRequired:NO]];
  275. OIDAuthorizationRequest *request =
  276. [[OIDAuthorizationRequest alloc] initWithConfiguration:_configuration
  277. clientId:_clientID
  278. scopes:[self adjustedScopes]
  279. redirectURL:[self redirectURI]
  280. responseType:OIDResponseTypeCode
  281. additionalParameters:additionalParameters];
  282. _currentAuthorizationFlow = [OIDAuthorizationService
  283. presentAuthorizationRequest:request
  284. presentingViewController:_presentingViewController
  285. callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse,
  286. NSError *_Nullable error) {
  287. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  288. authFlow.emmSupport = emmSupport;
  289. if (authorizationResponse) {
  290. if (authorizationResponse.authorizationCode.length) {
  291. authFlow.authState = [[OIDAuthState alloc]
  292. initWithAuthorizationResponse:authorizationResponse];
  293. // perform auth code exchange
  294. [self maybeFetchToken:authFlow fallback:nil];
  295. } else {
  296. // There was a failure, convert to appropriate error code.
  297. NSString *errorString;
  298. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  299. NSDictionary<NSString *, NSObject *> *params = authorizationResponse.additionalParameters;
  300. if (authFlow.emmSupport) {
  301. [authFlow wait];
  302. BOOL isEMMError = [[GIDEMMErrorHandler sharedInstance]
  303. handleErrorFromResponse:params
  304. completion:^{
  305. [authFlow next];
  306. }];
  307. if (isEMMError) {
  308. errorCode = kGIDSignInErrorCodeEMM;
  309. }
  310. }
  311. errorString = (NSString *)params[kOAuth2ErrorKeyName];
  312. if ([errorString isEqualToString:kOAuth2AccessDenied]) {
  313. errorCode = kGIDSignInErrorCodeCanceled;
  314. }
  315. authFlow.error = [self errorWithString:errorString code:errorCode];
  316. }
  317. } else {
  318. NSString *errorString = [error localizedDescription];
  319. GIDSignInErrorCode errorCode = kGIDSignInErrorCodeUnknown;
  320. if (error.code == OIDErrorCodeUserCanceledAuthorizationFlow) {
  321. // The user has canceled the flow at the iOS modal dialog.
  322. errorString = kUserCanceledError;
  323. errorCode = kGIDSignInErrorCodeCanceled;
  324. }
  325. authFlow.error = [self errorWithString:errorString code:errorCode];
  326. }
  327. [self addDecodeIdTokenCallback:authFlow];
  328. [self addSaveAuthCallback:authFlow];
  329. [self addCallDelegateCallback:authFlow];
  330. }];
  331. }
  332. // Perform authentication with the provided options.
  333. - (void)authenticateWithOptions:(GIDSignInInternalOptions *)options {
  334. // If this is an interactive flow, we're not going to try to restore any saved auth state.
  335. if (options.interactive) {
  336. [self authenticateInteractivelyWithOptions:options];
  337. return;
  338. }
  339. // Try retrieving an authorization object from the keychain.
  340. OIDAuthState *authState = [self loadAuthState];
  341. if (![authState isAuthorized]) {
  342. // No valid auth in keychain, per documentation/spec, notify delegate of failure.
  343. NSError *error = [NSError errorWithDomain:kGIDSignInErrorDomain
  344. code:kGIDSignInErrorCodeHasNoAuthInKeychain
  345. userInfo:nil];
  346. [_delegate signIn:self didSignInForUser:nil withError:error];
  347. return;
  348. }
  349. // Complete the auth flow using saved auth in keychain.
  350. GIDAuthFlow *authFlow = [[GIDAuthFlow alloc] init];
  351. authFlow.authState = authState;
  352. [self maybeFetchToken:authFlow fallback:options.interactive ? ^() {
  353. [self authenticateInteractivelyWithOptions:options];
  354. } : nil];
  355. [self addDecodeIdTokenCallback:authFlow];
  356. [self addSaveAuthCallback:authFlow];
  357. [self addCallDelegateCallback:authFlow];
  358. }
  359. // Fetches the access token if necessary as part of the auth flow. If |fallback|
  360. // is provided, call it instead of continuing the auth flow in case of error.
  361. - (void)maybeFetchToken:(GIDAuthFlow *)authFlow fallback:(nullable void (^)(void))fallback {
  362. OIDAuthState *authState = authFlow.authState;
  363. // Do nothing if we have an auth flow error or a restored access token that isn't near expiration.
  364. if (authFlow.error ||
  365. (authState.lastTokenResponse.accessToken &&
  366. [authState.lastTokenResponse.accessTokenExpirationDate timeIntervalSinceNow] >
  367. kMinimumRestoredAccessTokenTimeToExpire)) {
  368. return;
  369. }
  370. NSMutableDictionary<NSString *, NSString *> *additionalParameters = [@{} mutableCopy];
  371. if (_serverClientID) {
  372. additionalParameters[kAudienceParameter] = _serverClientID;
  373. }
  374. if (_openIDRealm) {
  375. additionalParameters[kOpenIDRealmParameter] = _openIDRealm;
  376. }
  377. NSDictionary<NSString *, NSObject *> *params =
  378. authState.lastAuthorizationResponse.additionalParameters;
  379. NSString *passcodeInfoRequired = (NSString *)params[kEMMPasscodeInfoRequiredKeyName];
  380. [additionalParameters addEntriesFromDictionary:
  381. [GIDAuthentication parametersWithParameters:@{}
  382. emmSupport:authFlow.emmSupport
  383. isPasscodeInfoRequired:passcodeInfoRequired.length > 0]];
  384. OIDTokenRequest *tokenRequest;
  385. if (!authState.lastTokenResponse.accessToken &&
  386. authState.lastAuthorizationResponse.authorizationCode) {
  387. tokenRequest = [authState.lastAuthorizationResponse
  388. tokenExchangeRequestWithAdditionalParameters:additionalParameters];
  389. } else {
  390. [additionalParameters
  391. addEntriesFromDictionary:authState.lastTokenResponse.request.additionalParameters];
  392. tokenRequest = [authState tokenRefreshRequestWithAdditionalParameters:additionalParameters];
  393. }
  394. [authFlow wait];
  395. [OIDAuthorizationService
  396. performTokenRequest:tokenRequest
  397. callback:^(OIDTokenResponse *_Nullable tokenResponse,
  398. NSError *_Nullable error) {
  399. [authState updateWithTokenResponse:tokenResponse error:error];
  400. authFlow.error = error;
  401. if (!tokenResponse.accessToken || error) {
  402. if (fallback) {
  403. [authFlow reset];
  404. fallback();
  405. return;
  406. }
  407. }
  408. if (authFlow.emmSupport) {
  409. [GIDAuthentication handleTokenFetchEMMError:error completion:^(NSError *error) {
  410. authFlow.error = error;
  411. [authFlow next];
  412. }];
  413. } else {
  414. [authFlow next];
  415. }
  416. }];
  417. }
  418. // Adds a callback to the auth flow to save the auth object to |self| and the keychain as well.
  419. - (void)addSaveAuthCallback:(GIDAuthFlow *)authFlow {
  420. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  421. [authFlow addCallback:^() {
  422. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  423. OIDAuthState *authState = handlerAuthFlow.authState;
  424. if (authState && !handlerAuthFlow.error) {
  425. if (![self saveAuthState:authState]) {
  426. handlerAuthFlow.error = [self errorWithString:kKeychainError
  427. code:kGIDSignInErrorCodeKeychain];
  428. return;
  429. }
  430. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  431. _currentUser = [[GIDGoogleUser alloc] initWithAuthState:authState
  432. profileData:handlerAuthFlow.profileData];
  433. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  434. }
  435. }];
  436. }
  437. // Adds a callback to the auth flow to extract user data from the ID token where available and
  438. // make a userinfo request if necessary.
  439. - (void)addDecodeIdTokenCallback:(GIDAuthFlow *)authFlow {
  440. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  441. [authFlow addCallback:^() {
  442. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  443. OIDAuthState *authState = handlerAuthFlow.authState;
  444. if (!authState || handlerAuthFlow.error) {
  445. return;
  446. }
  447. OIDIDToken *idToken =
  448. [[OIDIDToken alloc] initWithIDTokenString:authState.lastTokenResponse.idToken];
  449. if (idToken) {
  450. if (_shouldFetchBasicProfile) {
  451. // If the picture and name fields are present in the ID token, use them, otherwise make
  452. // a userinfo request to fetch them.
  453. if (idToken.claims[kBasicProfilePictureKey] &&
  454. idToken.claims[kBasicProfileNameKey] &&
  455. idToken.claims[kBasicProfileGivenNameKey] &&
  456. idToken.claims[kBasicProfileFamilyNameKey]) {
  457. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  458. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  459. name:idToken.claims[kBasicProfileNameKey]
  460. givenName:idToken.claims[kBasicProfileGivenNameKey]
  461. familyName:idToken.claims[kBasicProfileFamilyNameKey]
  462. imageURL:[NSURL URLWithString:idToken.claims[kBasicProfilePictureKey]]];
  463. } else {
  464. [handlerAuthFlow wait];
  465. NSURL *infoURL = [NSURL URLWithString:
  466. [NSString stringWithFormat:kUserInfoURLTemplate,
  467. [GIDSignInPreferences googleUserInfoServer],
  468. authState.lastTokenResponse.accessToken]];
  469. [self startFetchURL:infoURL
  470. fromAuthState:authState
  471. withComment:@"GIDSignIn: fetch basic profile info"
  472. withCompletionHandler:^(NSData *data, NSError *error) {
  473. if (data && !error) {
  474. NSError *jsonDeserializationError;
  475. NSDictionary<NSString *, NSString *> *profileDict =
  476. [NSJSONSerialization JSONObjectWithData:data
  477. options:NSJSONReadingMutableContainers
  478. error:&jsonDeserializationError];
  479. if (profileDict) {
  480. handlerAuthFlow.profileData = [[GIDProfileData alloc]
  481. initWithEmail:idToken.claims[kBasicProfileEmailKey]
  482. name:profileDict[kBasicProfileNameKey]
  483. givenName:profileDict[kBasicProfileGivenNameKey]
  484. familyName:profileDict[kBasicProfileFamilyNameKey]
  485. imageURL:[NSURL URLWithString:profileDict[kBasicProfilePictureKey]]];
  486. }
  487. }
  488. if (error) {
  489. handlerAuthFlow.error = error;
  490. }
  491. [handlerAuthFlow next];
  492. }];
  493. }
  494. }
  495. }
  496. }];
  497. }
  498. // Adds a callback to the auth flow to call the sign-in delegate.
  499. - (void)addCallDelegateCallback:(GIDAuthFlow *)authFlow {
  500. __weak GIDAuthFlow *weakAuthFlow = authFlow;
  501. [authFlow addCallback:^() {
  502. GIDAuthFlow *handlerAuthFlow = weakAuthFlow;
  503. [_delegate signIn:self didSignInForUser:_currentUser withError:handlerAuthFlow.error];
  504. }];
  505. }
  506. - (void)startFetchURL:(NSURL *)URL
  507. fromAuthState:(OIDAuthState *)authState
  508. withComment:(NSString *)comment
  509. withCompletionHandler:(void (^)(NSData *, NSError *))handler {
  510. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  511. GTMSessionFetcher *fetcher;
  512. GTMAppAuthFetcherAuthorization *authorization =
  513. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  514. id<GTMSessionFetcherServiceProtocol> fetcherService = authorization.fetcherService;
  515. if (fetcherService) {
  516. fetcher = [fetcherService fetcherWithRequest:request];
  517. } else {
  518. fetcher = [GTMSessionFetcher fetcherWithRequest:request];
  519. }
  520. fetcher.retryEnabled = YES;
  521. fetcher.maxRetryInterval = kFetcherMaxRetryInterval;
  522. fetcher.comment = comment;
  523. [fetcher beginFetchWithCompletionHandler:handler];
  524. }
  525. - (void)didDisconnectWithUser:(GIDGoogleUser *)user
  526. error:(nullable NSError *)error {
  527. if ([_delegate respondsToSelector:@selector(signIn:didDisconnectWithUser:withError:)]) {
  528. [_delegate signIn:self didDisconnectWithUser:user withError:error];
  529. }
  530. }
  531. // Parse incoming URL from the Google Device Policy app.
  532. - (BOOL)handleDevicePolicyAppURL:(NSURL *)url {
  533. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  534. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  535. NSObject<NSCopying> *actionParam = params[@"action"];
  536. NSString *actionString =
  537. [actionParam isKindOfClass:[NSString class]] ? (NSString *)actionParam : nil;
  538. if (![@"restart_auth" isEqualToString:actionString]) {
  539. return NO;
  540. }
  541. if (!_presentingViewController) {
  542. return NO;
  543. }
  544. if (!_currentAuthorizationFlow) {
  545. return NO;
  546. }
  547. [_currentAuthorizationFlow cancel];
  548. _currentAuthorizationFlow = nil;
  549. NSDictionary<NSString *, NSString *> *extraParameters = @{ kEMMRestartAuthParameter : @"1" };
  550. // In iOS 13 the presentation of ASWebAuthenticationSession needs an anchor window,
  551. // so we need to wait until the previous presentation is completely gone to ensure the right
  552. // anchor window is used here.
  553. dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
  554. (int64_t)(kPresentationDelayAfterCancel * NSEC_PER_SEC)),
  555. dispatch_get_main_queue(), ^{
  556. [self signInWithOptions:[_currentOptions optionsWithExtraParameters:extraParameters
  557. forContinuation:YES]];
  558. });
  559. return YES;
  560. }
  561. #pragma mark - Key-Value Observing
  562. // Override |NSObject(NSKeyValueObservingCustomization)| method in order to provide custom KVO
  563. // notifications for |clientID| and |currentUser| properties.
  564. + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
  565. if ([key isEqual:NSStringFromSelector(@selector(clientID))] ||
  566. [key isEqual:NSStringFromSelector(@selector(currentUser))]) {
  567. return NO;
  568. }
  569. return [super automaticallyNotifiesObserversForKey:key];
  570. }
  571. #pragma mark - Helpers
  572. - (NSError *)errorWithString:(NSString *)errorString code:(GIDSignInErrorCode)code {
  573. if (errorString == nil) {
  574. errorString = @"Unknown error";
  575. }
  576. NSDictionary<NSString *, NSString *> *errorDict = @{ NSLocalizedDescriptionKey : errorString };
  577. return [NSError errorWithDomain:kGIDSignInErrorDomain
  578. code:code
  579. userInfo:errorDict];
  580. }
  581. + (BOOL)isOperatingSystemAtLeast9 {
  582. NSProcessInfo *processInfo = [NSProcessInfo processInfo];
  583. return [processInfo respondsToSelector:@selector(isOperatingSystemAtLeastVersion:)] &&
  584. [processInfo isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){.majorVersion = 9}];
  585. }
  586. // Asserts the parameters being valid.
  587. - (void)assertValidParameters {
  588. if (![_clientID length]) {
  589. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  590. [NSException raise:NSInvalidArgumentException
  591. format:@"You must specify |clientID| for |GIDSignIn|"];
  592. }
  593. if ([self adjustedScopes].count == 0) {
  594. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  595. [NSException raise:NSInvalidArgumentException
  596. format:@"You must specify |shouldFetchBasicProfile| or |scopes| for |GIDSignIn|"];
  597. }
  598. }
  599. // Assert that the UI Delegate has been set.
  600. - (void)assertValidPresentingViewController {
  601. if (!_presentingViewController) {
  602. // NOLINTNEXTLINE(google-objc-avoid-throwing-exception)
  603. [NSException raise:NSInvalidArgumentException format:@"presentingViewController must be set."];
  604. }
  605. }
  606. // Checks whether or not this is the first time the app runs.
  607. - (BOOL)isFreshInstall {
  608. NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
  609. if ([defaults boolForKey:kAppHasRunBeforeKey]) {
  610. return NO;
  611. }
  612. [defaults setBool:YES forKey:kAppHasRunBeforeKey];
  613. return YES;
  614. }
  615. - (void)removeAllKeychainEntries {
  616. [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:kGTMAppAuthKeychainName];
  617. }
  618. // Clears the saved authentication object and other user information.
  619. - (void)clearAuthentication {
  620. [self willChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  621. _currentUser = nil;
  622. [self didChangeValueForKey:NSStringFromSelector(@selector(currentUser))];
  623. }
  624. // Adds basic profile scopes to |scopes| if |shouldFetchBasicProfile| is set.
  625. - (NSArray *)adjustedScopes {
  626. NSArray<NSString *> *adjustedScopes = _scopes;
  627. if (_shouldFetchBasicProfile) {
  628. adjustedScopes = [GIDScopes scopesWithBasicProfile:adjustedScopes];
  629. }
  630. return adjustedScopes;
  631. }
  632. - (NSURL *)redirectURI {
  633. NSString *scheme = [_schemes clientIdentifierScheme];
  634. return [NSURL URLWithString:[NSString stringWithFormat:@"%@:%@", scheme, kBrowserCallbackPath]];
  635. }
  636. - (void)signOutWithUser:(GIDGoogleUser *)user {
  637. // TODO(petea): Respond to user parameter.
  638. // TODO(petea): Mark user as signed out rather than removing auth from keychain.
  639. [self clearAuthentication];
  640. [self removeAllKeychainEntries];
  641. }
  642. - (void)disconnectWithUser:(GIDGoogleUser *)user {
  643. OIDAuthState *authState = user.authentication.authState;
  644. if (!authState) {
  645. // Even the user is not signed in right now, we still need to remove any token saved in the
  646. // keychain.
  647. authState = [self loadAuthState];
  648. }
  649. // Either access or refresh token would work, but we won't have access token if the auth is
  650. // retrieved from keychain.
  651. NSString *token = authState.lastTokenResponse.accessToken;
  652. if (!token) {
  653. token = authState.lastTokenResponse.refreshToken;
  654. }
  655. if (!token) {
  656. [self removeAllKeychainEntries];
  657. // Nothing to do here, consider the operation successful.
  658. [self didDisconnectWithUser:user error:nil];
  659. return;
  660. }
  661. NSString *revokeURLString = [NSString stringWithFormat:kRevokeTokenURLTemplate,
  662. [GIDSignInPreferences googleAuthorizationServer], token];
  663. // Append logging parameter
  664. revokeURLString = [NSString stringWithFormat:@"%@&%@=%@",
  665. revokeURLString,
  666. kSDKVersionLoggingParameter,
  667. GIDVersion()];
  668. NSURL *revokeURL = [NSURL URLWithString:revokeURLString];
  669. [self startFetchURL:revokeURL
  670. fromAuthState:authState
  671. withComment:@"GIDSignIn: revoke tokens"
  672. withCompletionHandler:^(NSData *data, NSError *error) {
  673. // Revoking an already revoked token seems always successful, which saves the trouble here for
  674. // us.
  675. if (error) {
  676. [self didDisconnectWithUser:user error:error];
  677. } else {
  678. [self signOutWithUser:user];
  679. [self didDisconnectWithUser:user error:nil];
  680. }
  681. }];
  682. }
  683. - (BOOL)saveAuthState:(OIDAuthState *)authState {
  684. GTMAppAuthFetcherAuthorization *authorization =
  685. [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState];
  686. return [GTMAppAuthFetcherAuthorization saveAuthorization:authorization
  687. toKeychainForName:kGTMAppAuthKeychainName];
  688. }
  689. - (OIDAuthState *)loadAuthState {
  690. GTMAppAuthFetcherAuthorization *authorization =
  691. [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthKeychainName];
  692. return authorization.authState;
  693. }
  694. @end
  695. NS_ASSUME_NONNULL_END