Skip to main content

yang_base/action/auth/
login.rs

1//! 登录 Action 与业务凭证校验契约。
2
3use super::audit::{AuthAuditEvent, AuthAuditHook, TracingAuditHook};
4use super::dto::{LoginInput, TokenPairResponse, VerifiedSubject};
5use crate::action::{ActionContext, TypedHandler};
6use crate::error::BaseError;
7use async_trait::async_trait;
8use yang_base_derive::Action;
9
10// ──────────────────────────────────────────────────────────────────────────────
11// CredentialVerifier:业务实现的凭证校验
12// ──────────────────────────────────────────────────────────────────────────────
13
14/// 凭证校验 trait,由业务方实现并注入 [`LoginAction`]。
15///
16/// # 限流(实现方必须)
17///
18/// 本 trait 同时服务登录与 step-up 重认证(`StepUpManager::complete_challenge`),
19/// 两者都是凭据猜测的在线入口。实现方**必须**在 `verify` 内(或调用它的端点上)
20/// 做速率限制与失败计数:按 `subject + 客户端标识`(来源 IP、设备指纹等)计数
21/// 连续失败,超阈值后指数退避或锁定并返回 `Unauthorized`;计数状态应经
22/// `ctx.tools()` 的共享存储(如 Redis)实现,保证多实例下一致。
23#[async_trait]
24pub trait CredentialVerifier: Send + Sync + 'static {
25    /// 校验登录凭证。
26    ///
27    /// # 参数
28    ///
29    /// - `ctx`: 动作上下文(可借此访问数据库等)
30    /// - `input`: 登录输入
31    ///
32    /// # 返回
33    ///
34    /// - `Ok(VerifiedSubject)`: 校验通过,携带签发 Token 所需的主体信息
35    /// - `Err(BaseError)`: 校验失败(如 `Unauthorized`)
36    async fn verify(
37        &self,
38        ctx: &ActionContext,
39        input: &LoginInput,
40    ) -> Result<VerifiedSubject, BaseError>;
41}
42
43// ──────────────────────────────────────────────────────────────────────────────
44// LoginAction
45// ──────────────────────────────────────────────────────────────────────────────
46
47/// 登录 Action:校验凭证后签发 Token 对。公开(无需登录即可访问)。
48///
49/// 泛型 `A` 为审计钩子(默认 [`TracingAuditHook`]):登录成功/失败均发审计事件,
50/// 事件只含 request_id/subject/错误码,**不含凭据明文**。
51#[derive(Action)]
52#[action(
53    name = "login",
54    display_name = "登录",
55    description = "校验凭证并签发 Token 对",
56    public
57)]
58pub struct LoginAction<V: CredentialVerifier, A: AuthAuditHook = TracingAuditHook> {
59    verifier: V,
60    audit: A,
61}
62
63impl<V: CredentialVerifier> LoginAction<V, TracingAuditHook> {
64    /// 用业务凭证校验器创建登录 Action(默认 tracing 审计钩子)。
65    pub fn new(verifier: V) -> Self {
66        Self {
67            verifier,
68            audit: TracingAuditHook,
69        }
70    }
71}
72
73impl<V: CredentialVerifier, A: AuthAuditHook> LoginAction<V, A> {
74    /// 用业务凭证校验器 + 自定义审计钩子创建登录 Action。
75    pub fn with_audit(verifier: V, audit: A) -> Self {
76        Self { verifier, audit }
77    }
78}
79
80#[async_trait]
81impl<V: CredentialVerifier, A: AuthAuditHook> TypedHandler for LoginAction<V, A> {
82    type Input = LoginInput;
83    type Output = TokenPairResponse;
84
85    async fn handle(
86        &self,
87        ctx: ActionContext,
88        input: LoginInput,
89    ) -> Result<TokenPairResponse, BaseError> {
90        let request_id = ctx.request_id.to_string();
91        let subject = match self.verifier.verify(&ctx, &input).await {
92            Ok(s) => s,
93            Err(e) => {
94                self.audit
95                    .on_failure(AuthAuditEvent {
96                        request_id,
97                        action: "login",
98                        subject: Some(input.username.clone()),
99                        error_code: Some(e.code_str()),
100                    })
101                    .await;
102                return Err(e);
103            }
104        };
105        let result = ctx
106            .tools()
107            .token()?
108            .generate_token_pair_with_refresh_claims(
109                &subject.subject,
110                subject.custom_claims,
111                subject.refresh_claims,
112            );
113        match result {
114            Ok((access_token, refresh_token)) => {
115                self.audit
116                    .on_success(AuthAuditEvent {
117                        request_id,
118                        action: "login",
119                        subject: Some(subject.subject.clone()),
120                        error_code: None,
121                    })
122                    .await;
123                Ok(TokenPairResponse {
124                    access_token,
125                    refresh_token,
126                })
127            }
128            Err(e) => {
129                self.audit
130                    .on_failure(AuthAuditEvent {
131                        request_id,
132                        action: "login",
133                        subject: Some(subject.subject.clone()),
134                        error_code: Some(e.code_str()),
135                    })
136                    .await;
137                Err(e)
138            }
139        }
140    }
141}