Skip to main content

tibba_session/
middleware.rs

1// Copyright 2026 Tree xie.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use super::{LOG_TARGET, Session, SessionParams};
16use axum::extract::Request;
17use axum::extract::State;
18use axum::middleware::Next;
19use axum::response::Response;
20use scopeguard::defer;
21use std::sync::Arc;
22use tibba_cache::RedisCache;
23use tracing::debug;
24
25type Result<T, E = tibba_error::Error> = std::result::Result<T, E>;
26
27/// axum 中间件:在请求扩展中注入空 Session 实例,供后续 handler 通过 extractor 按需加载。
28/// Session 数据不在此处预加载,而是在 `FromRequestParts` 实现中按需从 Redis 读取。
29pub async fn session(
30    State((cache, params)): State<(&'static RedisCache, Arc<SessionParams>)>,
31    mut req: Request,
32    next: Next,
33) -> Result<Response> {
34    debug!(target: LOG_TARGET, "--> session");
35    defer!(debug!(target: LOG_TARGET, "<-- session"););
36
37    req.extensions_mut().insert(Session::new(cache, params));
38    Ok(next.run(req).await)
39}