Skip to content

Auth State

A user's authentication state is described by the AuthState enum.

swift
public enum AuthState {
  /// AuthState has not been determined yet, show loading
  case notReady
  /// User is unauthenticated
  case unauthenticated
  // User is authenticated and has an associated PrivyUser object
  case authenticated(PrivyUser)
}

Auth state is exposed as a Publisher on the Privy object:

swift
public protocol Privy {
  /// A publisher that emits auth state changes.
  var authStatePublisher: AnyPublisher<AuthState, Never> { get }
}

There are various ways to determine user's auth state, outlined below:

1. Directly grab the User

As a convenience, you can grab the user object directly from the Privy instance. If the user is not null, there is an authenticated user.

swift
let privyUser = privy.user

if (privyUser != null) {
  // User is authenticated
  let linkedAccounts = privyUser.linkedAccounts
}

2. Grab the user's current auth state

swift
public protocol Privy {
  /// The user's current auth state.
  var authState: AuthState { get }
}
swift
// Grab current auth state
if case .authenticated(let user) = privy.authState {
  // User is authenticated. Grab the user's linked accounts
  let linkedAccounts = user.linkedAccounts
}

3. Subscribe to auth state updates

swift
privy.authStatePublisher
  .receive(on: RunLoop.main)
  .sink { authState in
    switch authState {
    case .authenticated(let user):
      // User is authenticated. Grab the user's linked accounts
      let linkedAccounts = user.linkedAccounts
    case .notReady:
      // Privy not yet ready. Call privy.awaitReady()
    case .unauthenticated:
      // User in not authenticated. Perhaps show login screen.
    }
  }