MultiFactor.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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)
  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 only.
  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.sessionForCurrentUser
  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. if assertion.factorID == PhoneMultiFactorInfo.TOTPMultiFactorID {
  64. guard let totpAssertion = assertion as? TOTPMultiFactorAssertion else {
  65. fatalError("Auth Internal Error: Failed to find TOTPMultiFactorAssertion")
  66. }
  67. switch totpAssertion.secretOrID {
  68. case .enrollmentID: fatalError("Missing secret in totpAssertion")
  69. case let .secret(secret):
  70. guard let user = user, let auth = user.auth else {
  71. fatalError("Internal Auth error: failed to get user enrolling in MultiFactor")
  72. }
  73. let finalizeMFATOTPRequestInfo =
  74. AuthProtoFinalizeMFATOTPEnrollmentRequestInfo(sessionInfo: secret.sessionInfo,
  75. verificationCode: totpAssertion
  76. .oneTimePassword)
  77. let request = FinalizeMFAEnrollmentRequest(idToken: self.user?.rawAccessToken(),
  78. displayName: displayName,
  79. totpVerificationInfo: finalizeMFATOTPRequestInfo,
  80. requestConfiguration: user
  81. .requestConfiguration)
  82. Task {
  83. do {
  84. let response = try await AuthBackend.call(with: request)
  85. do {
  86. let user = try await auth.completeSignIn(withAccessToken: response.idToken,
  87. accessTokenExpirationDate: nil,
  88. refreshToken: response.refreshToken,
  89. anonymous: false)
  90. try auth.updateCurrentUser(user, byForce: false, savingToDisk: true)
  91. if let completion {
  92. DispatchQueue.main.async {
  93. completion(nil)
  94. }
  95. }
  96. } catch {
  97. DispatchQueue.main.async {
  98. if let completion {
  99. completion(error)
  100. }
  101. }
  102. }
  103. } catch {
  104. if let completion {
  105. completion(error)
  106. }
  107. }
  108. }
  109. }
  110. } else if assertion.factorID != PhoneMultiFactorInfo.PhoneMultiFactorID {
  111. return
  112. }
  113. let phoneAssertion = assertion as? PhoneMultiFactorAssertion
  114. guard let credential = phoneAssertion?.authCredential else {
  115. fatalError("Internal Error: Missing credential")
  116. }
  117. switch credential.credentialKind {
  118. case .phoneNumber: fatalError("Internal Error: Missing verificationCode")
  119. case let .verification(verificationID, code):
  120. let finalizeMFAPhoneRequestInfo =
  121. AuthProtoFinalizeMFAPhoneRequestInfo(sessionInfo: verificationID, verificationCode: code)
  122. guard let user = user, let auth = user.auth else {
  123. fatalError("Internal Auth error: failed to get user enrolling in MultiFactor")
  124. }
  125. let request = FinalizeMFAEnrollmentRequest(
  126. idToken: self.user?.rawAccessToken(),
  127. displayName: displayName,
  128. phoneVerificationInfo: finalizeMFAPhoneRequestInfo,
  129. requestConfiguration: user.requestConfiguration
  130. )
  131. Task {
  132. do {
  133. let response = try await AuthBackend.call(with: request)
  134. do {
  135. let user = try await auth.completeSignIn(withAccessToken: response.idToken,
  136. accessTokenExpirationDate: nil,
  137. refreshToken: response.refreshToken,
  138. anonymous: false)
  139. try auth.updateCurrentUser(user, byForce: false, savingToDisk: true)
  140. if let completion {
  141. DispatchQueue.main.async {
  142. completion(nil)
  143. }
  144. }
  145. } catch {
  146. DispatchQueue.main.async {
  147. if let completion {
  148. completion(error)
  149. }
  150. }
  151. }
  152. } catch {
  153. if let completion {
  154. completion(error)
  155. }
  156. }
  157. }
  158. }
  159. }
  160. /// Enrolls a second factor as identified by the `MultiFactorAssertion` parameter for the
  161. /// current user.
  162. /// - Parameter assertion: The `MultiFactorAssertion`.
  163. /// - Parameter displayName: An optional display name associated with the multi factor to
  164. /// enroll.
  165. /// - Parameter completion: The block invoked when the request is complete, or fails.
  166. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  167. open func enroll(with assertion: MultiFactorAssertion, displayName: String?) async throws {
  168. return try await withCheckedThrowingContinuation { continuation in
  169. self.enroll(with: assertion, displayName: displayName) { error in
  170. if let error {
  171. continuation.resume(throwing: error)
  172. } else {
  173. continuation.resume()
  174. }
  175. }
  176. }
  177. }
  178. /// Unenroll the given multi factor.
  179. /// - Parameter completion: The block invoked when the request to send the verification email is
  180. /// complete, or fails.
  181. @objc(unenrollWithInfo:completion:)
  182. open func unenroll(with factorInfo: MultiFactorInfo,
  183. completion: ((Error?) -> Void)?) {
  184. unenroll(withFactorUID: factorInfo.uid, completion: completion)
  185. }
  186. /// Unenroll the given multi factor.
  187. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  188. open func unenroll(with factorInfo: MultiFactorInfo) async throws {
  189. try await unenroll(withFactorUID: factorInfo.uid)
  190. }
  191. /// Unenroll the given multi factor.
  192. /// - Parameter completion: The block invoked when the request to send the verification email is
  193. /// complete, or fails.
  194. @objc(unenrollWithFactorUID:completion:)
  195. open func unenroll(withFactorUID factorUID: String,
  196. completion: ((Error?) -> Void)?) {
  197. guard let user = user, let auth = user.auth else {
  198. fatalError("Internal Auth error: failed to get user unenrolling in MultiFactor")
  199. }
  200. let request = WithdrawMFARequest(idToken: user.rawAccessToken(),
  201. mfaEnrollmentID: factorUID,
  202. requestConfiguration: user.requestConfiguration)
  203. Task {
  204. do {
  205. let response = try await AuthBackend.call(with: request)
  206. do {
  207. let user = try await auth.completeSignIn(withAccessToken: response.idToken,
  208. accessTokenExpirationDate: nil,
  209. refreshToken: response.refreshToken,
  210. anonymous: false)
  211. try auth.updateCurrentUser(user, byForce: false, savingToDisk: true)
  212. if let completion {
  213. DispatchQueue.main.async {
  214. completion(nil)
  215. }
  216. }
  217. } catch {
  218. DispatchQueue.main.async {
  219. try? auth.signOut()
  220. if let completion {
  221. completion(error)
  222. }
  223. }
  224. }
  225. } catch {
  226. if let completion {
  227. completion(error)
  228. }
  229. }
  230. }
  231. }
  232. /// Unenroll the given multi factor.
  233. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  234. open func unenroll(withFactorUID factorUID: String) async throws {
  235. return try await withCheckedThrowingContinuation { continuation in
  236. self.unenroll(withFactorUID: factorUID) { error in
  237. if let error {
  238. continuation.resume(throwing: error)
  239. } else {
  240. continuation.resume()
  241. }
  242. }
  243. }
  244. }
  245. weak var user: User?
  246. convenience init(withMFAEnrollments mfaEnrollments: [AuthProtoMFAEnrollment]) {
  247. self.init()
  248. var multiFactorInfoArray: [MultiFactorInfo] = []
  249. for enrollment in mfaEnrollments {
  250. if enrollment.phoneInfo != nil {
  251. let multiFactorInfo = PhoneMultiFactorInfo(proto: enrollment)
  252. multiFactorInfoArray.append(multiFactorInfo)
  253. } else if enrollment.totpInfo != nil {
  254. let multiFactorInfo = TOTPMultiFactorInfo(proto: enrollment)
  255. multiFactorInfoArray.append(multiFactorInfo)
  256. }
  257. }
  258. enrolledFactors = multiFactorInfoArray
  259. }
  260. override init() {
  261. enrolledFactors = []
  262. }
  263. // MARK: - NSSecureCoding
  264. private let kEnrolledFactorsCodingKey = "enrolledFactors"
  265. public static var supportsSecureCoding: Bool {
  266. true
  267. }
  268. public func encode(with coder: NSCoder) {
  269. coder.encode(enrolledFactors, forKey: kEnrolledFactorsCodingKey)
  270. // Do not encode `user` weak property.
  271. }
  272. public required init?(coder: NSCoder) {
  273. let classes = [NSArray.self, MultiFactorInfo.self, PhoneMultiFactorInfo.self,
  274. TOTPMultiFactorInfo.self]
  275. let enrolledFactors = coder
  276. .decodeObject(of: classes, forKey: kEnrolledFactorsCodingKey) as? [MultiFactorInfo]
  277. self.enrolledFactors = enrolledFactors ?? []
  278. // Do not decode `user` weak property.
  279. }
  280. }
  281. #endif