use super::audit::{token_fingerprint, AuthAuditEvent, AuthAuditHook, TracingAuditHook};
use super::dto::{LogoutInput, MessageResponse};
use crate::action::{ActionContext, TypedHandler};
use crate::error::BaseError;
use async_trait::async_trait;
use yang_base_derive::Action;
#[derive(Action, Default)]
#[action(
name = "logout",
display_name = "登出",
description = "撤销 Token,使其在过期前失效",
public
)]
pub struct LogoutAction<A: AuthAuditHook = TracingAuditHook> {
audit: A,
}
impl LogoutAction<TracingAuditHook> {
pub fn new() -> Self {
Self {
audit: TracingAuditHook,
}
}
}
impl<A: AuthAuditHook> LogoutAction<A> {
pub fn with_audit(audit: A) -> Self {
Self { audit }
}
}
#[async_trait]
impl<A: AuthAuditHook> TypedHandler for LogoutAction<A> {
type Input = LogoutInput;
type Output = MessageResponse;
async fn handle(
&self,
ctx: ActionContext,
input: LogoutInput,
) -> Result<MessageResponse, BaseError> {
let request_id = ctx.request_id.to_string();
let manager = ctx.tools().token()?;
let run = async {
let target_claims = manager.verify_token(&input.token)?;
if let Some(bearer_token) = ctx.request.token() {
let caller_claims = manager
.verify_token_checked(bearer_token, crate::token::TokenType::Access)
.await?;
if caller_claims.sub != target_claims.sub {
return Err(BaseError::PermissionDenied(
"只能撤销自己的 Token".to_string(),
));
}
} else {
manager
.verify_token_checked(&input.token, target_claims.token_type)
.await?;
}
manager.revoke_by_subject(&target_claims.sub).await?;
Ok::<(), BaseError>(())
};
match run.await {
Ok(()) => {
self.audit
.on_success(AuthAuditEvent {
request_id,
action: "logout",
subject: Some(token_fingerprint(&input.token)),
error_code: None,
})
.await;
Ok(MessageResponse {
message: "已登出".to_string(),
})
}
Err(e) => {
self.audit
.on_failure(AuthAuditEvent {
request_id,
action: "logout",
subject: Some(token_fingerprint(&input.token)),
error_code: Some(e.code_str()),
})
.await;
Err(e)
}
}
}
}