use super::audit::{AuthAuditEvent, AuthAuditHook, TracingAuditHook};
use super::dto::{LoginInput, TokenPairResponse, VerifiedSubject};
use crate::action::{ActionContext, TypedHandler};
use crate::error::BaseError;
use async_trait::async_trait;
use yang_base_derive::Action;
#[async_trait]
pub trait CredentialVerifier: Send + Sync + 'static {
async fn verify(
&self,
ctx: &ActionContext,
input: &LoginInput,
) -> Result<VerifiedSubject, BaseError>;
}
#[derive(Action)]
#[action(
name = "login",
display_name = "登录",
description = "校验凭证并签发 Token 对",
public
)]
pub struct LoginAction<V: CredentialVerifier, A: AuthAuditHook = TracingAuditHook> {
verifier: V,
audit: A,
}
impl<V: CredentialVerifier> LoginAction<V, TracingAuditHook> {
pub fn new(verifier: V) -> Self {
Self {
verifier,
audit: TracingAuditHook,
}
}
}
impl<V: CredentialVerifier, A: AuthAuditHook> LoginAction<V, A> {
pub fn with_audit(verifier: V, audit: A) -> Self {
Self { verifier, audit }
}
}
#[async_trait]
impl<V: CredentialVerifier, A: AuthAuditHook> TypedHandler for LoginAction<V, A> {
type Input = LoginInput;
type Output = TokenPairResponse;
async fn handle(
&self,
ctx: ActionContext,
input: LoginInput,
) -> Result<TokenPairResponse, BaseError> {
let request_id = ctx.request_id.to_string();
let subject = match self.verifier.verify(&ctx, &input).await {
Ok(s) => s,
Err(e) => {
self.audit
.on_failure(AuthAuditEvent {
request_id,
action: "login",
subject: Some(input.username.clone()),
error_code: Some(e.code_str()),
})
.await;
return Err(e);
}
};
let result = ctx
.tools()
.token()?
.generate_token_pair_with_refresh_claims(
&subject.subject,
subject.custom_claims,
subject.refresh_claims,
);
match result {
Ok((access_token, refresh_token)) => {
self.audit
.on_success(AuthAuditEvent {
request_id,
action: "login",
subject: Some(subject.subject.clone()),
error_code: None,
})
.await;
Ok(TokenPairResponse {
access_token,
refresh_token,
})
}
Err(e) => {
self.audit
.on_failure(AuthAuditEvent {
request_id,
action: "login",
subject: Some(subject.subject.clone()),
error_code: Some(e.code_str()),
})
.await;
Err(e)
}
}
}
}