TOTPMultiFactorGenerator.swift 5.7 KB

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