Lock SwiftUI Views to Signed-In Users
If you want to lock specific views to only signed in users in SwiftUI, we provide a special view modifier that allows you to do just that.
The .requireLogin()
View Modifier
You can use the .requireLogin()
view modifier to lock a view behind sign-in view if the
user isn't logged in. Simple as that.
import SwiftUI
import FirebaseKit
struct ContentView: View {
@EnvironmentObject var db: DB
var body: some View {
// This view will only be shown if the user is the user is logged in
// Otherwise, it will a sign in view
Text("Only for logged in users")
.requireLogin(db: db, onCancel: {})
}
}
View Modifier definition:
extension View {
public func requireLogin(
db: DB,
navTitle: LocalizedStringKey = "",
onCancel: @escaping () -> Void
) -> some View {}
}
db
- TheDB
object that is used to check if the user is signed in. Accessed through the@EnvironmentObject
property wrapper.navTitle
- (Optional) The title of the navigation bar when the user is redirected to the sign-in view.onCancel
- (Optional) action to perform when the user presses on cancel. Use this to navigate back to the previous view (pop to root in NavigationStack).
Implementation Example
As an example to demonstrate the usage of the .requireLogin()
view modifier, we will use the AccountSettingsView
that requires the user to be logged in in order to access the logged in account's settings.
public struct AccountSettingsView: View {
@EnvironmentObject var db: DB
public init(popBackToRoot: @escaping () -> Void) {
self.popBackToSettings = popBackToRoot
}
public var body: some View {
List {
// ... account settings
}
// ...
.navigationTitle("Your Account")
.requireLogin(db: db, onCancel: popBackToSettings)
// ...
}
// ...
}
The .visibleOnlyToUserWithID()
View Modifier
If you want to make sure that a view is only shown to a specific user, you can use the
.visibleOnlyToUserWithID()
view modifier.
extension View {
public func visibleOnlyToUserWithID(
_ userID: String?,
db: DB,
onCancel: @escaping () -> Void
) -> some View { }
}
userID
- The user ID to check against. If user isn't logged in or the user ID doesn't match, the view will not be shown. Instead a hero view saying "Sorry, you can't access this" will be shown.db
- TheDB
object that is used to check if the user is signed in.onCancel
- In the top left corner, a cancel button will be shown. Use this to navigate back to the previous view (example: pop to root in NavigationStack).
Do not, I repeat, DO NOT use this as a security measure. It's a nice convenience feature, and a "first layer of defense", but always validate the user's permissions on the server-side. You can use AuthKit-related features on the backend to achieve just that.