mirror of
https://github.com/element-hq/matrix-authentication-service.git
synced 2026-08-27 09:00:06 +00:00
Admin API to list and get user sessions
This commit is contained in:
@@ -78,6 +78,11 @@ where
|
||||
description: Some("Manage emails associated with users".to_owned()),
|
||||
..Tag::default()
|
||||
})
|
||||
.tag(Tag {
|
||||
name: "user-sessions".to_owned(),
|
||||
description: Some("Manage browser sessions of users".to_owned()),
|
||||
..Tag::default()
|
||||
})
|
||||
.security_scheme(
|
||||
"oauth2",
|
||||
SecurityScheme::OAuth2 {
|
||||
|
||||
@@ -372,3 +372,87 @@ impl Resource for OAuth2Session {
|
||||
self.id
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser (cookie) session for a user
|
||||
#[derive(Serialize, JsonSchema)]
|
||||
pub struct UserSession {
|
||||
#[serde(skip)]
|
||||
id: Ulid,
|
||||
|
||||
/// When the object was created
|
||||
created_at: DateTime<Utc>,
|
||||
|
||||
/// When the session was finished
|
||||
finished_at: Option<DateTime<Utc>>,
|
||||
|
||||
/// The ID of the user who owns the session
|
||||
#[schemars(with = "super::schema::Ulid")]
|
||||
user_id: Ulid,
|
||||
|
||||
/// The user agent string of the client which started this session
|
||||
user_agent: Option<String>,
|
||||
|
||||
/// The last time the session was active
|
||||
last_active_at: Option<DateTime<Utc>>,
|
||||
|
||||
/// The last IP address used by the session
|
||||
last_active_ip: Option<IpAddr>,
|
||||
}
|
||||
|
||||
impl From<mas_data_model::BrowserSession> for UserSession {
|
||||
fn from(value: mas_data_model::BrowserSession) -> Self {
|
||||
Self {
|
||||
id: value.id,
|
||||
created_at: value.created_at,
|
||||
finished_at: value.finished_at,
|
||||
user_id: value.user.id,
|
||||
user_agent: value.user_agent.map(|ua| ua.raw),
|
||||
last_active_at: value.last_active_at,
|
||||
last_active_ip: value.last_active_ip,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserSession {
|
||||
/// Samples of user sessions
|
||||
pub fn samples() -> [Self; 3] {
|
||||
[
|
||||
Self {
|
||||
id: Ulid::from_bytes([0x01; 16]),
|
||||
created_at: DateTime::default(),
|
||||
finished_at: None,
|
||||
user_id: Ulid::from_bytes([0x02; 16]),
|
||||
user_agent: Some("Mozilla/5.0".to_owned()),
|
||||
last_active_at: Some(DateTime::default()),
|
||||
last_active_ip: Some("127.0.0.1".parse().unwrap()),
|
||||
},
|
||||
Self {
|
||||
id: Ulid::from_bytes([0x02; 16]),
|
||||
created_at: DateTime::default(),
|
||||
finished_at: None,
|
||||
user_id: Ulid::from_bytes([0x03; 16]),
|
||||
user_agent: None,
|
||||
last_active_at: None,
|
||||
last_active_ip: None,
|
||||
},
|
||||
Self {
|
||||
id: Ulid::from_bytes([0x03; 16]),
|
||||
created_at: DateTime::default(),
|
||||
finished_at: Some(DateTime::default()),
|
||||
user_id: Ulid::from_bytes([0x04; 16]),
|
||||
user_agent: Some("Mozilla/5.0".to_owned()),
|
||||
last_active_at: Some(DateTime::default()),
|
||||
last_active_ip: Some("127.0.0.1".parse().unwrap()),
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
impl Resource for UserSession {
|
||||
const KIND: &'static str = "user-session";
|
||||
const PATH: &'static str = "/api/admin/v1/user-sessions";
|
||||
|
||||
fn id(&self) -> Ulid {
|
||||
self.id
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ use crate::passwords::PasswordManager;
|
||||
mod compat_sessions;
|
||||
mod oauth2_sessions;
|
||||
mod user_emails;
|
||||
mod user_sessions;
|
||||
mod users;
|
||||
|
||||
pub fn router<S>() -> ApiRouter<S>
|
||||
@@ -86,4 +87,12 @@ where
|
||||
"/user-emails/{id}",
|
||||
get_with(self::user_emails::get, self::user_emails::get_doc),
|
||||
)
|
||||
.api_route(
|
||||
"/user-sessions",
|
||||
get_with(self::user_sessions::list, self::user_sessions::list_doc),
|
||||
)
|
||||
.api_route(
|
||||
"/user-sessions/{id}",
|
||||
get_with(self::user_sessions::get, self::user_sessions::get_doc),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// Copyright 2025 New Vector Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Please see LICENSE in the repository root for full details.
|
||||
|
||||
use aide::{transform::TransformOperation, OperationIo};
|
||||
use axum::{response::IntoResponse, Json};
|
||||
use hyper::StatusCode;
|
||||
use ulid::Ulid;
|
||||
|
||||
use crate::{
|
||||
admin::{
|
||||
call_context::CallContext,
|
||||
model::UserSession,
|
||||
params::UlidPathParam,
|
||||
response::{ErrorResponse, SingleResponse},
|
||||
},
|
||||
impl_from_error_for_route,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error, OperationIo)]
|
||||
#[aide(output_with = "Json<ErrorResponse>")]
|
||||
pub enum RouteError {
|
||||
#[error(transparent)]
|
||||
Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
|
||||
|
||||
#[error("User session ID {0} not found")]
|
||||
NotFound(Ulid),
|
||||
}
|
||||
|
||||
impl_from_error_for_route!(mas_storage::RepositoryError);
|
||||
|
||||
impl IntoResponse for RouteError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
let error = ErrorResponse::from_error(&self);
|
||||
let status = match self {
|
||||
Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::NotFound(_) => StatusCode::NOT_FOUND,
|
||||
};
|
||||
(status, Json(error)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn doc(operation: TransformOperation) -> TransformOperation {
|
||||
operation
|
||||
.id("getUserSession")
|
||||
.summary("Get a user session")
|
||||
.tag("user-session")
|
||||
.response_with::<200, Json<SingleResponse<UserSession>>, _>(|t| {
|
||||
let [sample, ..] = UserSession::samples();
|
||||
let response = SingleResponse::new_canonical(sample);
|
||||
t.description("User session was found").example(response)
|
||||
})
|
||||
.response_with::<404, RouteError, _>(|t| {
|
||||
let response = ErrorResponse::from_error(&RouteError::NotFound(Ulid::nil()));
|
||||
t.description("User session was not found")
|
||||
.example(response)
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "handler.admin.v1.user_sessions.get", skip_all, err)]
|
||||
pub async fn handler(
|
||||
CallContext { mut repo, .. }: CallContext,
|
||||
id: UlidPathParam,
|
||||
) -> Result<Json<SingleResponse<UserSession>>, RouteError> {
|
||||
let session = repo
|
||||
.browser_session()
|
||||
.lookup(*id)
|
||||
.await?
|
||||
.ok_or(RouteError::NotFound(*id))?;
|
||||
|
||||
Ok(Json(SingleResponse::new_canonical(UserSession::from(
|
||||
session,
|
||||
))))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use hyper::{Request, StatusCode};
|
||||
use insta::assert_json_snapshot;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState};
|
||||
|
||||
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
|
||||
async fn test_get(pool: PgPool) {
|
||||
setup();
|
||||
let mut state = TestState::from_pool(pool).await.unwrap();
|
||||
let token = state.token_with_scope("urn:mas:admin").await;
|
||||
let mut rng = state.rng();
|
||||
|
||||
// Provision a user and a user session
|
||||
let mut repo = state.repository().await.unwrap();
|
||||
let user = repo
|
||||
.user()
|
||||
.add(&mut rng, &state.clock, "alice".to_owned())
|
||||
.await
|
||||
.unwrap();
|
||||
let session = repo
|
||||
.browser_session()
|
||||
.add(&mut rng, &state.clock, &user, None)
|
||||
.await
|
||||
.unwrap();
|
||||
repo.save().await.unwrap();
|
||||
|
||||
let session_id = session.id;
|
||||
let request = Request::get(format!("/api/admin/v1/user-sessions/{session_id}"))
|
||||
.bearer(&token)
|
||||
.empty();
|
||||
let response = state.request(request).await;
|
||||
response.assert_status(StatusCode::OK);
|
||||
let body: serde_json::Value = response.json();
|
||||
assert_json_snapshot!(body, @r###"
|
||||
{
|
||||
"data": {
|
||||
"type": "user-session",
|
||||
"id": "01FSHN9AG0AJ6AC5HQ9X6H4RP4",
|
||||
"attributes": {
|
||||
"created_at": "2022-01-16T14:40:00Z",
|
||||
"finished_at": null,
|
||||
"user_id": "01FSHN9AG0MZAA6S4AF7CTV32E",
|
||||
"user_agent": null,
|
||||
"last_active_at": null,
|
||||
"last_active_ip": null
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01FSHN9AG0AJ6AC5HQ9X6H4RP4"
|
||||
}
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01FSHN9AG0AJ6AC5HQ9X6H4RP4"
|
||||
}
|
||||
}
|
||||
"###);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
// Copyright 2025 New Vector Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Please see LICENSE in the repository root for full details.
|
||||
|
||||
use aide::{transform::TransformOperation, OperationIo};
|
||||
use axum::{
|
||||
extract::{rejection::QueryRejection, Query},
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use axum_macros::FromRequestParts;
|
||||
use hyper::StatusCode;
|
||||
use mas_storage::{pagination::Page, user::BrowserSessionFilter};
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use ulid::Ulid;
|
||||
|
||||
use crate::{
|
||||
admin::{
|
||||
call_context::CallContext,
|
||||
model::{Resource, UserSession},
|
||||
params::Pagination,
|
||||
response::{ErrorResponse, PaginatedResponse},
|
||||
},
|
||||
impl_from_error_for_route,
|
||||
};
|
||||
|
||||
#[derive(Deserialize, JsonSchema, Clone, Copy)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
enum UserSessionStatus {
|
||||
Active,
|
||||
Finished,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for UserSessionStatus {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Active => write!(f, "active"),
|
||||
Self::Finished => write!(f, "finished"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(FromRequestParts, Deserialize, JsonSchema, OperationIo)]
|
||||
#[serde(rename = "UserSessionFilter")]
|
||||
#[aide(input_with = "Query<FilterParams>")]
|
||||
#[from_request(via(Query), rejection(RouteError))]
|
||||
pub struct FilterParams {
|
||||
/// Retrieve the items for the given user
|
||||
#[serde(rename = "filter[user]")]
|
||||
#[schemars(with = "Option<crate::admin::schema::Ulid>")]
|
||||
user: Option<Ulid>,
|
||||
|
||||
/// Retrieve the items with the given status
|
||||
///
|
||||
/// Defaults to retrieve all sessions, including finished ones.
|
||||
///
|
||||
/// * `active`: Only retrieve active sessions
|
||||
///
|
||||
/// * `finished`: Only retrieve finished sessions
|
||||
#[serde(rename = "filter[status]")]
|
||||
status: Option<UserSessionStatus>,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for FilterParams {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let mut sep = '?';
|
||||
|
||||
if let Some(user) = self.user {
|
||||
write!(f, "{sep}filter[user]={user}")?;
|
||||
sep = '&';
|
||||
}
|
||||
|
||||
if let Some(status) = self.status {
|
||||
write!(f, "{sep}filter[status]={status}")?;
|
||||
sep = '&';
|
||||
}
|
||||
|
||||
let _ = sep;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, OperationIo)]
|
||||
#[aide(output_with = "Json<ErrorResponse>")]
|
||||
pub enum RouteError {
|
||||
#[error(transparent)]
|
||||
Internal(Box<dyn std::error::Error + Send + Sync + 'static>),
|
||||
|
||||
#[error("User ID {0} not found")]
|
||||
UserNotFound(Ulid),
|
||||
|
||||
#[error("Invalid filter parameters")]
|
||||
InvalidFilter(#[from] QueryRejection),
|
||||
}
|
||||
|
||||
impl_from_error_for_route!(mas_storage::RepositoryError);
|
||||
|
||||
impl IntoResponse for RouteError {
|
||||
fn into_response(self) -> axum::response::Response {
|
||||
let error = ErrorResponse::from_error(&self);
|
||||
let status = match self {
|
||||
Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Self::UserNotFound(_) => StatusCode::NOT_FOUND,
|
||||
Self::InvalidFilter(_) => StatusCode::BAD_REQUEST,
|
||||
};
|
||||
(status, Json(error)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn doc(operation: TransformOperation) -> TransformOperation {
|
||||
operation
|
||||
.id("listUserSessions")
|
||||
.summary("List user sessions")
|
||||
.description("Retrieve a list of user sessions (browser sessions).
|
||||
Note that by default, all sessions, including finished ones are returned, with the oldest first.
|
||||
Use the `filter[status]` parameter to filter the sessions by their status and `page[last]` parameter to retrieve the last N sessions.")
|
||||
.tag("user-session")
|
||||
.response_with::<200, Json<PaginatedResponse<UserSession>>, _>(|t| {
|
||||
let sessions = UserSession::samples();
|
||||
let pagination = mas_storage::Pagination::first(sessions.len());
|
||||
let page = Page {
|
||||
edges: sessions.into(),
|
||||
has_next_page: true,
|
||||
has_previous_page: false,
|
||||
};
|
||||
|
||||
t.description("Paginated response of user sessions")
|
||||
.example(PaginatedResponse::new(
|
||||
page,
|
||||
pagination,
|
||||
42,
|
||||
UserSession::PATH,
|
||||
))
|
||||
})
|
||||
.response_with::<404, RouteError, _>(|t| {
|
||||
let response = ErrorResponse::from_error(&RouteError::UserNotFound(Ulid::nil()));
|
||||
t.description("User was not found").example(response)
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument(name = "handler.admin.v1.user_sessions.list", skip_all, err)]
|
||||
pub async fn handler(
|
||||
CallContext { mut repo, .. }: CallContext,
|
||||
Pagination(pagination): Pagination,
|
||||
params: FilterParams,
|
||||
) -> Result<Json<PaginatedResponse<UserSession>>, RouteError> {
|
||||
let base = format!("{path}{params}", path = UserSession::PATH);
|
||||
let filter = BrowserSessionFilter::default();
|
||||
|
||||
// Load the user from the filter
|
||||
let user = if let Some(user_id) = params.user {
|
||||
let user = repo
|
||||
.user()
|
||||
.lookup(user_id)
|
||||
.await?
|
||||
.ok_or(RouteError::UserNotFound(user_id))?;
|
||||
|
||||
Some(user)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let filter = match &user {
|
||||
Some(user) => filter.for_user(user),
|
||||
None => filter,
|
||||
};
|
||||
|
||||
let filter = match params.status {
|
||||
Some(UserSessionStatus::Active) => filter.active_only(),
|
||||
Some(UserSessionStatus::Finished) => filter.finished_only(),
|
||||
None => filter,
|
||||
};
|
||||
|
||||
let page = repo.browser_session().list(filter, pagination).await?;
|
||||
let count = repo.browser_session().count(filter).await?;
|
||||
|
||||
Ok(Json(PaginatedResponse::new(
|
||||
page.map(UserSession::from),
|
||||
pagination,
|
||||
count,
|
||||
&base,
|
||||
)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use chrono::Duration;
|
||||
use hyper::{Request, StatusCode};
|
||||
use insta::assert_json_snapshot;
|
||||
use sqlx::PgPool;
|
||||
|
||||
use crate::test_utils::{setup, RequestBuilderExt, ResponseExt, TestState};
|
||||
|
||||
#[sqlx::test(migrator = "mas_storage_pg::MIGRATOR")]
|
||||
async fn test_user_session_list(pool: PgPool) {
|
||||
setup();
|
||||
let mut state = TestState::from_pool(pool).await.unwrap();
|
||||
let token = state.token_with_scope("urn:mas:admin").await;
|
||||
let mut rng = state.rng();
|
||||
|
||||
// Provision two users, one user session for each, and finish one of them
|
||||
let mut repo = state.repository().await.unwrap();
|
||||
let alice = repo
|
||||
.user()
|
||||
.add(&mut rng, &state.clock, "alice".to_owned())
|
||||
.await
|
||||
.unwrap();
|
||||
state.clock.advance(Duration::minutes(1));
|
||||
|
||||
let bob = repo
|
||||
.user()
|
||||
.add(&mut rng, &state.clock, "bob".to_owned())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
repo.browser_session()
|
||||
.add(&mut rng, &state.clock, &alice, None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let session = repo
|
||||
.browser_session()
|
||||
.add(&mut rng, &state.clock, &bob, None)
|
||||
.await
|
||||
.unwrap();
|
||||
state.clock.advance(Duration::minutes(1));
|
||||
repo.browser_session()
|
||||
.finish(&state.clock, session)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
repo.save().await.unwrap();
|
||||
|
||||
let request = Request::get("/api/admin/v1/user-sessions")
|
||||
.bearer(&token)
|
||||
.empty();
|
||||
let response = state.request(request).await;
|
||||
response.assert_status(StatusCode::OK);
|
||||
let body: serde_json::Value = response.json();
|
||||
assert_json_snapshot!(body, @r###"
|
||||
{
|
||||
"meta": {
|
||||
"count": 2
|
||||
},
|
||||
"data": [
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "01FSHNB5309NMZYX8MFYH578R9",
|
||||
"attributes": {
|
||||
"created_at": "2022-01-16T14:41:00Z",
|
||||
"finished_at": null,
|
||||
"user_id": "01FSHN9AG0MZAA6S4AF7CTV32E",
|
||||
"user_agent": null,
|
||||
"last_active_at": null,
|
||||
"last_active_ip": null
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01FSHNB5309NMZYX8MFYH578R9"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "01FSHNB530KEPHYQQXW9XPTX6Z",
|
||||
"attributes": {
|
||||
"created_at": "2022-01-16T14:41:00Z",
|
||||
"finished_at": "2022-01-16T14:42:00Z",
|
||||
"user_id": "01FSHNB530AJ6AC5HQ9X6H4RP4",
|
||||
"user_agent": null,
|
||||
"last_active_at": null,
|
||||
"last_active_ip": null
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01FSHNB530KEPHYQQXW9XPTX6Z"
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions?page[first]=10",
|
||||
"first": "/api/admin/v1/user-sessions?page[first]=10",
|
||||
"last": "/api/admin/v1/user-sessions?page[last]=10"
|
||||
}
|
||||
}
|
||||
"###);
|
||||
|
||||
// Filter by user
|
||||
let request = Request::get(format!(
|
||||
"/api/admin/v1/user-sessions?filter[user]={}",
|
||||
alice.id
|
||||
))
|
||||
.bearer(&token)
|
||||
.empty();
|
||||
let response = state.request(request).await;
|
||||
response.assert_status(StatusCode::OK);
|
||||
let body: serde_json::Value = response.json();
|
||||
assert_json_snapshot!(body, @r###"
|
||||
{
|
||||
"meta": {
|
||||
"count": 1
|
||||
},
|
||||
"data": [
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "01FSHNB5309NMZYX8MFYH578R9",
|
||||
"attributes": {
|
||||
"created_at": "2022-01-16T14:41:00Z",
|
||||
"finished_at": null,
|
||||
"user_id": "01FSHN9AG0MZAA6S4AF7CTV32E",
|
||||
"user_agent": null,
|
||||
"last_active_at": null,
|
||||
"last_active_ip": null
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01FSHNB5309NMZYX8MFYH578R9"
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions?filter[user]=01FSHN9AG0MZAA6S4AF7CTV32E&page[first]=10",
|
||||
"first": "/api/admin/v1/user-sessions?filter[user]=01FSHN9AG0MZAA6S4AF7CTV32E&page[first]=10",
|
||||
"last": "/api/admin/v1/user-sessions?filter[user]=01FSHN9AG0MZAA6S4AF7CTV32E&page[last]=10"
|
||||
}
|
||||
}
|
||||
"###);
|
||||
|
||||
// Filter by status (active)
|
||||
let request = Request::get("/api/admin/v1/user-sessions?filter[status]=active")
|
||||
.bearer(&token)
|
||||
.empty();
|
||||
let response = state.request(request).await;
|
||||
response.assert_status(StatusCode::OK);
|
||||
let body: serde_json::Value = response.json();
|
||||
assert_json_snapshot!(body, @r###"
|
||||
{
|
||||
"meta": {
|
||||
"count": 1
|
||||
},
|
||||
"data": [
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "01FSHNB5309NMZYX8MFYH578R9",
|
||||
"attributes": {
|
||||
"created_at": "2022-01-16T14:41:00Z",
|
||||
"finished_at": null,
|
||||
"user_id": "01FSHN9AG0MZAA6S4AF7CTV32E",
|
||||
"user_agent": null,
|
||||
"last_active_at": null,
|
||||
"last_active_ip": null
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01FSHNB5309NMZYX8MFYH578R9"
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions?filter[status]=active&page[first]=10",
|
||||
"first": "/api/admin/v1/user-sessions?filter[status]=active&page[first]=10",
|
||||
"last": "/api/admin/v1/user-sessions?filter[status]=active&page[last]=10"
|
||||
}
|
||||
}
|
||||
"###);
|
||||
|
||||
// Filter by status (finished)
|
||||
let request = Request::get("/api/admin/v1/user-sessions?filter[status]=finished")
|
||||
.bearer(&token)
|
||||
.empty();
|
||||
let response = state.request(request).await;
|
||||
response.assert_status(StatusCode::OK);
|
||||
let body: serde_json::Value = response.json();
|
||||
assert_json_snapshot!(body, @r###"
|
||||
{
|
||||
"meta": {
|
||||
"count": 1
|
||||
},
|
||||
"data": [
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "01FSHNB530KEPHYQQXW9XPTX6Z",
|
||||
"attributes": {
|
||||
"created_at": "2022-01-16T14:41:00Z",
|
||||
"finished_at": "2022-01-16T14:42:00Z",
|
||||
"user_id": "01FSHNB530AJ6AC5HQ9X6H4RP4",
|
||||
"user_agent": null,
|
||||
"last_active_at": null,
|
||||
"last_active_ip": null
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01FSHNB530KEPHYQQXW9XPTX6Z"
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions?filter[status]=finished&page[first]=10",
|
||||
"first": "/api/admin/v1/user-sessions?filter[status]=finished&page[first]=10",
|
||||
"last": "/api/admin/v1/user-sessions?filter[status]=finished&page[last]=10"
|
||||
}
|
||||
}
|
||||
"###);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2025 New Vector Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Please see LICENSE in the repository root for full details.
|
||||
|
||||
mod get;
|
||||
mod list;
|
||||
|
||||
pub use self::{
|
||||
get::{doc as get_doc, handler as get},
|
||||
list::{doc as list_doc, handler as list},
|
||||
};
|
||||
@@ -1526,6 +1526,245 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/admin/v1/user-sessions": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"user-session"
|
||||
],
|
||||
"summary": "List user sessions",
|
||||
"description": "Retrieve a list of user sessions (browser sessions).\nNote that by default, all sessions, including finished ones are returned, with the oldest first.\nUse the `filter[status]` parameter to filter the sessions by their status and `page[last]` parameter to retrieve the last N sessions.",
|
||||
"operationId": "listUserSessions",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "query",
|
||||
"name": "page[before]",
|
||||
"description": "Retrieve the items before the given ID",
|
||||
"schema": {
|
||||
"description": "Retrieve the items before the given ID",
|
||||
"$ref": "#/components/schemas/ULID",
|
||||
"nullable": true
|
||||
},
|
||||
"style": "form"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "page[after]",
|
||||
"description": "Retrieve the items after the given ID",
|
||||
"schema": {
|
||||
"description": "Retrieve the items after the given ID",
|
||||
"$ref": "#/components/schemas/ULID",
|
||||
"nullable": true
|
||||
},
|
||||
"style": "form"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "page[first]",
|
||||
"description": "Retrieve the first N items",
|
||||
"schema": {
|
||||
"description": "Retrieve the first N items",
|
||||
"type": "integer",
|
||||
"format": "uint",
|
||||
"minimum": 1.0,
|
||||
"nullable": true
|
||||
},
|
||||
"style": "form"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "page[last]",
|
||||
"description": "Retrieve the last N items",
|
||||
"schema": {
|
||||
"description": "Retrieve the last N items",
|
||||
"type": "integer",
|
||||
"format": "uint",
|
||||
"minimum": 1.0,
|
||||
"nullable": true
|
||||
},
|
||||
"style": "form"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "filter[user]",
|
||||
"description": "Retrieve the items for the given user",
|
||||
"schema": {
|
||||
"description": "Retrieve the items for the given user",
|
||||
"$ref": "#/components/schemas/ULID",
|
||||
"nullable": true
|
||||
},
|
||||
"style": "form"
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "filter[status]",
|
||||
"description": "Retrieve the items with the given status\n\nDefaults to retrieve all sessions, including finished ones.\n\n* `active`: Only retrieve active sessions\n\n* `finished`: Only retrieve finished sessions",
|
||||
"schema": {
|
||||
"description": "Retrieve the items with the given status\n\nDefaults to retrieve all sessions, including finished ones.\n\n* `active`: Only retrieve active sessions\n\n* `finished`: Only retrieve finished sessions",
|
||||
"$ref": "#/components/schemas/UserSessionStatus",
|
||||
"nullable": true
|
||||
},
|
||||
"style": "form"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Paginated response of user sessions",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/PaginatedResponse_for_UserSession"
|
||||
},
|
||||
"example": {
|
||||
"meta": {
|
||||
"count": 42
|
||||
},
|
||||
"data": [
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "01040G2081040G2081040G2081",
|
||||
"attributes": {
|
||||
"created_at": "1970-01-01T00:00:00Z",
|
||||
"finished_at": null,
|
||||
"user_id": "02081040G2081040G2081040G2",
|
||||
"user_agent": "Mozilla/5.0",
|
||||
"last_active_at": "1970-01-01T00:00:00Z",
|
||||
"last_active_ip": "127.0.0.1"
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01040G2081040G2081040G2081"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "02081040G2081040G2081040G2",
|
||||
"attributes": {
|
||||
"created_at": "1970-01-01T00:00:00Z",
|
||||
"finished_at": null,
|
||||
"user_id": "030C1G60R30C1G60R30C1G60R3",
|
||||
"user_agent": null,
|
||||
"last_active_at": null,
|
||||
"last_active_ip": null
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/02081040G2081040G2081040G2"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "user-session",
|
||||
"id": "030C1G60R30C1G60R30C1G60R3",
|
||||
"attributes": {
|
||||
"created_at": "1970-01-01T00:00:00Z",
|
||||
"finished_at": "1970-01-01T00:00:00Z",
|
||||
"user_id": "040G2081040G2081040G208104",
|
||||
"user_agent": "Mozilla/5.0",
|
||||
"last_active_at": "1970-01-01T00:00:00Z",
|
||||
"last_active_ip": "127.0.0.1"
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/030C1G60R30C1G60R30C1G60R3"
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions?page[first]=3",
|
||||
"first": "/api/admin/v1/user-sessions?page[first]=3",
|
||||
"last": "/api/admin/v1/user-sessions?page[last]=3",
|
||||
"next": "/api/admin/v1/user-sessions?page[after]=030C1G60R30C1G60R30C1G60R3&page[first]=3"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "User was not found",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"errors": [
|
||||
{
|
||||
"title": "User ID 00000000000000000000000000 not found"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/admin/v1/user-sessions/{id}": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"user-session"
|
||||
],
|
||||
"summary": "Get a user session",
|
||||
"operationId": "getUserSession",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "path",
|
||||
"name": "id",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"title": "The ID of the resource",
|
||||
"$ref": "#/components/schemas/ULID"
|
||||
},
|
||||
"style": "simple"
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "User session was found",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/SingleResponse_for_UserSession"
|
||||
},
|
||||
"example": {
|
||||
"data": {
|
||||
"type": "user-session",
|
||||
"id": "01040G2081040G2081040G2081",
|
||||
"attributes": {
|
||||
"created_at": "1970-01-01T00:00:00Z",
|
||||
"finished_at": null,
|
||||
"user_id": "02081040G2081040G2081040G2",
|
||||
"user_agent": "Mozilla/5.0",
|
||||
"last_active_at": "1970-01-01T00:00:00Z",
|
||||
"last_active_ip": "127.0.0.1"
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01040G2081040G2081040G2081"
|
||||
}
|
||||
},
|
||||
"links": {
|
||||
"self": "/api/admin/v1/user-sessions/01040G2081040G2081040G2081"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "User session was not found",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"errors": [
|
||||
{
|
||||
"title": "User session ID 00000000000000000000000000 not found"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
@@ -2317,6 +2556,140 @@
|
||||
"$ref": "#/components/schemas/SelfLinks"
|
||||
}
|
||||
}
|
||||
},
|
||||
"UserSessionFilter": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filter[user]": {
|
||||
"description": "Retrieve the items for the given user",
|
||||
"$ref": "#/components/schemas/ULID",
|
||||
"nullable": true
|
||||
},
|
||||
"filter[status]": {
|
||||
"description": "Retrieve the items with the given status\n\nDefaults to retrieve all sessions, including finished ones.\n\n* `active`: Only retrieve active sessions\n\n* `finished`: Only retrieve finished sessions",
|
||||
"$ref": "#/components/schemas/UserSessionStatus",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"UserSessionStatus": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"active",
|
||||
"finished"
|
||||
]
|
||||
},
|
||||
"PaginatedResponse_for_UserSession": {
|
||||
"description": "A top-level response with a page of resources",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"data",
|
||||
"links",
|
||||
"meta"
|
||||
],
|
||||
"properties": {
|
||||
"meta": {
|
||||
"description": "Response metadata",
|
||||
"$ref": "#/components/schemas/PaginationMeta"
|
||||
},
|
||||
"data": {
|
||||
"description": "The list of resources",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/SingleResource_for_UserSession"
|
||||
}
|
||||
},
|
||||
"links": {
|
||||
"description": "Related links",
|
||||
"$ref": "#/components/schemas/PaginationLinks"
|
||||
}
|
||||
}
|
||||
},
|
||||
"SingleResource_for_UserSession": {
|
||||
"description": "A single resource, with its type, ID, attributes and related links",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"attributes",
|
||||
"id",
|
||||
"links",
|
||||
"type"
|
||||
],
|
||||
"properties": {
|
||||
"type": {
|
||||
"description": "The type of the resource",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "The ID of the resource",
|
||||
"$ref": "#/components/schemas/ULID"
|
||||
},
|
||||
"attributes": {
|
||||
"description": "The attributes of the resource",
|
||||
"$ref": "#/components/schemas/UserSession"
|
||||
},
|
||||
"links": {
|
||||
"description": "Related links",
|
||||
"$ref": "#/components/schemas/SelfLinks"
|
||||
}
|
||||
}
|
||||
},
|
||||
"UserSession": {
|
||||
"description": "The browser (cookie) session for a user",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"created_at",
|
||||
"user_id"
|
||||
],
|
||||
"properties": {
|
||||
"created_at": {
|
||||
"description": "When the object was created",
|
||||
"type": "string",
|
||||
"format": "date-time"
|
||||
},
|
||||
"finished_at": {
|
||||
"description": "When the session was finished",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"user_id": {
|
||||
"description": "The ID of the user who owns the session",
|
||||
"$ref": "#/components/schemas/ULID"
|
||||
},
|
||||
"user_agent": {
|
||||
"description": "The user agent string of the client which started this session",
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"last_active_at": {
|
||||
"description": "The last time the session was active",
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"last_active_ip": {
|
||||
"description": "The last IP address used by the session",
|
||||
"type": "string",
|
||||
"format": "ip",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"SingleResponse_for_UserSession": {
|
||||
"description": "A top-level response with a single resource",
|
||||
"type": "object",
|
||||
"required": [
|
||||
"data",
|
||||
"links"
|
||||
],
|
||||
"properties": {
|
||||
"data": {
|
||||
"$ref": "#/components/schemas/SingleResource_for_UserSession"
|
||||
},
|
||||
"links": {
|
||||
"$ref": "#/components/schemas/SelfLinks"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -2343,6 +2716,10 @@
|
||||
{
|
||||
"name": "user-email",
|
||||
"description": "Manage emails associated with users"
|
||||
},
|
||||
{
|
||||
"name": "user-sessions",
|
||||
"description": "Manage browser sessions of users"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user