GIDGoogleUser.m 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // Copyright 2022 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/GIDGoogleUser.h"
  15. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  16. #import "GoogleSignIn/Sources/Public/GoogleSignIn/GIDConfiguration.h"
  17. #import "GoogleSignIn/Sources/GIDAuthentication.h"
  18. #import "GoogleSignIn/Sources/GIDProfileData_Private.h"
  19. #import "GoogleSignIn/Sources/GIDToken_Private.h"
  20. #ifdef SWIFT_PACKAGE
  21. @import AppAuth;
  22. #else
  23. #import <AppAuth/AppAuth.h>
  24. #endif
  25. // The ID Token claim key for the hosted domain value.
  26. static NSString *const kHostedDomainIDTokenClaimKey = @"hd";
  27. // Key constants used for encode and decode.
  28. static NSString *const kAuthenticationKey = @"authentication";
  29. static NSString *const kProfileDataKey = @"profileData";
  30. static NSString *const kAuthState = @"authState";
  31. // Parameters for the token exchange endpoint.
  32. static NSString *const kAudienceParameter = @"audience";
  33. static NSString *const kOpenIDRealmParameter = @"openid.realm";
  34. NS_ASSUME_NONNULL_BEGIN
  35. @implementation GIDGoogleUser {
  36. OIDAuthState *_authState;
  37. GIDConfiguration *_cachedConfiguration;
  38. GIDToken *_cachedAccessToken;
  39. GIDToken *_cachedRefreshToken;
  40. GIDToken *_cachedIdToken;
  41. }
  42. - (nullable NSString *)userID {
  43. NSString *idTokenString = self.idToken.tokenString;
  44. if (idTokenString) {
  45. OIDIDToken *idTokenDecoded =
  46. [[OIDIDToken alloc] initWithIDTokenString:idTokenString];
  47. if (idTokenDecoded && idTokenDecoded.subject) {
  48. return [idTokenDecoded.subject copy];
  49. }
  50. }
  51. return nil;
  52. }
  53. - (nullable NSArray<NSString *> *)grantedScopes {
  54. NSArray<NSString *> *grantedScopes;
  55. NSString *grantedScopeString = _authState.lastTokenResponse.scope;
  56. if (grantedScopeString) {
  57. // If we have a 'scope' parameter from the backend, this is authoritative.
  58. // Remove leading and trailing whitespace.
  59. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  60. [NSCharacterSet whitespaceCharacterSet]];
  61. // Tokenize with space as a delimiter.
  62. NSMutableArray<NSString *> *parsedScopes =
  63. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  64. // Remove empty strings.
  65. [parsedScopes removeObject:@""];
  66. grantedScopes = [parsedScopes copy];
  67. }
  68. return grantedScopes;
  69. }
  70. - (GIDConfiguration *)configuration {
  71. @synchronized(self) {
  72. // Caches the configuration since it would not change for one GIDGoogleUser instance.
  73. if (!_cachedConfiguration) {
  74. NSString *clientID = _authState.lastAuthorizationResponse.request.clientID;
  75. NSString *serverClientID =
  76. _authState.lastTokenResponse.request.additionalParameters[kAudienceParameter];
  77. NSString *openIDRealm =
  78. _authState.lastTokenResponse.request.additionalParameters[kOpenIDRealmParameter];
  79. _cachedConfiguration = [[GIDConfiguration alloc] initWithClientID:clientID
  80. serverClientID:serverClientID
  81. hostedDomain:[self hostedDomain]
  82. openIDRealm:openIDRealm];
  83. };
  84. }
  85. return _cachedConfiguration;
  86. }
  87. - (GIDToken *)accessToken {
  88. @synchronized(self) {
  89. return _cachedAccessToken;
  90. }
  91. }
  92. - (GIDToken *)refreshToken {
  93. @synchronized(self) {
  94. return _cachedRefreshToken;
  95. }
  96. }
  97. - (nullable GIDToken *)idToken {
  98. @synchronized(self) {
  99. return _cachedIdToken;
  100. }
  101. }
  102. - (id<GTMFetcherAuthorizationProtocol>) fetcherAuthorizer {
  103. return [_authentication fetcherAuthorizer];
  104. }
  105. - (void)doWithFreshTokens:(void (^)(GIDGoogleUser *_Nullable user,
  106. NSError *_Nullable error))completion {
  107. [_authentication doWithFreshTokens:^(OIDAuthState *authState, NSError *error) {
  108. if (authState) {
  109. NSString *accessTokenString = authState.lastTokenResponse.accessToken;
  110. NSDate *accessTokenExpirationDate = authState.lastTokenResponse.accessTokenExpirationDate;
  111. NSString *refreshTokenString = authState.refreshToken;
  112. NSString *idTokenString = authState.lastTokenResponse.idToken;
  113. NSDate *idTokenExpirationDate = [[[OIDIDToken alloc]
  114. initWithIDTokenString:idTokenString] expiresAt];
  115. // Check if it is the current authState.
  116. if ([accessTokenString isEqual:self.accessToken.tokenString] &&
  117. [self isTheSameExpirationDate:accessTokenExpirationDate
  118. with:self.accessToken.expirationDate] &&
  119. [refreshTokenString isEqual:self.refreshToken.tokenString] &&
  120. [idTokenString isEqual:self.idToken.tokenString] &&
  121. [self isTheSameExpirationDate:idTokenExpirationDate with:self.idToken.expirationDate]) {
  122. completion(self, nil);;
  123. } else {
  124. [self updateAuthState:authState notifyTokenChanges:YES];
  125. completion(self, nil);
  126. }
  127. } else {
  128. completion(nil, error);
  129. }
  130. }];
  131. }
  132. #pragma mark - Private Methods
  133. - (instancetype)initWithAuthState:(OIDAuthState *)authState
  134. profileData:(nullable GIDProfileData *)profileData {
  135. self = [super init];
  136. if (self) {
  137. [self updateAuthState:authState profileData:profileData notifyTokenChanges:NO];
  138. }
  139. return self;
  140. }
  141. - (void)updateAuthState:(OIDAuthState *)authState
  142. profileData:(nullable GIDProfileData *)profileData
  143. notifyTokenChanges:(BOOL)notify{
  144. _profile = profileData;
  145. [self updateAuthState:authState notifyTokenChanges:notify];
  146. }
  147. - (void)updateAuthState:(OIDAuthState *)authState
  148. notifyTokenChanges:(BOOL)notify{
  149. @synchronized(self) {
  150. _authState = authState;
  151. _authentication = [[GIDAuthentication alloc] initWithAuthState:authState];
  152. if (notify) {
  153. [self willChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  154. [self willChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  155. [self willChangeValueForKey:NSStringFromSelector(@selector(refreshToken))];
  156. }
  157. // Update three tokens
  158. _cachedAccessToken = [[GIDToken alloc] initWithTokenString:_authState.lastTokenResponse.accessToken
  159. expirationDate:_authState.lastTokenResponse.
  160. accessTokenExpirationDate];
  161. _cachedRefreshToken = [[GIDToken alloc] initWithTokenString:_authState.refreshToken
  162. expirationDate:nil];
  163. _cachedIdToken = nil;
  164. NSString *idTokenString = _authState.lastTokenResponse.idToken;
  165. if (idTokenString) {
  166. NSDate *idTokenExpirationDate = [[[OIDIDToken alloc]
  167. initWithIDTokenString:idTokenString] expiresAt];
  168. _cachedIdToken = [[GIDToken alloc] initWithTokenString:idTokenString
  169. expirationDate:idTokenExpirationDate];
  170. }
  171. if (notify) {
  172. [self didChangeValueForKey:NSStringFromSelector(@selector(accessToken))];
  173. [self didChangeValueForKey:NSStringFromSelector(@selector(idToken))];
  174. [self didChangeValueForKey:NSStringFromSelector(@selector(refreshToken))];
  175. }
  176. }
  177. }
  178. #pragma mark - Helpers
  179. - (nullable NSString *)hostedDomain {
  180. NSString *idTokenString = self.idToken.tokenString;
  181. if (idTokenString) {
  182. OIDIDToken *idTokenDecoded = [[OIDIDToken alloc] initWithIDTokenString:idTokenString];
  183. if (idTokenDecoded && idTokenDecoded.claims[kHostedDomainIDTokenClaimKey]) {
  184. return idTokenDecoded.claims[kHostedDomainIDTokenClaimKey];
  185. }
  186. }
  187. return nil;
  188. }
  189. // The date is nullable in GIDToken. If they are both nil they are considered equal.
  190. - (BOOL)isTheSameExpirationDate:(nullable NSDate *)date1
  191. with:(nullable NSDate *)date2 {
  192. if (!date1 && !date2) {
  193. return YES;
  194. }
  195. return [date1 isEqualToDate:date2];
  196. }
  197. #pragma mark - NSSecureCoding
  198. + (BOOL)supportsSecureCoding {
  199. return YES;
  200. }
  201. - (nullable instancetype)initWithCoder:(NSCoder *)decoder {
  202. self = [super init];
  203. if (self) {
  204. GIDProfileData *profileData =
  205. [decoder decodeObjectOfClass:[GIDProfileData class] forKey:kProfileDataKey];
  206. OIDAuthState *authState;
  207. if ([decoder containsValueForKey:kAuthState]) { // Current encoding
  208. authState = [decoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthState];
  209. } else { // Old encoding
  210. GIDAuthentication *authentication = [decoder decodeObjectOfClass:[GIDAuthentication class]
  211. forKey:kAuthenticationKey];
  212. authState = authentication.authState;
  213. }
  214. [self updateAuthState:authState profileData:profileData notifyTokenChanges:NO];
  215. }
  216. return self;
  217. }
  218. - (void)encodeWithCoder:(NSCoder *)encoder {
  219. [encoder encodeObject:_profile forKey:kProfileDataKey];
  220. [encoder encodeObject:_authState forKey:kAuthState];
  221. }
  222. @end
  223. NS_ASSUME_NONNULL_END