Skip to main content

tibba_session/
lib.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 snafu::Snafu;
16use tibba_error::Error as BaseError;
17
18/// 该 crate 所有日志事件的 tracing target。
19/// 可通过 `RUST_LOG=tibba:session=info`(或 `debug`)进行过滤。
20pub(crate) const LOG_TARGET: &str = "tibba:session";
21
22mod middleware;
23mod session;
24
25pub use middleware::*;
26pub use session::*;
27
28#[derive(Debug, Snafu)]
29pub enum Error {
30    /// Session ID 为空,通常表示尚未登录或 Session 已重置。
31    #[snafu(display("session id is empty"))]
32    SessionIdEmpty,
33    /// Session ID 格式非法(长度不足 36 字符)。
34    #[snafu(display("session id is invalid"))]
35    SessionIdInvalid,
36    /// Session 缓存未初始化,属于服务端配置错误。
37    #[snafu(display("session cache is not set"))]
38    SessionCacheNotSet,
39    /// Cookie 签名密钥错误。
40    #[snafu(display("{source}"))]
41    Key { source: cookie::KeyError },
42    /// 请求扩展中未找到 Session,通常表示 session 中间件未挂载。
43    #[snafu(display("session not found"))]
44    SessionNotFound,
45    /// 用户未登录,HTTP 401。
46    #[snafu(display("user not login"))]
47    UserNotLogin,
48    /// 用户无管理员权限,HTTP 403。
49    #[snafu(display("user not admin"))]
50    UserNotAdmin,
51}
52
53impl From<Error> for BaseError {
54    fn from(val: Error) -> Self {
55        let err = match val {
56            // 服务端内部异常,返回 500
57            e @ (Error::SessionIdEmpty
58            | Error::SessionIdInvalid
59            | Error::SessionCacheNotSet
60            | Error::SessionNotFound) => BaseError::new(e.to_string())
61                .with_status(500)
62                .with_exception(true),
63
64            // Cookie 密钥错误,视为服务端异常
65            Error::Key { source } => BaseError::new(source)
66                .with_sub_category("cookie")
67                .with_status(500)
68                .with_exception(true),
69
70            // 未登录,返回 401
71            Error::UserNotLogin => BaseError::new("user not login")
72                .with_sub_category("user")
73                .with_status(401)
74                .with_exception(false),
75
76            // 无权限,返回 403
77            Error::UserNotAdmin => BaseError::new("user not admin")
78                .with_sub_category("user")
79                .with_status(403)
80                .with_exception(false),
81        };
82        err.with_category("session")
83    }
84}