UserProfileUpdate.swift 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. // Copyright 2024 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 Foundation
  15. /// Actor to serialize the update profile calls.
  16. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  17. actor UserProfileUpdate {
  18. func link(user: User, with credential: AuthCredential) async throws -> AuthDataResult {
  19. let accessToken = try await user.internalGetTokenAsync(backend: user.backend)
  20. let request = VerifyAssertionRequest(providerID: credential.provider,
  21. requestConfiguration: user.requestConfiguration)
  22. credential.prepare(request)
  23. request.accessToken = accessToken
  24. do {
  25. let response = try await user.backend.call(with: request)
  26. guard let idToken = response.idToken,
  27. let refreshToken = response.refreshToken,
  28. let providerID = response.providerID else {
  29. fatalError("Internal Auth Error: missing token in EmailLinkSignInResponse")
  30. }
  31. try await updateTokenAndRefreshUser(user: user,
  32. idToken: idToken,
  33. refreshToken: refreshToken,
  34. expirationDate: response.approximateExpirationDate)
  35. let updatedOAuthCredential = OAuthCredential(withVerifyAssertionResponse: response)
  36. let additionalUserInfo = AdditionalUserInfo(providerID: providerID,
  37. profile: response.profile,
  38. username: response.username,
  39. isNewUser: response.isNewUser)
  40. return AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo,
  41. credential: updatedOAuthCredential)
  42. } catch {
  43. user.signOutIfTokenIsInvalid(withError: error)
  44. throw error
  45. }
  46. }
  47. func unlink(user: User, fromProvider provider: String) async throws -> User {
  48. let accessToken = try await user.internalGetTokenAsync(backend: user.backend)
  49. let request = SetAccountInfoRequest(
  50. accessToken: accessToken, requestConfiguration: user.requestConfiguration
  51. )
  52. if user.providerDataRaw[provider] == nil {
  53. throw AuthErrorUtils.noSuchProviderError()
  54. }
  55. request.deleteProviders = [provider]
  56. do {
  57. let response = try await user.backend.call(with: request)
  58. // We can't just use the provider info objects in SetAccountInfoResponse
  59. // because they don't have localID and email fields. Remove the specific
  60. // provider manually.
  61. user.providerDataRaw.removeValue(forKey: provider)
  62. if provider == EmailAuthProvider.id {
  63. user.hasEmailPasswordCredential = false
  64. }
  65. #if os(iOS)
  66. // After successfully unlinking a phone auth provider, remove the phone number
  67. // from the cached user info.
  68. if provider == PhoneAuthProvider.id {
  69. user.phoneNumber = nil
  70. }
  71. #endif
  72. if let idToken = response.idToken,
  73. let refreshToken = response.refreshToken {
  74. let tokenService = SecureTokenService(
  75. withRequestConfiguration: user.requestConfiguration,
  76. accessToken: idToken,
  77. accessTokenExpirationDate: response.approximateExpirationDate,
  78. refreshToken: refreshToken
  79. )
  80. try await setTokenService(user: user, tokenService: tokenService)
  81. return user
  82. }
  83. } catch {
  84. user.signOutIfTokenIsInvalid(withError: error)
  85. throw error
  86. }
  87. if let error = user.updateKeychain() {
  88. throw error
  89. }
  90. return user
  91. }
  92. /// Performs a setAccountInfo request by mutating the results of a getAccountInfo response,
  93. /// atomically in regards to other calls to this method.
  94. /// - Parameter changeBlock: A block responsible for mutating a template `SetAccountInfoRequest`
  95. func executeUserUpdateWithChanges(user: User,
  96. changeBlock: @escaping (GetAccountInfoResponse.User,
  97. SetAccountInfoRequest)
  98. -> Void) async throws {
  99. let userAccountInfo = try await getAccountInfoRefreshingCache(user)
  100. let accessToken = try await user.internalGetTokenAsync(backend: user.backend)
  101. // Mutate setAccountInfoRequest in block
  102. let setAccountInfoRequest =
  103. SetAccountInfoRequest(
  104. accessToken: accessToken,
  105. requestConfiguration: user.requestConfiguration
  106. )
  107. changeBlock(userAccountInfo, setAccountInfoRequest)
  108. do {
  109. let accountInfoResponse = try await user.backend.call(with: setAccountInfoRequest)
  110. if let idToken = accountInfoResponse.idToken,
  111. let refreshToken = accountInfoResponse.refreshToken {
  112. let tokenService = SecureTokenService(
  113. withRequestConfiguration: user.requestConfiguration,
  114. accessToken: idToken,
  115. accessTokenExpirationDate: accountInfoResponse.approximateExpirationDate,
  116. refreshToken: refreshToken
  117. )
  118. try await setTokenService(user: user, tokenService: tokenService)
  119. }
  120. } catch {
  121. user.signOutIfTokenIsInvalid(withError: error)
  122. throw error
  123. }
  124. }
  125. // Update the new token and refresh user info again.
  126. func updateTokenAndRefreshUser(user: User,
  127. idToken: String,
  128. refreshToken: String,
  129. expirationDate: Date?) async throws {
  130. user.tokenService = SecureTokenService(
  131. withRequestConfiguration: user.requestConfiguration,
  132. accessToken: idToken,
  133. accessTokenExpirationDate: expirationDate,
  134. refreshToken: refreshToken
  135. )
  136. let accessToken = try await user.internalGetTokenAsync(backend: user.backend)
  137. let getAccountInfoRequest = GetAccountInfoRequest(
  138. accessToken: accessToken,
  139. requestConfiguration: user.requestConfiguration
  140. )
  141. do {
  142. let response = try await user.backend.call(with: getAccountInfoRequest)
  143. user.isAnonymous = false
  144. user.update(withGetAccountInfoResponse: response)
  145. } catch {
  146. user.signOutIfTokenIsInvalid(withError: error)
  147. throw error
  148. }
  149. if let error = user.updateKeychain() {
  150. throw error
  151. }
  152. }
  153. /// Sets a new token service for the `User` instance.
  154. ///
  155. /// The method makes sure the token service has access and refresh token and the new tokens
  156. /// are saved in the keychain before calling back.
  157. /// - Parameter tokenService: The new token service object.
  158. /// - Parameter callback: The block to be called in the global auth working queue once finished.
  159. func setTokenService(user: User, tokenService: SecureTokenService) async throws {
  160. _ = try await tokenService.fetchAccessToken(forcingRefresh: false, backend: user.backend)
  161. user.tokenService = tokenService
  162. if let error = user.updateKeychain() {
  163. throw error
  164. }
  165. }
  166. /// Gets the users' account data from the server, updating our local values.
  167. /// - Parameter callback: Invoked when the request to getAccountInfo has completed, or when an
  168. /// error has been detected. Invoked asynchronously on the auth global work queue in the future.
  169. func getAccountInfoRefreshingCache(_ user: User) async throws
  170. -> GetAccountInfoResponse.User {
  171. let token = try await user.internalGetTokenAsync(backend: user.backend)
  172. let request = GetAccountInfoRequest(accessToken: token,
  173. requestConfiguration: user.requestConfiguration)
  174. do {
  175. let accountInfoResponse = try await user.backend.call(with: request)
  176. user.update(withGetAccountInfoResponse: accountInfoResponse)
  177. if let error = user.updateKeychain() {
  178. throw error
  179. }
  180. return (accountInfoResponse.users?.first)!
  181. } catch {
  182. user.signOutIfTokenIsInvalid(withError: error)
  183. throw error
  184. }
  185. }
  186. }