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] Add general MFA sign-in sheet #14116

Merged
merged 2 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,178 @@
// 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 = ""

let resolver: MultiFactorResolver

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
) {
// TODO(ncooke3): Does this task inherit a higher priority? What about the regular SwiftUI
// button?
Task(priority: .userInitiated, operation: 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(priority: .userInitiated, operation: 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)
dismiss()
} 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.
dismiss()
} 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 @@ -27,6 +27,8 @@ import GameKit
import GoogleSignIn
import UIKit

import SwiftUI

// For Sign in with Apple
import AuthenticationServices
import CryptoKit
Expand Down Expand Up @@ -355,10 +357,8 @@ class AuthViewController: UIViewController, DataSourceProviderDelegate {
}

private func performMfaLoginFlow(resolver: MultiFactorResolver) {
let mfaLoginController = MFALoginViewController(resolver: resolver)
mfaLoginController.delegate = self
let navMfaLoginController = UINavigationController(rootViewController: mfaLoginController)
navigationController?.present(navMfaLoginController, animated: true)
let mfaLoginController = UIHostingController(rootView: MFALoginView(resolver: resolver))
present(mfaLoginController, animated: true)
}

private func performAnonymousLoginFlow() {
Expand Down

This file was deleted.