---
title: "User Authentication"
canonical_url: "https://docs.sportradar.com/resources/virtual-stadium/docs/sdk/userAuthentication"
markdown_url: "https://docs.sportradar.com/resources/virtual-stadium/docs/sdk/userAuthentication.md"
last_updated: "2026-04-16T10:19:11Z"
---

# User Authentication

This guide covers authentication management and user state tracking in the Virtual Stadium Data SDK.

***

## Login Manager

The `LoginManager` handles login operations within the Virtual Stadium Data SDK. It provides functionalities to perform user authentication through **JWT token** validation and manage user sessions.

The `LoginManager` plays a crucial role in ensuring that users are authenticated before they can interact with the SDK's features. It uses JWT tokens, which are compact and secure, for authenticating users.

## Key Functions

**`login(jwtToken: String)`**

Authenticates the user with the provided JWT token. This is a prerequisite for all SDK interactions.

**`logOut()`**

Performs the logout operation, ending the user's session.

**`loginState`**

Observable flow for tracking authentication status changes.

***

## Login Implementation

Inject `LoginManager` via dependency injection and expose the `loginState` flow to your UI layer.

Monitor login state to handle different authentication statuses:

- **LOGGED\_OUT** - User is not authenticated
- **LOADING** - Authentication in progress
- **LOGGED\_IN** - Successfully authenticated
- **ERROR** - Authentication failed

**Android**

```kotlin
import ag.sportradar.virtualstadium.datasdk.services.LoginManager
import androidx.lifecycle.ViewModel
import org.koin.core.component.KoinComponent
import org.koin.core.component.get

class LoginViewModel :
    ViewModel(),
    KoinComponent {

    private val loginManager: LoginManager
        get() = get()

    val loginState = loginManager.loginState

    fun login(jwtToken: String) {
        loginManager.login(jwtToken)
    }

    fun logout() {
        loginManager.logOut()
    }
}
```

**iOS**

```swift
import VirtualStadiumDataSDK

class ExampleLoginViewModel: ObservableObject {

    private var loginManager = KoinHelper().getLoginManager()
    @Published var loginStatus: LoginStatus? = .loggedOut
    @Published var loginError: LoginError?

    init() {
        subscribeToLoginState()
    }

    private func subscribeToLoginState() {
        loginManager.loginState.subscribe(onCollect: { loginState in
            self?.loginStatus = loginState?.loginStatus
            self?.loginError = loginState?.loginError
        })
    }

    func login() {
        loginManager.login(jwtToken: "YOUR_JWT_TOKEN")
    }

    func logout() {
        loginManager.logOut()
    }
}
```

***

## Login Screen Example

Implement a login screen that responds to authentication state changes.

Handle all login states appropriately:

- Show login button when logged out
- Display loading indicator during authentication
- Navigate to main content when logged in
- Show error messages on failure

**Android**

**Jetpack Compose:**

```kotlin
@Composable
fun LoginScreen(
    modifier: Modifier = Modifier,
    loginViewModel: LoginViewModel,
) {
    val loginState by loginViewModel.loginState
        .collectAsStateWithLifecycle()

    Scaffold { paddingValues ->
        when (loginState.loginStatus) {
            LoginStatus.LOGGED_OUT -> {
                Box(
                    modifier = Modifier
                        .padding(paddingValues)
                        .fillMaxSize(),
                    contentAlignment = Alignment.BottomCenter,
                ) {
                    OutlinedButton(
                        onClick = { 
                            loginViewModel.login("YOUR_JWT_TOKEN") 
                        },
                    ) {
                        Text("Log In")
                    }
                }
            }

            LoginStatus.LOADING -> {
                Box(
                    modifier = Modifier
                        .padding(paddingValues)
                        .fillMaxSize(),
                    contentAlignment = Alignment.Center,
                ) {
                    CircularProgressIndicator()
                }
            }

            LoginStatus.LOGGED_IN -> {
                ExampleScreen(loginViewModel = loginViewModel)
            }

            LoginStatus.ERROR -> {
                Column(
                    modifier = Modifier
                        .padding(paddingValues)
                        .fillMaxSize(),
                    verticalArrangement = Arrangement.Center,
                ) {
                    Text("Error: ${loginState.loginError?.message}")
                    OutlinedButton(
                        onClick = { 
                            loginViewModel.login("YOUR_JWT_TOKEN") 
                        },
                    ) {
                        Text("Try to log in again")
                    }
                }
            }
        }
    }
}
```

**iOS**

**SwiftUI:**

```swift
import SwiftUI

struct LoginScreen: View {
    @ObservedObject var loginViewModel = ExampleLoginViewModel()

    var body: some View {
        switch loginViewModel.loginStatus {
        case .loggedOut:
            VStack {
                Spacer()
                Button("Log in",  action: {
                    loginViewModel.login()
                })
                .padding(.bottom, 40)
            }

        case .loading:
            VStack {
                ProgressView()
            }

        case .loggedIn:
            LoggedInView()

        case .error:
            ErrorScreen(errorText: "Error: \(loginViewModel.loginError?.description() ?? "Unknown error")")

        default:
            ErrorScreen(errorText: "Something went wrong!")
        }
    }
}
```

**UIKit:**

```swift
import UIKit
import Combine

class LoginViewController: UIViewController {
    private var loginViewModel = ExampleLoginViewModel()
    private var cancellables: Set<AnyCancellable> = []

    private let loginButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Log in", for: .normal)
        button.addTarget(nil, action: #selector(loginButtonTapped), 
                         for: .touchUpInside)
        return button
    }()

    private let progressView: UIActivityIndicatorView = {
        let activityIndicator = UIActivityIndicatorView(style: .large)
        activityIndicator.hidesWhenStopped = true
        return activityIndicator
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        observeViewModel()
        updateUI()
    }

    private func setupViews() {
        view.addSubview(loginButton)
        view.addSubview(progressView)
        // ...constraint setup...
    }

    private func observeViewModel() {
        loginViewModel.$loginStatus
            .receive(on: DispatchQueue.main)
            .sink { [weak self] _ in
                self?.updateUI()
            }
            .store(in: &cancellables)
    }

    private func updateUI() {
        switch loginViewModel.loginStatus {
        case .loggedOut:
            loginButton.isHidden = false
            progressView.stopAnimating()
        case .loading:
            loginButton.isHidden = true
            progressView.startAnimating()
        case .loggedIn:
            // Navigate to main screen
        case .error:
            // Show error message
        default:
            break
        }
    }

    @objc private func loginButtonTapped() {
        loginViewModel.login()
    }
}
```

***

## User Provider

The `UserProvider` is a crucial component designed to manage and maintain user-related data and state. It encapsulates functionalities essential for handling user data, managing user states, and dealing with user infractions within the application.

## Key Functionalities

- Observing and updating user state changes
- Managing user infractions (adding, retrieving, clearing)
- Handling user data based on JWT tokens
- Providing mechanisms for user timeout and ban management

The `UserProvider` ensures that user-related operations are performed in a secure, efficient, and consistent manner, maintaining the integrity of the user experience.

***

## User State

To detect state changes of the current user's status, collect changes from the SDK's `UserProvider`. The `UserState` class contains values for the user and their status.

## User Status Values

**`UserStatus.Initial`**

Initial status value before user state is determined.

**`UserStatus.Valid`**

User can post messages normally.

**`UserStatus.Timeout(remainingSeconds)`**

User is temporarily banned. The `remainingSeconds` value updates every second.

**`UserStatus.Banned`**

User is permanently banned and cannot post messages.

***

## User State Implementation

Access user state and infraction management through the `UserProvider`.

The provider exposes:

- **userState** - Current user status
- **nextInfraction** - Next infraction message
- **dismissTimerCountDown** - Auto-dismiss countdown

Methods for infraction management:

- **startAutoDismissInfraction()** - Start auto-dismiss timer
- **stopAutoDismissInfraction()** - Stop auto-dismiss timer
- **getNextInfraction()** - Retrieve next infraction
- **removeFirstInfraction()** - Remove first infraction from queue

**Android**

```kotlin
class LoginViewModel :
    ViewModel(),
    KoinComponent {

    private val userProvider: UserProvider
        get() = get()

    // Represents the current state of the user
    val userState = userProvider.userState

    // Indicates which is the next infraction for the user
    val nextInfraction = userProvider.nextInfraction

    // Countdown timer for dismissing the infraction
    val dismissInfraction = userProvider.dismissTimerCountDown

    fun startDismissInfractionJob() {
        userProvider.startAutoDismissInfraction()
    }

    fun stopDismissInfractionJob() {
        userProvider.stopAutoDismissInfraction()
    }

    fun getNextInfraction() {
        userProvider.getNextInfraction()
    }

    fun removeFirstInfraction() {
        userProvider.removeFirstInfraction()
    }
}
```

**iOS**

```swift
import VirtualStadiumDataSDK

class ExampleUserViewModel: ObservableObject {

    private var userProvider = KoinHelper().getUserProvider()

    @Published var userState: UserState?
    @Published var nextInfraction: InfractionMessage?
    @Published var dismissTimerCountDown: Int?

    init() {
        subscribeToUserProvider()
    }

    private func subscribeToUserProvider() {
        userProvider.userState.subscribe { [weak self] userState in
            self?.userState = userState
        }
        userProvider.nextInfraction.subscribe { [weak self] nextInfraction in
            self?.nextInfraction = nextInfraction
        }
        userProvider.dismissTimerCountDown.subscribe { [weak self] dismissTimerCountDown in
            self?.dismissTimerCountDown = Int(truncating: dismissTimerCountDown ?? 0)
        }
    }

    func startDismissInfractionJob() {
        userProvider.startAutoDismissInfraction()
    }

    func stopDismissInfractionJob() {
        userProvider.stopAutoDismissInfraction()
    }

    func getNextInfraction() {
        userProvider.getNextInfraction()
    }

    func removeFirstInfraction() {
        userProvider.removeFirstInfraction()
    }
}
```

> **Info**
>
> All state variables are of type `CommonStateFlow`, which can be collected (Android) or subscribed to (iOS), similar to `loginState` in the [Login Screen Example](#login-screen-example).
