yang_base/action/auth/
middleware.rs1use crate::action::{ActionContext, ApiResponse, User};
4use crate::error::BaseError;
5use crate::router::middleware::{Middleware, MiddlewareRole, MiddlewareScope, Next};
6use crate::token::TokenClaims;
7use async_trait::async_trait;
8
9pub struct TokenAuthMiddleware<F, V = NoopTokenClaimsValidator> {
45 build_user: F,
47 claims_validator: V,
49 authenticate_public_actions: bool,
51}
52
53#[async_trait]
58pub trait TokenClaimsValidator: Send + Sync + 'static {
59 async fn validate(
61 &self,
62 context: &ActionContext,
63 claims: &TokenClaims,
64 ) -> Result<(), BaseError>;
65}
66
67#[derive(Debug, Clone, Copy, Default)]
69pub struct NoopTokenClaimsValidator;
70
71#[async_trait]
72impl TokenClaimsValidator for NoopTokenClaimsValidator {
73 async fn validate(
74 &self,
75 _context: &ActionContext,
76 _claims: &TokenClaims,
77 ) -> Result<(), BaseError> {
78 Ok(())
79 }
80}
81
82#[doc(hidden)]
87pub trait IntoUserProjection {
88 fn into_user_projection(self) -> Result<User, BaseError>;
89}
90
91impl IntoUserProjection for User {
92 fn into_user_projection(self) -> Result<User, BaseError> {
93 Ok(self)
94 }
95}
96
97impl IntoUserProjection for Result<User, BaseError> {
98 fn into_user_projection(self) -> Result<User, BaseError> {
99 self
100 }
101}
102
103impl<F, R> TokenAuthMiddleware<F, NoopTokenClaimsValidator>
104where
105 F: Fn(&TokenClaims) -> R + Send + Sync + 'static,
106 R: IntoUserProjection,
107{
108 pub fn new(build_user: F) -> Self {
113 Self {
114 build_user,
115 claims_validator: NoopTokenClaimsValidator,
116 authenticate_public_actions: false,
117 }
118 }
119}
120
121impl<F, V> TokenAuthMiddleware<F, V> {
122 pub fn with_claims_validator<N>(self, claims_validator: N) -> TokenAuthMiddleware<F, N>
124 where
125 N: TokenClaimsValidator,
126 {
127 TokenAuthMiddleware {
128 build_user: self.build_user,
129 claims_validator,
130 authenticate_public_actions: self.authenticate_public_actions,
131 }
132 }
133
134 pub fn authenticate_public_actions(mut self) -> Self {
143 self.authenticate_public_actions = true;
144 self
145 }
146}
147
148#[async_trait]
149impl<F, R, V> Middleware for TokenAuthMiddleware<F, V>
150where
151 F: Fn(&TokenClaims) -> R + Send + Sync + 'static,
152 R: IntoUserProjection + Send + Sync + 'static,
153 V: TokenClaimsValidator,
154{
155 fn role(&self) -> MiddlewareRole {
156 MiddlewareRole::Authentication
157 }
158
159 fn scope(&self) -> MiddlewareScope {
160 if self.authenticate_public_actions {
161 MiddlewareScope::AllActions
162 } else {
163 MiddlewareScope::ProtectedActions
164 }
165 }
166
167 async fn handle(
168 &self,
169 mut ctx: ActionContext,
170 next: Next<'_>,
171 ) -> Result<ApiResponse, BaseError> {
172 let token = match ctx.request.token() {
174 Some(t) => t.to_string(),
175 None if self.authenticate_public_actions
176 && next.policy.is_public
177 && ctx.request.get_header("authorization").is_none() =>
178 {
179 return next.run(ctx).await;
180 }
181 None => {
182 return Err(BaseError::Unauthorized(
183 "缺少 Authorization Bearer Token".to_string(),
184 ))
185 }
186 };
187
188 let claims = ctx
190 .tools()
191 .token()?
192 .verify_token_checked(&token, crate::token::TokenType::Access)
193 .await?;
194
195 self.claims_validator.validate(&ctx, &claims).await?;
197
198 ctx.user = Some((self.build_user)(&claims).into_user_projection()?);
200 if let Some(user) = &ctx.user {
201 tracing::Span::current().record("actor_id", user.id);
202 }
203 next.run(ctx).await
204 }
205}