Authentication

  • Authenticates with the UniFi controller

    Establishes a session with the UniFi controller using the provided credentials. This method must be called before making any API requests that require authentication. Supports both UniFi Network Controller and UniFi OS authentication endpoints.

    Returns Promise<boolean>

    Promise that resolves to true when login is successful

    Throws

    When login credentials are invalid

    Throws

    When unable to connect to the controller

    Throws

    When client configuration is invalid

    Example

    try {
    const success = await authAPI.login();
    console.log('Successfully logged in:', success);
    } catch (error) {
    if (error instanceof AuthenticationError) {
    console.error('Invalid credentials');
    } else {
    console.error('Login failed:', error.message);
    }
    }

    See

    Since

    1.0.0

    Remarks

    PHP: login() -> return $this->is_logged_in;

  • Logs out from the UniFi controller

    Terminates the current session with the UniFi controller and clears all authentication cookies. This method should be called when finished with the client. Always succeeds locally even if the server logout request fails.

    Returns Promise<boolean>

    Promise that resolves to true when logout is successful

    Example

    // Always logout when done
    try {
    const success = await authAPI.logout();
    console.log('Successfully logged out:', success);
    } catch (error) {
    console.warn('Logout failed, but session cleared locally');
    }

    See

    Since

    1.0.0

    Remarks

    PHP: logout() -> return $this->is_logged_in;

  • Checks if the client is currently authenticated

    Returns the current authentication status without making any network requests. Note that this only reflects the local session state and doesn't verify if the session is still valid on the server.

    Returns boolean

    true if the client has an active session, false otherwise

    Example

    if (!authAPI.isAuthenticated()) {
    await authAPI.login();
    }

    // Now safe to make API calls
    const devices = await client.listDevices();

    See

    Since

    1.0.0

  • Retrieves current session information

    Returns detailed information about the current session including authentication status, login time, last activity, and user details.

    Returns SessionInfo

    Session information object

    Example

    const sessionInfo = authAPI.getSessionInfo();
    console.log(`Logged in as: ${sessionInfo.username}`);
    console.log(`Site: ${sessionInfo.site}`);
    console.log(`Session active: ${sessionInfo.isAuthenticated}`);

    if (sessionInfo.loginTime) {
    const duration = Date.now() - sessionInfo.loginTime.getTime();
    console.log(`Session duration: ${Math.round(duration / 1000)}s`);
    }

    See

    Since

    1.0.0

  • Gets the authenticated username

    Returns the username of the currently authenticated user. Returns undefined if not authenticated.

    Returns undefined | string

    Username if authenticated, undefined otherwise

    Example

    const username = authAPI.getUsername();
    if (username) {
    console.log(`Authenticated as: ${username}`);
    } else {
    console.log('Not authenticated');
    }

    See

    Since

    1.0.0

  • Gets the configured site name

    Returns the site name that this client instance is configured to work with. All API operations will be performed in the context of this site.

    Returns string

    The site name (defaults to 'default' if not specified in config)

    Example

    const site = authAPI.getSite();
    console.log(`Working with site: ${site}`);

    See

    getSessionInfo for complete session information

    Since

    1.0.0

  • Ensures the client is authenticated

    Checks current authentication status and performs login or session refresh as needed. This method is called automatically by API methods but can be called manually to ensure authentication before making multiple API calls.

    Returns Promise<void>

    Throws

    When authentication fails

    Throws

    When session has expired and refresh fails

    Example

    // Ensure authentication before making multiple API calls
    await authAPI.ensureAuthenticated();

    // Now safe to make multiple API calls without re-authentication overhead
    const devices = await client.listDevices();
    const clients = await client.listUsers();
    const sites = await client.listSites();

    See

    Since

    1.0.0

  • Wraps an API call with automatic authentication

    Ensures authentication before executing the API call and handles re-authentication if the session expires during the call. This is useful for making custom API calls that need authentication handling.

    Type Parameters

    • T

      Return type of the API call

    Parameters

    • apiCall: (() => Promise<T>)

      Function that makes the API call

        • (): Promise<T>
        • Returns Promise<T>

    Returns Promise<T>

    Promise resolving to the API call result

    Throws

    When authentication fails

    Example

    // Make a custom authenticated API call
    const customData = await authAPI.withAuth(async () => {
    return httpClient.get('/api/s/default/stat/health');
    });

    // The authentication is handled automatically
    console.log('Health data:', customData);

    See

    ensureAuthenticated for manual authentication check

    Since

    1.0.0

  • Gets the underlying session manager instance

    Provides access to the internal session manager for advanced session management scenarios. Use with caution as this exposes internal implementation.

    Returns SessionManager

    The session manager instance

    Example

    const sessionManager = authAPI.getSessionManager();

    // Advanced usage - check if session needs refresh
    await sessionManager.ensureAuthenticated();

    Since

    1.0.0

  • Gets the underlying HTTP client instance

    Provides access to the internal HTTP client for advanced usage scenarios such as custom request configuration or direct API calls. Use with caution as this exposes internal implementation.

    Returns HTTPClient

    The HTTP client instance

    Example

    const httpClient = authAPI.getHttpClient();

    // Make a custom API call (authentication not handled automatically)
    const response = await httpClient.get('/api/s/default/stat/health');

    See

    withAuth for authenticated custom API calls

    Since

    1.0.0

Constructors