v3 : une session dure jusqu'à ce qu'on la ferme, l'administration ferme celles d'une identité

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Yvv
2026-10-23 08:45:26 +02:00
co-authored by Claude Opus 5.5
parent 422b45ab75
commit cf634c25d2
11 changed files with 163 additions and 13 deletions
+35 -1
View File
@@ -7,6 +7,7 @@ use crate::error::{AppError, AppResult};
use crate::util;
use axum::Json;
use axum::extract::{Path, State};
use axum::http::HeaderMap;
use serde::Deserialize;
use serde_json::json;
@@ -14,7 +15,11 @@ fn admin_only(user: &IdentityRow) -> AppResult<()> {
if trustin_access::manages_access(&user.to_identity()) { Ok(()) } else { Err(AppError::Forbidden) }
}
pub async fn overview(State(state): State<AppState>, User(user): User) -> AppResult<Json<serde_json::Value>> {
pub async fn overview(
State(state): State<AppState>,
headers: HeaderMap,
User(user): User,
) -> AppResult<Json<serde_json::Value>> {
admin_only(&user)?;
#[derive(sqlx::FromRow)]
struct Member {
@@ -34,6 +39,14 @@ pub async fn overview(State(state): State<AppState>, User(user): User) -> AppRes
.await?;
let last_seen: Vec<(String, Option<String>)> =
sqlx::query_as("SELECT id, last_seen_at FROM identities").fetch_all(&state.db).await?;
// Open sessions, but the one this page is read with.
let sessions: Vec<(String, i64)> = sqlx::query_as(
"SELECT identity_id, COUNT(*) FROM sessions WHERE expires_at > ? AND token_hash != ? GROUP BY identity_id",
)
.bind(util::now())
.bind(auth::session_hash(&state, &headers).unwrap_or_default())
.fetch_all(&state.db)
.await?;
let came_by: Vec<(String, String)> =
sqlx::query_as("SELECT i.id, t.label FROM identities i JOIN team_links t ON t.token_hash = i.team_link")
.fetch_all(&state.db)
@@ -63,6 +76,7 @@ pub async fn overview(State(state): State<AppState>, User(user): User) -> AppRes
"id": i.id, "kind": i.kind, "displayName": i.display_name, "g1Member": i.g1_member, "admin": i.admin,
"lastSeenAt": last_seen.iter().find(|(id, _)| id == &i.id).and_then(|(_, at)| at.clone()),
"teamLink": came_by.iter().find(|(id, _)| id == &i.id).map(|(_, label)| label.clone()),
"sessions": sessions.iter().find(|(id, _)| id == &i.id).map_or(0, |(_, n)| *n),
})).collect::<Vec<_>>(),
"teamLinks": crate::team::list(&state).await?,
"invitations": invitations.iter().map(|(hash, label, admin, groups, expires, identity)| json!({
@@ -207,6 +221,26 @@ pub async fn set_admin(
Ok(Json(json!({ "admin": b.admin })))
}
/// A lost device, a person who left: every session of this identity closes,
/// but the one this request comes with.
pub async fn close_sessions(
State(state): State<AppState>,
headers: HeaderMap,
User(user): User,
Path(id): Path<String>,
) -> AppResult<Json<serde_json::Value>> {
admin_only(&user)?;
auth::load_identity(&state, &id).await?;
let closed = sqlx::query("DELETE FROM sessions WHERE identity_id = ? AND token_hash != ?")
.bind(&id)
.bind(auth::session_hash(&state, &headers).unwrap_or_default())
.execute(&state.db)
.await?
.rows_affected();
tracing::info!(identity = %id, closed, by = %user.id, "sessions closed");
Ok(Json(json!({ "closed": closed })))
}
#[derive(Deserialize)]
pub struct FeedbackBody {
route: String,
+30 -3
View File
@@ -39,7 +39,9 @@ fn session_cookie(state: &AppState) -> &'static str {
fn oauth_cookie(state: &AppState) -> &'static str {
if state.cfg.secure_cookies() { "__Secure-ld_oauth" } else { OAUTH_COOKIE }
}
const SESSION_DAYS: i64 = 30;
/// A session lasts until it is closed (sign-out, or an administrator): 400 days
/// is the longest a browser keeps a cookie, and each visit starts them again.
const SESSION_DAYS: i64 = 400;
const INVITATION_DAYS: i64 = 14;
fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
@@ -178,8 +180,33 @@ pub async fn config(State(state): State<AppState>) -> Json<serde_json::Value> {
Json(json!(AuthConfig { g1: state.cfg.connect.is_some(), dev: state.cfg.dev_login }))
}
pub async fn me(Viewer(viewer): Viewer) -> Json<serde_json::Value> {
Json(json!({ "me": viewer }))
/// The hash of the session this request comes with, if any.
pub(crate) fn session_hash(state: &AppState, headers: &HeaderMap) -> Option<String> {
cookie_value(headers, session_cookie(state)).map(|token| util::sha256_hex(&token))
}
/// Who is signed in. Once a day at most, the visit starts the session's days
/// again, in the database and in the browser.
pub async fn me(State(state): State<AppState>, headers: HeaderMap, Viewer(viewer): Viewer) -> AppResult<Response> {
let mut res = Json(json!({ "me": viewer })).into_response();
if let (Some(me), Some(token)) = (&viewer, cookie_value(&headers, session_cookie(&state))) {
let renewed = sqlx::query("UPDATE sessions SET expires_at = ? WHERE token_hash = ? AND expires_at < ?")
.bind(util::in_days(SESSION_DAYS))
.bind(util::sha256_hex(&token))
.bind(util::in_days(SESSION_DAYS - 1))
.execute(&state.db)
.await?;
if renewed.rows_affected() == 1 {
sqlx::query("UPDATE identities SET last_seen_at = ? WHERE id = ?")
.bind(util::now())
.bind(&me.id)
.execute(&state.db)
.await?;
res.headers_mut()
.append(SET_COOKIE, cookie(&state, session_cookie(&state), &token, "/", SESSION_DAYS * 86_400));
}
}
Ok(res)
}
/// Only local paths, never `//host` nor a scheme.
+1
View File
@@ -127,6 +127,7 @@ pub fn api_router() -> Router<AppState> {
.route("/access/team-links", post(team::create))
.route("/access/team-links/{hash}", delete(team::revoke))
.route("/access/identities/{id}/admin", post(access::set_admin))
.route("/access/identities/{id}/sessions", delete(access::close_sessions))
.route("/access/feedback", get(access::feedback_list))
.route("/access/feedback/{id}", post(access::feedback_status))
.layer(middleware::from_fn(csrf_guard))