Skip to content

Commit

Permalink
[Auth] Add MFA view controller and support MFA on Swift sample app (#…
Browse files Browse the repository at this point in the history
…14111)

Co-authored-by: Nick Cooke <[email protected]>
  • Loading branch information
Xiaoshouzi-gh and ncooke3 authored Nov 19, 2024
1 parent 6b99ad1 commit 380a861
Show file tree
Hide file tree
Showing 10 changed files with 283 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
EA527CAC24A0EE9600ADB9A2 /* LoginView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA527CAB24A0EE9600ADB9A2 /* LoginView.swift */; };
EAB3A1792494433500385291 /* DataSourceProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAB3A1782494433500385291 /* DataSourceProvider.swift */; };
EAB3A17C2494628200385291 /* UserViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAB3A17B2494628200385291 /* UserViewController.swift */; };
EAD8BD402CE535C400E23E30 /* MFALoginView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAD8BD3F2CE535C400E23E30 /* MFALoginView.swift */; };
EAE08EB524CF5D09006FA3A5 /* AccountLinkingViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAE08EB424CF5D09006FA3A5 /* AccountLinkingViewController.swift */; };
EAE4CBC524855E3A00245E92 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAE4CBC424855E3A00245E92 /* AppDelegate.swift */; };
EAE4CBC724855E3A00245E92 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAE4CBC624855E3A00245E92 /* SceneDelegate.swift */; };
Expand Down Expand Up @@ -128,6 +129,7 @@
EA527CAB24A0EE9600ADB9A2 /* LoginView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginView.swift; sourceTree = "<group>"; };
EAB3A1782494433500385291 /* DataSourceProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DataSourceProvider.swift; sourceTree = "<group>"; };
EAB3A17B2494628200385291 /* UserViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserViewController.swift; sourceTree = "<group>"; };
EAD8BD3F2CE535C400E23E30 /* MFALoginView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MFALoginView.swift; sourceTree = "<group>"; };
EAE08EB424CF5D09006FA3A5 /* AccountLinkingViewController.swift */ = {isa = PBXFileReference; indentWidth = 2; lastKnownFileType = sourcecode.swift; path = AccountLinkingViewController.swift; sourceTree = "<group>"; };
EAE4CBC124855E3A00245E92 /* AuthenticationExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AuthenticationExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
EAE4CBC424855E3A00245E92 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -244,6 +246,7 @@
EA20B47724973BB100B5E581 /* CustomViews */ = {
isa = PBXGroup;
children = (
EAD8BD3F2CE535C400E23E30 /* MFALoginView.swift */,
EA20B46B2495A9F900B5E581 /* SignedOutView.swift */,
EA527CAB24A0EE9600ADB9A2 /* LoginView.swift */,
);
Expand Down Expand Up @@ -561,6 +564,7 @@
EA20B510249FDB4400B5E581 /* OtherAuthMethods.swift in Sources */,
EA12697F29E33A5D00D79E66 /* CryptoUtils.swift in Sources */,
EAEBCE11248A9AA000FCEA92 /* Section.swift in Sources */,
EAD8BD402CE535C400E23E30 /* MFALoginView.swift in Sources */,
DEC2E5DF2A9583CA0090260A /* AppManager.swift in Sources */,
DEC2E5DD2A95331E0090260A /* SettingsViewController.swift in Sources */,
EA20B503249C6C3D00B5E581 /* CustomAuthViewController.swift in Sources */,
Expand Down Expand Up @@ -789,7 +793,7 @@
CODE_SIGN_STYLE = Manual;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = AuthenticationExample/SwiftApplication.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
Expand All @@ -812,7 +816,7 @@
CODE_SIGN_STYLE = Manual;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = AuthenticationExample/SwiftApplication.plist;
IPHONEOS_DEPLOYMENT_TARGET = 13.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.6;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import FirebaseAuth
import SwiftUI

struct MFALoginView: View {
@Environment(\.dismiss) private var dismiss

@State private var factorSelection: MultiFactorInfo?
// This is only needed for phone MFA.
@State private var verificationId: String?
// This is needed for both phone and TOTP MFA.
@State private var verificationCode: String = ""

private let resolver: MultiFactorResolver
private weak var delegate: (any LoginDelegate)?

init(resolver: MultiFactorResolver, delegate: (any LoginDelegate)?) {
self.resolver = resolver
self.delegate = delegate
}

var body: some View {
Text("Choose a second factor to continue.")
.padding(.top)
List(resolver.hints, id: \.self, selection: $factorSelection) {
Text($0.displayName ?? "No display name provided.")
}
.frame(height: 300)
.clipShape(RoundedRectangle(cornerRadius: 15))
.padding()

if let factorSelection {
// TODO(ncooke3): This logic handles both phone and TOTP MFA states. Investigate how to make
// more clear with better APIs.
if factorSelection.factorID == PhoneMultiFactorID, verificationId == nil {
MFAViewButton(
text: "Send Verification Code",
accentColor: .white,
backgroundColor: .orange
) {
Task { await startMfALogin() }
}
.padding()
} else {
TextField("Enter verification code.", text: $verificationCode)
.textFieldStyle(SymbolTextField(symbolName: "lock.circle.fill"))
.padding()
MFAViewButton(
text: "Sign in",
accentColor: .white,
backgroundColor: .orange
) {
Task { await finishMfALogin() }
}
.padding()
}
}
Spacer()
}
}

extension MFALoginView {
private func startMfALogin() async {
guard let factorSelection else { return }
switch factorSelection.factorID {
case PhoneMultiFactorID:
await startPhoneMultiFactorSignIn(hint: factorSelection as? PhoneMultiFactorInfo)
case TOTPMultiFactorID: break // TODO(ncooke3): Indicate to user to get verification code.
default: return
}
}

private func startPhoneMultiFactorSignIn(hint: PhoneMultiFactorInfo?) async {
guard let hint else { return }
do {
verificationId = try await PhoneAuthProvider.provider().verifyPhoneNumber(
with: hint,
uiDelegate: nil,
multiFactorSession: resolver.session
)
} catch {
print(error)
}
}

private func finishMfALogin() async {
guard let factorSelection else { return }
switch factorSelection.factorID {
case PhoneMultiFactorID:
await finishPhoneMultiFactorSignIn()
case TOTPMultiFactorID:
await finishTOTPMultiFactorSignIn(hint: factorSelection)
default: return
}
}

private func finishPhoneMultiFactorSignIn() async {
guard let verificationId else { return }
let credential = PhoneAuthProvider.provider().credential(
withVerificationID: verificationId,
verificationCode: verificationCode
)
let assertion = PhoneMultiFactorGenerator.assertion(with: credential)
do {
_ = try await resolver.resolveSignIn(with: assertion)
// MFA login was successful.
await MainActor.run {
dismiss()
delegate?.loginDidOccur(resolver: nil)
}
} catch {
print(error)
}
}

private func finishTOTPMultiFactorSignIn(hint: MultiFactorInfo) async {
// TODO(ncooke3): Disable button if verification code textfield contents is empty.
guard verificationCode.count > 0 else { return }
let assertion = TOTPMultiFactorGenerator.assertionForSignIn(
withEnrollmentID: hint.uid,
oneTimePassword: verificationCode
)
do {
_ = try await resolver.resolveSignIn(with: assertion)
// MFA login was successful.
await MainActor.run {
dismiss()
delegate?.loginDidOccur(resolver: nil)
}
} catch {
// Wrong or expired OTP. Re-prompt the user.
// TODO(ncooke3): Show error to user.
print(error)
}
}
}

private struct MFAViewButton: View {
let text: String
let accentColor: Color
let backgroundColor: Color
let action: () -> Void

var body: some View {
Button(action: action) {
HStack {
Spacer()
Text(text)
.bold()
.accentColor(accentColor)
Spacer()
}
.padding()
.background(backgroundColor)
.cornerRadius(14)
}
}
}

private struct SymbolTextField: TextFieldStyle {
let symbolName: String

func _body(configuration: TextField<Self._Label>) -> some View {
HStack {
Image(systemName: symbolName)
.foregroundColor(.orange)
.imageScale(.large)
.padding(.leading)
configuration
.padding([.vertical, .trailing])
}
.background(Color(uiColor: .secondarySystemBackground))
.cornerRadius(14)
.textInputAutocapitalization(.never)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ enum OtherAuthMethod: String {
case Passwordless = "Email Link/Passwordless"
case PhoneNumber = "Phone Auth"
case Custom = "a Custom Auth System"
case MfaLogin = "Multifactor Authentication"

var navigationTitle: String { "Sign in using \(rawValue)" }

Expand All @@ -30,6 +31,8 @@ enum OtherAuthMethod: String {
return "Enter Phone Number"
case .Custom:
return "Enter Custom Auth Token"
case .MfaLogin:
return "Choose a Second Factor to Continue"
}
}

Expand All @@ -41,13 +44,17 @@ enum OtherAuthMethod: String {
return "phone.circle"
case .Custom:
return "lock.shield"
case .MfaLogin:
return "phone.circle"
}
}

var textFieldInputText: String? {
switch self {
case .PhoneNumber:
return "Example input for +1 (123)456-7890 would be 11234567890"
case .MfaLogin:
return "Enter the index of the selected factor to continue"
default:
return nil
}
Expand All @@ -61,6 +68,8 @@ enum OtherAuthMethod: String {
return "Send Verification Code"
case .Custom:
return "Login"
case .MfaLogin:
return "Send Verification Code"
}
}

Expand All @@ -72,9 +81,17 @@ enum OtherAuthMethod: String {
return phoneNumberInfoText
case .Custom:
return customAuthInfoText
case .MfaLogin:
return mfaLoginInfoText
}
}

private var mfaLoginInfoText: String {
"""
MFA placeholder
"""
}

private var passwordlessInfoText: String {
"""
Authenticate users with only their email, \
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.

import FirebaseAuth
import Foundation

/// Delegate for signaling that a successful login with Firebase Auth has occurred
protocol LoginDelegate: NSObject {
func loginDidOccur()
func loginDidOccur(resolver: MultiFactorResolver?)
}
Loading

0 comments on commit 380a861

Please sign in to comment.