StpUtil

Struct StpUtil 

Source
pub struct StpUtil;
Expand description

StpUtil - 权限认证工具类

提供便捷的认证和授权操作方法,类似于 Java 版 sa-token 的 StpUtil

Implementations§

Source§

impl StpUtil

Source

pub fn init_manager(manager: SaTokenManager)

初始化全局 SaTokenManager(应用启动时调用一次)

§示例
let manager = SaTokenConfig::builder()
    .storage(Arc::new(MemoryStorage::new()))
    .build();
StpUtil::init_manager(manager);
Source

pub fn event_bus() -> &'static SaTokenEventBus

获取事件总线,用于注册监听器

§示例
use sa_token_core::{StpUtil, SaTokenListener};
use async_trait::async_trait;
 
struct MyListener;
 
#[async_trait]
impl SaTokenListener for MyListener {
    async fn on_login(&self, login_id: &str, token: &str, login_type: &str) {
        println!("用户 {} 登录了", login_id);
    }
}
 
// 注册监听器
StpUtil::event_bus().register(Arc::new(MyListener)).await;
Source

pub fn register_listener(listener: Arc<dyn SaTokenListener>)

注册事件监听器(便捷方法)

§示例
StpUtil::register_listener(Arc::new(MyListener)).await;
Source

pub async fn login(login_id: impl LoginId) -> Result<TokenValue, SaTokenError>

会话登录

§示例
// 支持字符串 ID
let token = StpUtil::login("user_123").await?;
 
// 支持数字 ID
let token = StpUtil::login(10001).await?;
let token = StpUtil::login(10001_i64).await?;
Source

pub async fn login_with_type( login_id: impl LoginId, _login_type: impl Into<String>, ) -> Result<TokenValue, SaTokenError>

Source

pub async fn login_with_extra( login_id: impl LoginId, extra_data: Value, ) -> Result<TokenValue, SaTokenError>

登录并设置额外数据 | Login with extra data

§参数 | Arguments
  • login_id - 登录ID | Login ID
  • extra_data - 额外数据 | Extra data
Source

pub async fn login_with_manager( manager: &SaTokenManager, login_id: impl Into<String>, ) -> Result<TokenValue, SaTokenError>

会话登录(带 manager 参数的版本,向后兼容)

Source

pub async fn logout(token: &TokenValue) -> Result<(), SaTokenError>

会话登出

Source

pub async fn logout_with_manager( manager: &SaTokenManager, token: &TokenValue, ) -> Result<(), SaTokenError>

Source

pub async fn kick_out(login_id: impl LoginId) -> Result<(), SaTokenError>

踢人下线(根据登录ID)

Source

pub async fn kick_out_with_manager( manager: &SaTokenManager, login_id: &str, ) -> Result<(), SaTokenError>

Source

pub async fn logout_by_login_id( login_id: impl LoginId, ) -> Result<(), SaTokenError>

强制登出(根据登录ID)

Source

pub async fn logout_by_token(token: &TokenValue) -> Result<(), SaTokenError>

根据 token 登出(别名方法,更直观)

Source

pub fn get_token_value() -> Result<TokenValue, SaTokenError>

获取当前请求的 token(无参数,从上下文获取)

§示例
// 在请求处理函数中
let token = StpUtil::get_token_value()?;
Source

pub async fn logout_current() -> Result<(), SaTokenError>

当前会话登出(无参数,从上下文获取 token)

§示例
// 在请求处理函数中
StpUtil::logout_current().await?;
Source

pub fn is_login_current() -> bool

检查当前会话是否登录(无参数,返回 bool)

§示例
// 在请求处理函数中
if StpUtil::is_login_current() {
    println!("当前用户已登录");
}
Source

pub fn check_login_current() -> Result<(), SaTokenError>

检查当前会话登录状态,未登录则抛出异常(无参数)

§示例
// 在请求处理函数中
StpUtil::check_login_current()?;
Source

pub async fn get_login_id_as_string() -> Result<String, SaTokenError>

获取当前会话的 login_id(String 类型,无参数)

§示例
// 在请求处理函数中
let login_id = StpUtil::get_login_id_as_string().await?;
Source

pub async fn get_login_id_as_long() -> Result<i64, SaTokenError>

获取当前会话的 login_id(i64 类型,无参数)

§示例
// 在请求处理函数中
let user_id = StpUtil::get_login_id_as_long().await?;
Source

pub fn get_token_info_current() -> Result<Arc<TokenInfo>, SaTokenError>

获取当前会话的 token 信息(无参数)

§示例
// 在请求处理函数中
let token_info = StpUtil::get_token_info_current()?;
println!("Token 创建时间: {:?}", token_info.create_time);
Source

pub async fn is_login(token: &TokenValue) -> bool

检查当前 token 是否已登录

Source

pub async fn is_login_by_login_id(login_id: impl LoginId) -> bool

根据登录 ID 检查是否已登录

§示例
let is_logged_in = StpUtil::is_login_by_login_id("user_123").await;
let is_logged_in = StpUtil::is_login_by_login_id(10001).await;
Source

pub async fn is_login_with_manager( manager: &SaTokenManager, token: &TokenValue, ) -> bool

Source

pub async fn check_login(token: &TokenValue) -> Result<(), SaTokenError>

检查当前 token 是否已登录,如果未登录则抛出异常

Source

pub async fn get_token_info( token: &TokenValue, ) -> Result<TokenInfo, SaTokenError>

获取 token 信息

Source

pub async fn get_login_id(token: &TokenValue) -> Result<String, SaTokenError>

获取当前 token 的登录ID

Source

pub async fn get_login_id_or_default( token: &TokenValue, default: impl Into<String>, ) -> String

获取当前 token 的登录ID,如果未登录则返回默认值

Source

pub async fn get_token_by_login_id( login_id: impl LoginId, ) -> Result<TokenValue, SaTokenError>

根据登录 ID 获取当前用户的 token

§示例
let token = StpUtil::get_token_by_login_id("user_123").await?;
let token = StpUtil::get_token_by_login_id(10001).await?;
Source

pub async fn get_all_tokens_by_login_id( login_id: impl LoginId, ) -> Result<Vec<TokenValue>, SaTokenError>

根据登录 ID 获取所有在线的 token 列表(支持多设备登录)

§示例
let tokens = StpUtil::get_all_tokens_by_login_id("user_123").await?;
Source

pub async fn get_session( login_id: impl LoginId, ) -> Result<SaSession, SaTokenError>

获取当前登录账号的 Session

Source

pub async fn save_session(session: &SaSession) -> Result<(), SaTokenError>

保存 Session

Source

pub async fn delete_session(login_id: impl LoginId) -> Result<(), SaTokenError>

删除 Session

Source

pub async fn set_session_value<T>( login_id: impl LoginId, key: &str, value: T, ) -> Result<(), SaTokenError>
where T: Serialize,

在 Session 中设置值

Source

pub async fn get_session_value<T>( login_id: impl LoginId, key: &str, ) -> Result<Option<T>, SaTokenError>

从 Session 中获取值

Source

pub fn create_token(token_value: impl Into<String>) -> TokenValue

创建一个新的 token(但不登录)

Source

pub fn is_valid_token_format(token: &str) -> bool

检查 token 格式是否有效(仅检查格式,不检查是否存在于存储中)

Source§

impl StpUtil

Source

pub async fn set_permissions( login_id: impl LoginId, permissions: Vec<String>, ) -> Result<(), SaTokenError>

为用户添加权限

Source

pub async fn add_permission( login_id: impl LoginId, permission: impl Into<String>, ) -> Result<(), SaTokenError>

为用户添加单个权限

Source

pub async fn remove_permission( login_id: impl LoginId, permission: &str, ) -> Result<(), SaTokenError>

移除用户的某个权限

Source

pub async fn clear_permissions( login_id: impl LoginId, ) -> Result<(), SaTokenError>

清除用户的所有权限

Source

pub async fn get_permissions(login_id: impl LoginId) -> Vec<String>

获取用户的所有权限

Source

pub async fn has_permission(login_id: impl LoginId, permission: &str) -> bool

检查用户是否拥有指定权限

Source

pub async fn has_all_permissions( login_id: impl LoginId, permissions: &[&str], ) -> bool

检查用户是否拥有所有指定权限(AND 逻辑)

Source

pub async fn has_permissions_and( login_id: impl LoginId, permissions: &[&str], ) -> bool

检查用户是否拥有所有指定权限(别名,AND 逻辑)

Source

pub async fn has_any_permission( login_id: impl LoginId, permissions: &[&str], ) -> bool

检查用户是否拥有任一指定权限(OR 逻辑)

Source

pub async fn has_permissions_or( login_id: impl LoginId, permissions: &[&str], ) -> bool

检查用户是否拥有任一指定权限(别名,OR 逻辑)

Source

pub async fn check_permission( login_id: impl LoginId, permission: &str, ) -> Result<(), SaTokenError>

检查权限,如果没有则抛出异常

Source§

impl StpUtil

Source

pub async fn set_roles( login_id: impl LoginId, roles: Vec<String>, ) -> Result<(), SaTokenError>

为用户设置角色

Source

pub async fn add_role( login_id: impl LoginId, role: impl Into<String>, ) -> Result<(), SaTokenError>

为用户添加单个角色

Source

pub async fn remove_role( login_id: impl LoginId, role: &str, ) -> Result<(), SaTokenError>

移除用户的某个角色

Source

pub async fn clear_roles(login_id: impl LoginId) -> Result<(), SaTokenError>

清除用户的所有角色

Source

pub async fn get_roles(login_id: impl LoginId) -> Vec<String>

获取用户的所有角色

Source

pub async fn has_role(login_id: impl LoginId, role: &str) -> bool

检查用户是否拥有指定角色

Source

pub async fn has_all_roles(login_id: impl LoginId, roles: &[&str]) -> bool

检查用户是否拥有所有指定角色(AND 逻辑)

Source

pub async fn has_roles_and(login_id: impl LoginId, roles: &[&str]) -> bool

检查用户是否拥有所有指定角色(别名,AND 逻辑)

Source

pub async fn has_any_role(login_id: impl LoginId, roles: &[&str]) -> bool

检查用户是否拥有任一指定角色(OR 逻辑)

Source

pub async fn has_roles_or(login_id: impl LoginId, roles: &[&str]) -> bool

检查用户是否拥有任一指定角色(别名,OR 逻辑)

Source

pub async fn check_role( login_id: impl LoginId, role: &str, ) -> Result<(), SaTokenError>

检查角色,如果没有则抛出异常

Source§

impl StpUtil

Source

pub async fn kick_out_batch<T>( login_ids: &[T], ) -> Result<Vec<Result<(), SaTokenError>>, SaTokenError>
where T: LoginId,

批量踢人下线

Source

pub async fn get_token_timeout( token: &TokenValue, ) -> Result<Option<i64>, SaTokenError>

获取 token 剩余有效时间(秒)

Source

pub async fn renew_timeout( token: &TokenValue, timeout_seconds: i64, ) -> Result<(), SaTokenError>

续期 token(重置过期时间)

Source

pub async fn set_extra_data( token: &TokenValue, extra_data: Value, ) -> Result<(), SaTokenError>

设置 Token 的额外数据 | Set extra data for token

§参数 | Arguments
  • token - Token值 | Token value
  • extra_data - 额外数据 | Extra data
Source

pub async fn get_extra_data( token: &TokenValue, ) -> Result<Option<Value>, SaTokenError>

获取 Token 的额外数据 | Get extra data from token

§参数 | Arguments
  • token - Token值 | Token value
Source

pub fn builder(login_id: impl LoginId) -> TokenBuilder

创建 Token 构建器,用于链式调用 | Create token builder for chain calls

§示例 | Example
use serde_json::json;
 
// 链式调用示例
let token = StpUtil::builder("user_123")
    .extra_data(json!({"ip": "192.168.1.1"}))
    .device("pc")
    .login_type("admin")
    .login()
    .await?;

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> ServiceExt for T

Source§

fn propagate_header(self, header: HeaderName) -> PropagateHeader<Self>
where Self: Sized,

Propagate a header from the request to the response. Read more
Source§

fn add_extension<T>(self, value: T) -> AddExtension<Self, T>
where Self: Sized,

Add some shareable value to request extensions. Read more
Source§

fn map_request_body<F>(self, f: F) -> MapRequestBody<Self, F>
where Self: Sized,

Apply a transformation to the request body. Read more
Source§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Apply a transformation to the response body. Read more
Source§

fn compression(self) -> Compression<Self>
where Self: Sized,

Compresses response bodies. Read more
Source§

fn decompression(self) -> Decompression<Self>
where Self: Sized,

Decompress response bodies. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
Source§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. Read more
Source§

fn sensitive_headers( self, headers: impl IntoIterator<Item = HeaderName>, ) -> SetSensitiveRequestHeaders<SetSensitiveResponseHeaders<Self>>
where Self: Sized,

Mark headers as sensitive on both requests and responses. Read more
Source§

fn sensitive_request_headers( self, headers: impl IntoIterator<Item = HeaderName>, ) -> SetSensitiveRequestHeaders<Self>
where Self: Sized,

Mark headers as sensitive on requests. Read more
Source§

fn sensitive_response_headers( self, headers: impl IntoIterator<Item = HeaderName>, ) -> SetSensitiveResponseHeaders<Self>
where Self: Sized,

Mark headers as sensitive on responses. Read more
Source§

fn override_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request. Read more
Source§

fn append_request_header<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Append a header into the request. Read more
Source§

fn insert_request_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetRequestHeader<Self, M>
where Self: Sized,

Insert a header into the request, if the header is not already present. Read more
Source§

fn override_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response. Read more
Source§

fn append_response_header<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Append a header into the response. Read more
Source§

fn insert_response_header_if_not_present<M>( self, header_name: HeaderName, make: M, ) -> SetResponseHeader<Self, M>
where Self: Sized,

Insert a header into the response, if the header is not already present. Read more
Source§

fn set_request_id<M>( self, header_name: HeaderName, make_request_id: M, ) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension. Read more
Source§

fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension, using x-request-id as the header name. Read more
Source§

fn propagate_request_id( self, header_name: HeaderName, ) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses. Read more
Source§

fn propagate_x_request_id(self) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses, using x-request-id as the header name. Read more
Source§

fn catch_panic(self) -> CatchPanic<Self, DefaultResponseForPanic>
where Self: Sized,

Catch panics and convert them into 500 Internal Server responses. Read more
Source§

fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>
where Self: Sized,

Intercept requests with over-sized payloads and convert them into 413 Payload Too Large responses. Read more
Source§

fn trim_trailing_slash(self) -> NormalizePath<Self>
where Self: Sized,

Remove trailing slashes from paths. Read more
Source§

fn append_trailing_slash(self) -> NormalizePath<Self>
where Self: Sized,

Append trailing slash to paths. Read more
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<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