Skip to content

Auth State

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

dart
/// Base class representing different authentication states.
sealed class AuthState {
  const AuthState();
}

/// Represents the initial state before authentication status is determined.
class NotReady extends AuthState {
  const NotReady();
}

/// Represents the state when the user is not authenticated.
class Unauthenticated extends AuthState {
  const Unauthenticated();
}

/// Represents the state when the user is authenticated.
class Authenticated extends AuthState {
  final PrivyUser user;

  /// Constructor accepting the authenticated user's details.
  const Authenticated(this.user);
}

The current auth state and an auth state stream are accessible directly on the Privy object.

dart
abstract interface class Privy {
  // Get the current authentication state.
  AuthState get currentAuthState;

  // A stream for auth state updates.
  Stream<AuthState> get authStateStream;
}

Accessing authentication state

There are various ways to determine user's auth state, outlined below. Mix and max the options to fit the needs of your application.

1. Directly retrieve 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.

dart
final privyUser = privy.user;

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

2. Retrieve the current auth state

dart
// Grab current auth state
final currentAuthState = privy.currentAuthState;

if (currentAuthState is Authenticated) {
  // User is authenticated. Retrieve the associated user from the auth state.
  final privyUser = currentAuthState.user;
  final linkedAccounts = privyUser.linkedAccounts;
}

3. Subscribe to auth state updates

dart
privy.authStateStream.listen((authState) {
  switch (authState) {
    case Authenticated():
      // User is authenticated. Retrieve the user.
      final privyUser = authState.user;
      final userId = privyUser.linkedAccounts;
      break;
    case NotReady():
      // Privy is not yet ready. Ensure Privy is initialized first.
      break;
    case Unauthenticated():
      // User is not authenticated. You may want to show the login screen.
      break;
  }
});