Skip to main content

SessionClient

Struct SessionClient 

Source
pub struct SessionClient { /* private fields */ }
Expand description

Raw HTTP client for the UniFi controller’s session API.

Handles the { data: [], meta: { rc, msg } } envelope, site-scoped URL construction, and platform-aware path prefixing. All methods return unwrapped data payloads – the envelope is stripped before the caller sees it.

Implementations§

Source§

impl SessionClient

Source

pub async fn login( &self, username: &str, password: &SecretString, totp_token: Option<&SecretString>, ) -> Result<(), Error>

Authenticate with the controller using username/password.

If the controller has MFA enabled it returns HTTP 499. When a totp_token is provided, we complete the two-step challenge automatically. Without one, Error::TwoFactorRequired is returned so the caller can prompt the user.

Source

pub async fn login_with_cache( &self, username: &str, password: &SecretString, totp_token: Option<&SecretString>, cache: &SessionCache, ) -> Result<(), Error>

Attempt to restore a session from cache, falling back to fresh login.

If a cached session is available and the validation probe succeeds, the cookie and CSRF token are restored without hitting the login endpoint. Otherwise, performs a normal login and caches the result.

Source

pub async fn logout(&self) -> Result<(), Error>

End the current session.

Platform-specific logout endpoint:

  • UniFi OS: POST /api/auth/logout
  • Standalone: POST /api/logout
Source

pub async fn detect_platform( base_url: &Url, ) -> Result<ControllerPlatform, Error>

Auto-detect the controller platform by probing login endpoints.

Tries the UniFi OS endpoint first (/api/auth/login). If it responds (even with an error), we’re on UniFi OS. If the connection fails or returns 404, falls back to standalone detection.

Source§

impl SessionClient

Source

pub fn new( base_url: Url, site: String, platform: ControllerPlatform, transport: &TransportConfig, ) -> Result<Self, Error>

Create a new session client from a TransportConfig.

If the config doesn’t already include a cookie jar, one is created automatically (session auth requires cookies). The base_url should be the controller root (e.g. https://192.168.1.1 for UniFi OS or https://controller:8443 for standalone).

Source

pub fn with_client( http: Client, base_url: Url, site: String, platform: ControllerPlatform, auth: SessionAuth, ) -> Self

Create a session client with a pre-built reqwest::Client.

Use this when you already have a client with a session cookie in its jar (e.g. after authenticating via a shared client).

Source

pub fn auth(&self) -> SessionAuth

The authentication method used by this client.

Source

pub fn site(&self) -> &str

The current site identifier.

Source

pub fn http(&self) -> &Client

The underlying HTTP client (for auth flows that need direct access).

Source

pub fn base_url(&self) -> &Url

The controller base URL.

Source

pub fn platform(&self) -> ControllerPlatform

The detected controller platform.

Source

pub fn cookie_header(&self) -> Option<String>

Extract the session cookie header value for WebSocket auth.

Returns the Cookie header string (e.g. "TOKEN=abc123") if a cookie jar is available and contains cookies for the controller URL.

Source

pub async fn raw_get(&self, path: &str) -> Result<Value, Error>

Send a raw GET to an arbitrary path (no envelope unwrapping).

The path is appended directly after {base}{prefix}/.

Source

pub async fn raw_post(&self, path: &str, body: &Value) -> Result<Value, Error>

Send a raw POST to an arbitrary path (no envelope unwrapping).

Source

pub async fn raw_put(&self, path: &str, body: &Value) -> Result<Value, Error>

Send a raw PUT to an arbitrary path (no envelope unwrapping).

Source

pub async fn raw_patch(&self, path: &str, body: &Value) -> Result<Value, Error>

Send a raw PATCH to an arbitrary path (no envelope unwrapping).

Source

pub async fn raw_delete(&self, path: &str) -> Result<(), Error>

Send a raw DELETE to an arbitrary path (no envelope unwrapping).

Source§

impl SessionClient

Source

pub async fn list_clients(&self) -> Result<Vec<SessionClientEntry>, Error>

List all currently connected clients (stations).

GET /api/s/{site}/stat/sta

Source

pub async fn block_client(&self, mac: &str) -> Result<(), Error>

Block a client by MAC address.

POST /api/s/{site}/cmd/stamgr with {"cmd": "block-sta", "mac": "..."}

Source

pub async fn unblock_client(&self, mac: &str) -> Result<(), Error>

Unblock a client by MAC address.

POST /api/s/{site}/cmd/stamgr with {"cmd": "unblock-sta", "mac": "..."}

Source

pub async fn kick_client(&self, mac: &str) -> Result<(), Error>

Disconnect (kick) a client.

POST /api/s/{site}/cmd/stamgr with {"cmd": "kick-sta", "mac": "..."}

Source

pub async fn forget_client(&self, mac: &str) -> Result<(), Error>

Forget (permanently remove) a client by MAC address.

POST /api/s/{site}/cmd/stamgr with {"cmd": "forget-sta", "macs": [...]}

Source

pub async fn authorize_guest( &self, mac: &str, minutes: u32, up_kbps: Option<u32>, down_kbps: Option<u32>, quota_mb: Option<u32>, ) -> Result<(), Error>

Authorize a guest client on the hotspot portal.

POST /api/s/{site}/cmd/stamgr with guest authorization parameters.

  • mac: Client MAC address
  • minutes: Authorization duration in minutes
  • up_kbps: Optional upload bandwidth limit (Kbps)
  • down_kbps: Optional download bandwidth limit (Kbps)
  • quota_mb: Optional data transfer quota (MB)
Source

pub async fn unauthorize_guest(&self, mac: &str) -> Result<(), Error>

Revoke guest authorization for a client.

POST /api/s/{site}/cmd/stamgr with {"cmd": "unauthorize-guest", "mac": "..."}

Source

pub async fn list_users(&self) -> Result<Vec<SessionUserEntry>, Error>

List all known users (includes offline clients with reservations).

GET /api/s/{site}/rest/user

Source

pub async fn set_client_fixed_ip( &self, mac: &str, ip: &str, network_id: &str, ) -> Result<(), Error>

Set a fixed IP (DHCP reservation) for a client.

Looks up the client in rest/user by MAC. If already known, PUTs an update; otherwise POSTs a new user entry.

Source

pub async fn remove_client_fixed_ip( &self, mac: &str, network_id: Option<&str>, ) -> Result<(), Error>

Remove a fixed IP (DHCP reservation) from a client.

If network_id is provided, only the reservation on that network is removed. Otherwise all reservations for the MAC are cleared.

Source§

impl SessionClient

Source

pub async fn list_devices(&self) -> Result<Vec<SessionDevice>, Error>

List all devices with full statistics.

GET /api/s/{site}/stat/device

Source

pub async fn get_device( &self, mac: &str, ) -> Result<Option<SessionDevice>, Error>

Get a single device by MAC address.

Filters the device list by MAC. Returns None if no device matches.

Source

pub async fn adopt_device(&self, mac: &str) -> Result<(), Error>

Adopt a pending device.

POST /api/s/{site}/cmd/devmgr with {"cmd": "adopt", "mac": "..."}

Source

pub async fn restart_device(&self, mac: &str) -> Result<(), Error>

Restart a device.

POST /api/s/{site}/cmd/devmgr with {"cmd": "restart", "mac": "..."}

Source

pub async fn upgrade_device( &self, mac: &str, firmware_url: Option<&str>, ) -> Result<(), Error>

Upgrade device firmware.

If url is Some, upgrades from that URL (cmd: "upgrade-external"). Otherwise upgrades from Ubiquiti’s cloud (cmd: "upgrade").

Source

pub async fn provision_device(&self, mac: &str) -> Result<(), Error>

Force re-provision a device configuration.

POST /api/s/{site}/cmd/devmgr with {"cmd": "force-provision", "mac": "..."}

Source

pub async fn speedtest(&self) -> Result<(), Error>

Trigger a site speed test (gateway).

POST /api/s/{site}/cmd/devmgr with {"cmd": "speedtest"}

Source

pub async fn locate_device(&self, mac: &str, enable: bool) -> Result<(), Error>

Toggle the LED locator on a device.

enable: true sends set-locate, false sends unset-locate.

Source§

impl SessionClient

Source

pub async fn list_events( &self, count: Option<u32>, ) -> Result<Vec<SessionEvent>, Error>

List recent events.

GET /api/s/{site}/stat/event

If count is provided, limits the number of events returned by appending ?_limit={count} to the request.

Source

pub async fn list_alarms(&self) -> Result<Vec<SessionAlarm>, Error>

List active alarms.

GET /api/s/{site}/stat/alarm

Source

pub async fn archive_alarm(&self, id: &str) -> Result<(), Error>

Archive (acknowledge) a specific alarm by its ID.

POST /api/s/{site}/cmd/evtmgr with {"cmd": "archive-alarm", "_id": "..."}

Source

pub async fn archive_all_alarms(&self) -> Result<(), Error>

Archive all alarms for the active site.

POST /api/s/{site}/cmd/evtmgr with {"cmd": "archive-all-alarms"}

Source§

impl SessionClient

Source

pub async fn list_nat_rules(&self) -> Result<Vec<Value>, Error>

List all NAT rules via the v2 API.

GET /v2/api/site/{site}/nat

Source

pub async fn create_nat_rule(&self, body: &Value) -> Result<Value, Error>

Create a NAT rule via the v2 API.

POST /v2/api/site/{site}/nat

Source

pub async fn update_nat_rule( &self, rule_id: &str, body: &Value, ) -> Result<Value, Error>

Update a NAT rule via the v2 API.

PUT /v2/api/site/{site}/nat/{rule_id}

Source

pub async fn delete_nat_rule(&self, rule_id: &str) -> Result<(), Error>

Delete a NAT rule via the v2 API.

DELETE /v2/api/site/{site}/nat/{rule_id}

Source§

impl SessionClient

Source

pub async fn list_network_conf(&self) -> Result<Vec<Value>, Error>

List raw networkconf records for the current site.

Source

pub async fn create_network_conf( &self, body: &Value, ) -> Result<Vec<Value>, Error>

Create a networkconf record for the current site.

Source

pub async fn update_network_conf( &self, record_id: &str, body: &Value, ) -> Result<Vec<Value>, Error>

Update a networkconf record for the current site.

Source

pub async fn delete_network_conf( &self, record_id: &str, ) -> Result<Vec<Value>, Error>

Delete a networkconf record for the current site.

Source§

impl SessionClient

Source

pub async fn list_sites(&self) -> Result<Vec<SessionSite>, Error>

List all sites visible to the authenticated user.

GET /api/self/sites (controller-level, not site-scoped)

Source

pub async fn get_site_settings(&self) -> Result<Vec<Value>, Error>

Get all site settings.

GET /api/s/{site}/rest/setting

Source

pub async fn create_site( &self, name: &str, description: &str, ) -> Result<(), Error>

Create a new site.

POST /api/s/{site}/cmd/sitemgr with {"cmd": "add-site", "name": "...", "desc": "..."}

Source

pub async fn delete_site(&self, name: &str) -> Result<(), Error>

Delete a site.

POST /api/s/{site}/cmd/sitemgr with {"cmd": "delete-site", "name": "..."}

Source

pub async fn invite_admin( &self, name: &str, email: &str, role: &str, ) -> Result<(), Error>

Invite a site administrator.

POST /api/s/{site}/cmd/sitemgr with {"cmd": "invite-admin", ...}

Source

pub async fn revoke_admin(&self, admin_id: &str) -> Result<(), Error>

Revoke a site administrator.

POST /api/s/{site}/cmd/sitemgr with {"cmd": "revoke-admin", "admin": "..."}

Source

pub async fn set_site_setting( &self, key: &str, body: &Value, ) -> Result<(), Error>

Update a site setting.

PUT /api/s/{site}/set/setting/{key} with an arbitrary JSON body.

Source

pub async fn update_admin( &self, admin_id: &str, role: Option<&str>, ) -> Result<(), Error>

Update site administrator role.

POST /api/s/{site}/cmd/sitemgr with {"cmd": "update-admin", ...}

Source§

impl SessionClient

Source

pub async fn get_site_stats( &self, interval: &str, start: Option<i64>, end: Option<i64>, attrs: Option<&[String]>, ) -> Result<Vec<Value>, Error>

Fetch site-level historical statistics.

POST /api/s/{site}/stat/report/{interval}.site

The interval parameter should be one of: "5minutes", "hourly", "daily". Returns loosely-typed JSON because the field set varies by report type.

Source

pub async fn get_device_stats( &self, interval: &str, macs: Option<&[String]>, attrs: Option<&[String]>, ) -> Result<Vec<Value>, Error>

Fetch per-device historical statistics.

POST /api/s/{site}/stat/report/{interval}.device

If macs is provided, results are filtered to those devices.

Source

pub async fn get_client_stats( &self, interval: &str, macs: Option<&[String]>, attrs: Option<&[String]>, ) -> Result<Vec<Value>, Error>

Fetch per-client historical statistics.

POST /api/s/{site}/stat/report/{interval}.user

If macs is provided, results are filtered to those clients.

Source

pub async fn get_gateway_stats( &self, interval: &str, start: Option<i64>, end: Option<i64>, attrs: Option<&[String]>, ) -> Result<Vec<Value>, Error>

Fetch gateway historical statistics.

POST /api/s/{site}/stat/report/{interval}.gw

Source

pub async fn get_dpi_stats( &self, group_by: &str, macs: Option<&[String]>, ) -> Result<Vec<Value>, Error>

Fetch DPI (Deep Packet Inspection) statistics.

Tries multiple session DPI endpoints for compatibility across firmware versions:

  1. stat/stadpi with MAC filter — when macs is provided
  2. stat/sitedpi with type filter — site-level aggregated stats
  3. stat/dpi (unfiltered GET) — fallback for firmware that only populates this endpoint

The group_by parameter selects the DPI grouping: "by_app" or "by_cat". Returns empty data if DPI tracking is not enabled on the controller.

Source§

impl SessionClient

Source

pub async fn get_sysinfo(&self) -> Result<Value, Error>

Get controller system information.

GET /api/s/{site}/stat/sysinfo

Returns loosely-typed JSON because the field set varies by platform and firmware version.

Source

pub async fn get_health(&self) -> Result<Vec<Value>, Error>

Get site health dashboard metrics.

GET /api/s/{site}/stat/health

Returns subsystem health entries (wan, lan, wlan, vpn, etc.).

Source

pub async fn list_backups(&self) -> Result<Vec<Value>, Error>

List available controller backups.

POST /api/s/{site}/cmd/backup with {"cmd": "list-backups"}

Source

pub async fn delete_backup(&self, filename: &str) -> Result<(), Error>

Delete a backup file from the controller.

POST /api/s/{site}/cmd/backup with {"cmd": "delete-backup", "filename": "..."}

Source

pub async fn download_backup(&self, filename: &str) -> Result<Vec<u8>, Error>

Download a backup file from the controller.

GET /dl/autobackup/{filename}

Source

pub async fn list_admins(&self) -> Result<Vec<Value>, Error>

List controller admins.

GET /api/stat/admin — controller-level (not site-scoped).

Source

pub async fn create_backup(&self) -> Result<(), Error>

Create a new controller backup.

POST /api/s/{site}/cmd/backup with {"cmd": "backup"}

Source

pub async fn reboot_controller(&self) -> Result<(), Error>

Reboot the controller.

POST /api/system/reboot

Source

pub async fn poweroff_controller(&self) -> Result<(), Error>

Power off the controller.

POST /api/system/poweroff

Source§

impl SessionClient

Source

pub async fn get_client_roams( &self, mac: &str, limit: Option<u32>, ) -> Result<Vec<Value>, Error>

Get a client’s connection timeline: connects, disconnects, and roams.

GET /v2/api/site/{site}/system-log/client-connection/{mac}

Quirk: the MAC must appear in both the URL path and the ?mac= query parameter.

Source§

impl SessionClient

Source

pub async fn list_ipsec_sa(&self) -> Result<Vec<IpsecSa>, Error>

Source

pub async fn get_openvpn_port_suggestions(&self) -> Result<Value, Error>

Suggest available OpenVPN ports via the v2 API.

GET /v2/api/site/{site}/network/port-suggest?service=openvpn

Source

pub async fn list_vpn_client_connections(&self) -> Result<Vec<Value>, Error>

List VPN client connections via the v2 API.

GET /v2/api/site/{site}/vpn/connections

Source

pub async fn restart_vpn_client_connection( &self, connection_id: &str, ) -> Result<Value, Error>

Restart a VPN client connection via the v2 API.

POST /v2/api/site/{site}/vpn/{connection_id}/restart

Source

pub async fn list_magic_site_to_site_vpn_configs( &self, ) -> Result<Vec<Value>, Error>

List magic site-to-site VPN configs via the v2 API.

GET /v2/api/site/{site}/magicsitetositevpn/configs

Source

pub async fn download_openvpn_configuration( &self, server_id: &str, ) -> Result<Vec<u8>, Error>

Download an OpenVPN client configuration via the v2 API.

GET /v2/api/site/{site}/vpn/openvpn/{server_id}/configuration

Source§

impl SessionClient

Source

pub async fn list_rogue_aps( &self, within_secs: Option<i64>, ) -> Result<Vec<RogueAp>, Error>

List neighboring / rogue access points detected by your APs.

GET /api/s/{site}/stat/rogueap

Quirk: within_secs uses Unix epoch seconds semantics, not milliseconds like many other UniFi stats routes.

Source

pub async fn list_channels(&self) -> Result<Vec<ChannelAvailability>, Error>

List per-radio regulatory channel availability.

GET /api/s/{site}/stat/current-channel

Source

pub async fn get_client_wifi_experience( &self, client_ip: &str, ) -> Result<Value, Error>

Get per-client live Wi-Fi experience metrics.

GET /v2/api/site/{site}/wifiman/{client_ip}/

Quirk: Band codes from this endpoint (2.4g, 5g, 6g) differ from stat/sta (ng, na, 6e).

Source§

impl SessionClient

Source

pub async fn list_wireguard_peers( &self, server_id: &str, ) -> Result<Vec<Value>, Error>

List WireGuard peers for a specific remote-access server via the v2 API.

GET /v2/api/site/{site}/wireguard/{server_id}/users?networkId={server_id}

Source

pub async fn list_all_wireguard_peers(&self) -> Result<Vec<Value>, Error>

List WireGuard peers across all servers via the v2 API.

GET /v2/api/site/{site}/wireguard/users

Source

pub async fn get_wireguard_peer_existing_subnets(&self) -> Result<Value, Error>

List existing subnets already used by WireGuard peers.

GET /v2/api/site/{site}/wireguard/users/existing-subnets

Source

pub async fn create_wireguard_peers( &self, server_id: &str, body: &Value, ) -> Result<Value, Error>

Create one or more WireGuard peers via the v2 API.

POST /v2/api/site/{site}/wireguard/{server_id}/users/batch

Source

pub async fn update_wireguard_peers( &self, server_id: &str, body: &Value, ) -> Result<Value, Error>

Update one or more WireGuard peers via the v2 API.

PUT /v2/api/site/{site}/wireguard/{server_id}/users/batch

Source

pub async fn delete_wireguard_peers( &self, server_id: &str, body: &Value, ) -> Result<Value, Error>

Delete one or more WireGuard peers via the v2 API.

POST /v2/api/site/{site}/wireguard/{server_id}/users/batch_delete

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more