GIDSignIn.m 45 KB

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