yang_base/action/auth/
login.rs1use 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#[async_trait]
24pub trait CredentialVerifier: Send + Sync + 'static {
25 async fn verify(
37 &self,
38 ctx: &ActionContext,
39 input: &LoginInput,
40 ) -> Result<VerifiedSubject, BaseError>;
41}
42
43#[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 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 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}