yang_base/action/auth/
logout.rs1use super::audit::{token_fingerprint, AuthAuditEvent, AuthAuditHook, TracingAuditHook};
4use super::dto::{LogoutInput, MessageResponse};
5use crate::action::{ActionContext, TypedHandler};
6use crate::error::BaseError;
7use async_trait::async_trait;
8use yang_base_derive::Action;
9
10#[derive(Action, Default)]
28#[action(
29 name = "logout",
30 display_name = "登出",
31 description = "撤销 Token,使其在过期前失效",
32 public
33)]
34pub struct LogoutAction<A: AuthAuditHook = TracingAuditHook> {
35 audit: A,
36}
37
38impl LogoutAction<TracingAuditHook> {
39 pub fn new() -> Self {
41 Self {
42 audit: TracingAuditHook,
43 }
44 }
45}
46
47impl<A: AuthAuditHook> LogoutAction<A> {
48 pub fn with_audit(audit: A) -> Self {
50 Self { audit }
51 }
52}
53
54#[async_trait]
55impl<A: AuthAuditHook> TypedHandler for LogoutAction<A> {
56 type Input = LogoutInput;
57 type Output = MessageResponse;
58
59 async fn handle(
60 &self,
61 ctx: ActionContext,
62 input: LogoutInput,
63 ) -> Result<MessageResponse, BaseError> {
64 let request_id = ctx.request_id.to_string();
65 let manager = ctx.tools().token()?;
66
67 let run = async {
68 let target_claims = manager.verify_token(&input.token)?;
70
71 if let Some(bearer_token) = ctx.request.token() {
73 let caller_claims = manager
75 .verify_token_checked(bearer_token, crate::token::TokenType::Access)
76 .await?;
77 if caller_claims.sub != target_claims.sub {
78 return Err(BaseError::PermissionDenied(
79 "只能撤销自己的 Token".to_string(),
80 ));
81 }
82 } else {
83 manager
84 .verify_token_checked(&input.token, target_claims.token_type)
85 .await?;
86 }
87
88 manager.revoke_by_subject(&target_claims.sub).await?;
92 Ok::<(), BaseError>(())
93 };
94
95 match run.await {
96 Ok(()) => {
97 self.audit
99 .on_success(AuthAuditEvent {
100 request_id,
101 action: "logout",
102 subject: Some(token_fingerprint(&input.token)),
103 error_code: None,
104 })
105 .await;
106 Ok(MessageResponse {
107 message: "已登出".to_string(),
108 })
109 }
110 Err(e) => {
111 self.audit
112 .on_failure(AuthAuditEvent {
113 request_id,
114 action: "logout",
115 subject: Some(token_fingerprint(&input.token)),
116 error_code: Some(e.code_str()),
117 })
118 .await;
119 Err(e)
120 }
121 }
122 }
123}