TOTPMultiFactorGenerator.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  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. /// The data structure used to help initialize an assertion for a second factor entity to the
  17. /// Firebase Auth/CICP server. Depending on the type of second factor, this will help generate
  18. /// the assertion.
  19. ///
  20. /// This class is available on iOS and macOS.
  21. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  22. @objc(FIRTOTPMultiFactorGenerator) open class TOTPMultiFactorGenerator: NSObject {
  23. /// Creates a TOTP secret as part of enrolling a TOTP second factor. Used for generating a
  24. /// QR code URL or inputting into a TOTP app. This method uses the auth instance corresponding
  25. /// to the user in the multiFactorSession.
  26. /// - Parameter session: The multiFactorSession instance.
  27. /// - Parameter completion: Completion block
  28. @objc(generateSecretWithMultiFactorSession:completion:)
  29. open class func generateSecret(with session: MultiFactorSession,
  30. completion: @escaping (TOTPSecret?, Error?) -> Void) {
  31. guard let currentUser = session.currentUser, let auth = currentUser.auth else {
  32. let error = AuthErrorUtils.error(code: AuthErrorCode.internalError,
  33. userInfo: [NSLocalizedDescriptionKey:
  34. "Invalid ID token."])
  35. completion(nil, error)
  36. return
  37. }
  38. let totpEnrollmentInfo = AuthProtoStartMFATOTPEnrollmentRequestInfo()
  39. let request = StartMFAEnrollmentRequest(idToken: session.idToken,
  40. totpEnrollmentInfo: totpEnrollmentInfo,
  41. requestConfiguration: auth.requestConfiguration)
  42. Task {
  43. do {
  44. let response = try await auth.backend.call(with: request)
  45. if let totpSessionInfo = response.totpSessionInfo {
  46. let secret = TOTPSecret(secretKey: totpSessionInfo.sharedSecretKey,
  47. hashingAlgorithm: totpSessionInfo.hashingAlgorithm,
  48. codeLength: totpSessionInfo.verificationCodeLength,
  49. codeIntervalSeconds: totpSessionInfo.periodSec,
  50. enrollmentCompletionDeadline: totpSessionInfo
  51. .finalizeEnrollmentTime,
  52. sessionInfo: totpSessionInfo.sessionInfo)
  53. completion(secret, nil)
  54. } else {
  55. let error = AuthErrorUtils.error(code: AuthErrorCode.internalError,
  56. userInfo: [NSLocalizedDescriptionKey:
  57. "Error generating TOTP secret."])
  58. completion(nil, error)
  59. }
  60. } catch {
  61. completion(nil, error)
  62. }
  63. }
  64. }
  65. /// Creates a TOTP secret as part of enrolling a TOTP second factor.
  66. ///
  67. /// Used for generating a QR code URL or inputting into a TOTP app. This
  68. /// method uses the auth instance correspondingto the user in the multiFactorSession.
  69. /// - Parameter session: The multiFactorSession instance.
  70. /// - Returns: The TOTP secret.
  71. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  72. open class func generateSecret(with session: MultiFactorSession) async throws -> TOTPSecret {
  73. return try await withCheckedThrowingContinuation { continuation in
  74. self.generateSecret(with: session) { secret, error in
  75. if let secret {
  76. continuation.resume(returning: secret)
  77. } else {
  78. continuation.resume(throwing: error!)
  79. }
  80. }
  81. }
  82. }
  83. /// Initializes the MFA assertion to confirm ownership of the TOTP second factor.
  84. ///
  85. /// This assertion is used to complete enrollment of TOTP as a second factor.
  86. /// - Parameter secret: The TOTP secret.
  87. /// - Parameter oneTimePassword: One time password string.
  88. /// - Returns: The MFA assertion.
  89. @objc(assertionForEnrollmentWithSecret:oneTimePassword:)
  90. open class func assertionForEnrollment(with secret: TOTPSecret,
  91. oneTimePassword: String) -> TOTPMultiFactorAssertion {
  92. return TOTPMultiFactorAssertion(secretOrID: SecretOrID.secret(secret),
  93. oneTimePassword: oneTimePassword)
  94. }
  95. /// Initializes the MFA assertion to confirm ownership of the TOTP second factor.
  96. ///
  97. /// This assertion is used to complete signIn with TOTP as a second factor.
  98. /// - Parameter enrollmentID: The ID that identifies the enrolled TOTP second factor.
  99. /// - Parameter oneTimePassword: one time password string.
  100. /// - Returns: The MFA assertion.
  101. @objc(assertionForSignInWithEnrollmentID:oneTimePassword:)
  102. open class func assertionForSignIn(withEnrollmentID enrollmentID: String,
  103. oneTimePassword: String) -> TOTPMultiFactorAssertion {
  104. return TOTPMultiFactorAssertion(secretOrID: SecretOrID.enrollmentID(enrollmentID),
  105. oneTimePassword: oneTimePassword)
  106. }
  107. }
  108. #endif