Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Auth] Use result type to wrap completion handlers internally #13563

Merged
merged 17 commits into from
Dec 3, 2024
Merged
92 changes: 46 additions & 46 deletions FirebaseAuth/Sources/Swift/Auth/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -300,9 +300,9 @@ extension Auth: AuthInterop {
Task {
do {
let response = try await self.backend.call(with: request)
Auth.wrapMainAsync(callback: completion, withParam: response.signinMethods, error: nil)
Auth.wrapMainAsync(callback: completion, with: .success(response.signinMethods))
} catch {
Auth.wrapMainAsync(callback: completion, withParam: nil, error: error)
Auth.wrapMainAsync(callback: completion, with: .failure(error))
}
}
}
Expand Down Expand Up @@ -365,9 +365,9 @@ extension Auth: AuthInterop {
withEmail: email,
password: password
)
decoratedCallback(authData, nil)
decoratedCallback(.success(authData))
} catch {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
}
}
Expand Down Expand Up @@ -463,9 +463,9 @@ extension Auth: AuthInterop {
do {
let authData = try await self.internalSignInAndRetrieveData(withCredential: credential,
isReauthentication: false)
decoratedCallback(authData, nil)
decoratedCallback(.success(authData))
} catch {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
}
}
Expand Down Expand Up @@ -544,9 +544,9 @@ extension Auth: AuthInterop {
withCredential: credential,
isReauthentication: false
)
decoratedCallback(authData, nil)
decoratedCallback(.success(authData))
} catch {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
}
}
Expand Down Expand Up @@ -642,9 +642,9 @@ extension Auth: AuthInterop {
do {
let authData = try await self.internalSignInAndRetrieveData(withCredential: credential,
isReauthentication: false)
decoratedCallback(authData, nil)
decoratedCallback(.success(authData))
} catch {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
}
}
Expand Down Expand Up @@ -710,7 +710,7 @@ extension Auth: AuthInterop {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
if let currentUser = self._currentUser, currentUser.isAnonymous {
let result = AuthDataResult(withUser: currentUser, additionalUserInfo: nil)
decoratedCallback(result, nil)
decoratedCallback(.success(result))
return
}
let request = SignUpNewUserRequest(requestConfiguration: self.requestConfiguration)
Expand All @@ -728,10 +728,11 @@ extension Auth: AuthInterop {
profile: nil,
username: nil,
isNewUser: true)
decoratedCallback(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo),
nil)
decoratedCallback(
.success(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo))
)
} catch {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
}
}
Expand Down Expand Up @@ -790,10 +791,11 @@ extension Auth: AuthInterop {
profile: nil,
username: nil,
isNewUser: response.isNewUser)
decoratedCallback(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo),
nil)
decoratedCallback(
.success(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo))
)
} catch {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
}
}
Expand Down Expand Up @@ -866,7 +868,7 @@ extension Auth: AuthInterop {
action: AuthRecaptchaAction.signUpPassword) { response, error in
if let error {
DispatchQueue.main.async {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
return
}
Expand All @@ -881,7 +883,8 @@ extension Auth: AuthInterop {

func internalCreateUserWithEmail(request: SignUpNewUserRequest,
inResponse: SignUpNewUserResponse? = nil,
decoratedCallback: @escaping (AuthDataResult?, Error?) -> Void) {
decoratedCallback: @escaping (Result<AuthDataResult, Error>)
-> Void) {
Task {
do {
var response: SignUpNewUserResponse
Expand All @@ -900,11 +903,11 @@ extension Auth: AuthInterop {
profile: nil,
username: nil,
isNewUser: true)
decoratedCallback(AuthDataResult(withUser: user,
additionalUserInfo: additionalUserInfo),
nil)
decoratedCallback(
.success(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo))
)
} catch {
decoratedCallback(nil, error)
decoratedCallback(.failure(error))
}
}
}
Expand Down Expand Up @@ -1009,9 +1012,9 @@ extension Auth: AuthInterop {
let actionCodeInfo = ActionCodeInfo(withOperation: operation,
email: email,
newEmail: response.verifiedEmail)
Auth.wrapMainAsync(callback: completion, withParam: actionCodeInfo, error: nil)
Auth.wrapMainAsync(callback: completion, with: .success(actionCodeInfo))
} catch {
Auth.wrapMainAsync(callback: completion, withParam: nil, error: error)
Auth.wrapMainAsync(callback: completion, with: .failure(error))
}
}
}
Expand Down Expand Up @@ -2238,23 +2241,19 @@ extension Auth: AuthInterop {
/// Invoked asynchronously on the main thread in the future.
/// - Returns: Returns a block that updates the current user.
func signInFlowAuthDataResultCallback(byDecorating callback:
((AuthDataResult?, Error?) -> Void)?) -> (AuthDataResult?, Error?) -> Void {
let authDataCallback: (((AuthDataResult?, Error?) -> Void)?, AuthDataResult?, Error?) -> Void =
{ callback, result, error in
Auth.wrapMainAsync(callback: callback, withParam: result, error: error)
}
ncooke3 marked this conversation as resolved.
Show resolved Hide resolved
return { authResult, error in
if let error {
authDataCallback(callback, nil, error)
return
}
do {
try self.updateCurrentUser(authResult?.user, byForce: false, savingToDisk: true)
} catch {
authDataCallback(callback, nil, error)
return
((AuthDataResult?, Error?) -> Void)?) -> (Result<AuthDataResult, Error>) -> Void {
return { result in
switch result {
case let .success(authResult):
do {
try self.updateCurrentUser(authResult.user, byForce: false, savingToDisk: true)
Auth.wrapMainAsync(callback: callback, with: .success(authResult))
} catch {
Auth.wrapMainAsync(callback: callback, with: .failure(error))
}
case let .failure(error):
Auth.wrapMainAsync(callback: callback, with: .failure(error))
}
authDataCallback(callback, authResult, nil)
}
}

Expand All @@ -2278,11 +2277,12 @@ extension Auth: AuthInterop {
}

class func wrapMainAsync<T: Any>(callback: ((T?, Error?) -> Void)?,
withParam param: T?,
error: Error?) -> Void {
if let callback {
DispatchQueue.main.async {
callback(param, error)
with result: Result<T, Error>) -> Void {
guard let callback else { return }
DispatchQueue.main.async {
switch result {
case let .success(success): callback(success, nil)
case let .failure(error): callback(nil, error)
}
}
}
Expand Down
13 changes: 6 additions & 7 deletions FirebaseAuth/Sources/Swift/AuthProvider/PhoneAuthProvider.swift
ncooke3 marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -265,10 +265,10 @@ import Foundation
/// - Parameter phoneNumber: The phone number to be verified.
/// - Parameter callback: The callback to be invoked on the global work queue when the flow is
/// finished.
func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
retryOnInvalidAppCredential: Bool,
uiDelegate: AuthUIDelegate?,
auditFallback: Bool = false) async throws
private func verifyClAndSendVerificationCode(toPhoneNumber phoneNumber: String,
retryOnInvalidAppCredential: Bool,
uiDelegate: AuthUIDelegate?,
auditFallback: Bool = false) async throws
-> String? {
let codeIdentity = try await verifyClient(withUIDelegate: uiDelegate)
let request = SendVerificationCodeRequest(phoneNumber: phoneNumber,
Expand Down Expand Up @@ -350,7 +350,7 @@ import Foundation
action: .mfaSmsSignIn
)
let response = try await auth.backend.call(with: request)
return response.responseInfo?.sessionInfo
return response.responseInfo.sessionInfo
}
} catch {
// For Audit fallback only after rCE check failed
Expand Down Expand Up @@ -419,9 +419,8 @@ import Foundation
MFAEnrollmentID: session.multiFactorInfo?.uid,
signInInfo: startMFARequestInfo,
requestConfiguration: auth.requestConfiguration)

let response = try await auth.backend.call(with: request)
return response.responseInfo?.sessionInfo
return response.responseInfo.sessionInfo
}
} catch {
return try await handleVerifyErrorWithRetry(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import Foundation

@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
struct StartMFASignInResponse: AuthRPCResponse {
var responseInfo: AuthProtoStartMFAPhoneResponseInfo?
let responseInfo: AuthProtoStartMFAPhoneResponseInfo
ncooke3 marked this conversation as resolved.
Show resolved Hide resolved

init(dictionary: [String: AnyHashable]) throws {
if let data = dictionary["phoneResponseInfo"] as? [String: AnyHashable] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
import Foundation

struct SendVerificationCodeResponse: AuthRPCResponse {
var verificationID: String?
let verificationID: String?

init(dictionary: [String: AnyHashable]) throws {
verificationID = dictionary["sessionInfo"] as? String
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ import Foundation
let result = AuthDataResult(withUser: user, additionalUserInfo: nil)
let decoratedCallback = self.auth
.signInFlowAuthDataResultCallback(byDecorating: completion)
decoratedCallback(result, nil)
decoratedCallback(.success(result))
} catch {
if let completion {
completion(nil, error)
Expand Down
2 changes: 1 addition & 1 deletion FirebaseAuth/Tests/Unit/RPCBaseTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ class RPCBaseTests: XCTestCase {
XCTFail("decodedRequest is not a dictionary")
}
// Dummy response to unblock await.
let _ = try self.rpcIssuer?.respond(withJSON: [:])
let _ = try self.rpcIssuer?.respond(withJSON: ["sessionInfo": "verification_id_123"])
ncooke3 marked this conversation as resolved.
Show resolved Hide resolved
}
let _ = try await authBackend.call(with: request)
}
Expand Down
Loading