MultiFactor.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. // Copyright 2023 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. #if os(iOS) || os(macOS)
  16. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  17. extension MultiFactor: NSSecureCoding {}
  18. /// The interface defining the multi factor related properties and operations pertaining to a
  19. /// user.
  20. ///
  21. /// This class is available on iOS and macOS.
  22. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  23. @objc(FIRMultiFactor) open class MultiFactor: NSObject {
  24. @objc open var enrolledFactors: [MultiFactorInfo]
  25. /// Get a session for a second factor enrollment operation.
  26. ///
  27. /// This is used to identify the current user trying to enroll a second factor.
  28. /// - Parameter completion: A block with the session identifier for a second factor enrollment
  29. /// operation.
  30. @objc(getSessionWithCompletion:)
  31. open func getSessionWithCompletion(_ completion: ((MultiFactorSession?, Error?) -> Void)?) {
  32. let session = MultiFactorSession.session(for: user)
  33. if let completion {
  34. completion(session, nil)
  35. }
  36. }
  37. /// Get a session for a second factor enrollment operation.
  38. ///
  39. /// This is used to identify the current user trying to enroll a second factor.
  40. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  41. open func session() async throws -> MultiFactorSession {
  42. return try await withCheckedThrowingContinuation { continuation in
  43. self.getSessionWithCompletion { session, error in
  44. if let session {
  45. continuation.resume(returning: session)
  46. } else {
  47. continuation.resume(throwing: error!)
  48. }
  49. }
  50. }
  51. }
  52. /// Enrolls a second factor as identified by the `MultiFactorAssertion` parameter for the
  53. /// current user.
  54. /// - Parameter assertion: The `MultiFactorAssertion`.
  55. /// - Parameter displayName: An optional display name associated with the multi factor to
  56. /// enroll.
  57. /// - Parameter completion: The block invoked when the request is complete, or fails.
  58. @objc(enrollWithAssertion:displayName:completion:)
  59. open func enroll(with assertion: MultiFactorAssertion,
  60. displayName: String?,
  61. completion: ((Error?) -> Void)?) {
  62. // TODO: Refactor classes so this duplicated code isn't necessary for phone and totp.
  63. guard
  64. assertion.factorID == PhoneMultiFactorInfo.TOTPMultiFactorID ||
  65. assertion.factorID == PhoneMultiFactorInfo.PhoneMultiFactorID
  66. else {
  67. return
  68. }
  69. guard let user, let auth = user.auth else {
  70. fatalError("Internal Auth error: failed to get user enrolling in MultiFactor")
  71. }
  72. let request = Self.enrollmentFinalizationRequest(
  73. with: assertion,
  74. displayName: displayName,
  75. user: user,
  76. auth: auth
  77. )
  78. Task {
  79. do {
  80. let response = try await auth.backend.call(with: request)
  81. let user = try await auth.completeSignIn(withAccessToken: response.idToken,
  82. accessTokenExpirationDate: nil,
  83. refreshToken: response.refreshToken,
  84. anonymous: false)
  85. try auth.updateCurrentUser(user, byForce: false, savingToDisk: true)
  86. if let completion {
  87. DispatchQueue.main.async {
  88. completion(nil)
  89. }
  90. }
  91. } catch {
  92. if let completion {
  93. DispatchQueue.main.async {
  94. completion(error)
  95. }
  96. }
  97. }
  98. }
  99. }
  100. private static func enrollmentFinalizationRequest(with assertion: MultiFactorAssertion,
  101. displayName: String?,
  102. user: User,
  103. auth: Auth) -> FinalizeMFAEnrollmentRequest {
  104. var request: FinalizeMFAEnrollmentRequest? = nil
  105. if assertion.factorID == PhoneMultiFactorInfo.TOTPMultiFactorID {
  106. guard let totpAssertion = assertion as? TOTPMultiFactorAssertion else {
  107. fatalError("Auth Internal Error: Failed to find TOTPMultiFactorAssertion")
  108. }
  109. switch totpAssertion.secretOrID {
  110. case .enrollmentID: fatalError("Missing secret in totpAssertion")
  111. case let .secret(secret):
  112. let finalizeMFATOTPRequestInfo =
  113. AuthProtoFinalizeMFATOTPEnrollmentRequestInfo(sessionInfo: secret.sessionInfo,
  114. verificationCode: totpAssertion
  115. .oneTimePassword)
  116. request = FinalizeMFAEnrollmentRequest(idToken: user.rawAccessToken(),
  117. displayName: displayName,
  118. totpVerificationInfo: finalizeMFATOTPRequestInfo,
  119. requestConfiguration: user
  120. .requestConfiguration)
  121. }
  122. } else if assertion.factorID == PhoneMultiFactorInfo.PhoneMultiFactorID {
  123. let phoneAssertion = assertion as? PhoneMultiFactorAssertion
  124. guard let credential = phoneAssertion?.authCredential else {
  125. fatalError("Internal Error: Missing credential")
  126. }
  127. switch credential.credentialKind {
  128. case .phoneNumber: fatalError("Internal Error: Missing verificationCode")
  129. case let .verification(verificationID, code):
  130. let finalizeMFAPhoneRequestInfo =
  131. AuthProtoFinalizeMFAPhoneRequestInfo(
  132. sessionInfo: verificationID,
  133. verificationCode: code
  134. )
  135. request = FinalizeMFAEnrollmentRequest(
  136. idToken: user.rawAccessToken(),
  137. displayName: displayName,
  138. phoneVerificationInfo: finalizeMFAPhoneRequestInfo,
  139. requestConfiguration: user.requestConfiguration
  140. )
  141. }
  142. }
  143. guard let request else {
  144. // Assertion is not a phone assertion or TOTP assertion.
  145. fatalError("Internal Error: Unsupported assertion with factor ID: \(assertion.factorID).")
  146. }
  147. return request
  148. }
  149. /// Enrolls a second factor as identified by the `MultiFactorAssertion` parameter for the
  150. /// current user.
  151. /// - Parameter assertion: The `MultiFactorAssertion`.
  152. /// - Parameter displayName: An optional display name associated with the multi factor to
  153. /// enroll.
  154. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  155. open func enroll(with assertion: MultiFactorAssertion, displayName: String?) async throws {
  156. return try await withCheckedThrowingContinuation { continuation in
  157. self.enroll(with: assertion, displayName: displayName) { error in
  158. if let error {
  159. continuation.resume(throwing: error)
  160. } else {
  161. continuation.resume()
  162. }
  163. }
  164. }
  165. }
  166. /// Unenroll the given multi factor.
  167. /// - Parameter factorInfo: The second factor instance to unenroll.
  168. /// - Parameter completion: The block invoked when the request to send the verification email is
  169. /// complete, or fails.
  170. @objc(unenrollWithInfo:completion:)
  171. open func unenroll(with factorInfo: MultiFactorInfo,
  172. completion: ((Error?) -> Void)?) {
  173. unenroll(withFactorUID: factorInfo.uid, completion: completion)
  174. }
  175. /// Unenroll the given multi factor.
  176. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  177. open func unenroll(with factorInfo: MultiFactorInfo) async throws {
  178. try await unenroll(withFactorUID: factorInfo.uid)
  179. }
  180. /// Unenroll the given multi factor.
  181. /// - Parameter factorUID: The unique identifier corresponding to the
  182. /// second factor being unenrolled.
  183. /// - Parameter completion: The block invoked when the request to send the verification email is
  184. /// complete, or fails.
  185. @objc(unenrollWithFactorUID:completion:)
  186. open func unenroll(withFactorUID factorUID: String,
  187. completion: ((Error?) -> Void)?) {
  188. guard let user = user, let auth = user.auth else {
  189. fatalError("Internal Auth error: failed to get user unenrolling in MultiFactor")
  190. }
  191. let request = WithdrawMFARequest(idToken: user.rawAccessToken(),
  192. mfaEnrollmentID: factorUID,
  193. requestConfiguration: user.requestConfiguration)
  194. Task {
  195. do {
  196. let response = try await auth.backend.call(with: request)
  197. do {
  198. let user = try await auth.completeSignIn(withAccessToken: response.idToken,
  199. accessTokenExpirationDate: nil,
  200. refreshToken: response.refreshToken,
  201. anonymous: false)
  202. try auth.updateCurrentUser(user, byForce: false, savingToDisk: true)
  203. if let completion {
  204. DispatchQueue.main.async {
  205. completion(nil)
  206. }
  207. }
  208. } catch {
  209. DispatchQueue.main.async {
  210. try? auth.signOut()
  211. if let completion {
  212. completion(error)
  213. }
  214. }
  215. }
  216. } catch {
  217. if let completion {
  218. completion(error)
  219. }
  220. }
  221. }
  222. }
  223. /// Unenroll the given multi factor.
  224. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  225. open func unenroll(withFactorUID factorUID: String) async throws {
  226. return try await withCheckedThrowingContinuation { continuation in
  227. self.unenroll(withFactorUID: factorUID) { error in
  228. if let error {
  229. continuation.resume(throwing: error)
  230. } else {
  231. continuation.resume()
  232. }
  233. }
  234. }
  235. }
  236. weak var user: User?
  237. convenience init(withMFAEnrollments mfaEnrollments: [AuthProtoMFAEnrollment]) {
  238. self.init()
  239. var multiFactorInfoArray: [MultiFactorInfo] = []
  240. for enrollment in mfaEnrollments {
  241. if enrollment.phoneInfo != nil {
  242. let multiFactorInfo = PhoneMultiFactorInfo(proto: enrollment)
  243. multiFactorInfoArray.append(multiFactorInfo)
  244. } else if enrollment.totpInfo != nil {
  245. let multiFactorInfo = TOTPMultiFactorInfo(proto: enrollment)
  246. multiFactorInfoArray.append(multiFactorInfo)
  247. }
  248. }
  249. enrolledFactors = multiFactorInfoArray
  250. }
  251. override init() {
  252. enrolledFactors = []
  253. }
  254. // MARK: - NSSecureCoding
  255. private let kEnrolledFactorsCodingKey = "enrolledFactors"
  256. public static let supportsSecureCoding = true
  257. public func encode(with coder: NSCoder) {
  258. coder.encode(enrolledFactors, forKey: kEnrolledFactorsCodingKey)
  259. // Do not encode `user` weak property.
  260. }
  261. public required init?(coder: NSCoder) {
  262. let classes = [NSArray.self, MultiFactorInfo.self, PhoneMultiFactorInfo.self,
  263. TOTPMultiFactorInfo.self]
  264. let enrolledFactors = coder
  265. .decodeObject(of: classes, forKey: kEnrolledFactorsCodingKey) as? [MultiFactorInfo]
  266. self.enrolledFactors = enrolledFactors ?? []
  267. // Do not decode `user` weak property.
  268. }
  269. }
  270. #endif