1use std::any::{Any, TypeId, type_name};
4use std::collections::HashMap;
5use std::future::Future;
6use std::marker::PhantomData;
7use std::sync::Arc;
8
9use http::Method;
10
11use crate::adapter::Adapter;
12use crate::endpoint::{
13 After, Before, BoxFuture, Ctx, Endpoint, EndpointHooks, Erased, ErasedAfter, ErasedBefore,
14 ErasedClaimHook, ErasedEndpoint, ErasedEventHandler, ErasedResolver, ErasedResponseHook,
15 ErasedSessionGate, ErasedSessionHook, ErasedUserInputHook, FixedExpiry, Gate, HookCtx,
16 OwnedGate, Response, SessionResolver, SessionUse, SignInAttempt,
17};
18use crate::error::{AuthError, ErrorCodes};
19use crate::events::Event;
20use crate::internal::{Claim, UserInput};
21use crate::model::Fields;
22use crate::rate_limit::{Limit, Rule};
23use crate::schema::SchemaBuilder;
24use crate::session::SessionView;
25
26pub trait Plugin: Send + Sync + Sized + 'static {
28 const ID: &'static str;
30 type Requires;
32 type UserFields: Fields;
34 type SessionFields: Fields;
36
37 fn schema(&self, schema: &mut SchemaBuilder) {
40 let _ = schema;
41 }
42
43 fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
46 let _ = app;
47 }
48}
49
50pub(crate) struct RouteDef<D> {
51 pub method: Method,
52 pub path: &'static str,
53 pub owner: &'static str,
54 pub type_id: TypeId,
55 pub endpoint: Arc<dyn ErasedEndpoint<D>>,
56}
57
58pub struct Registry<D> {
60 pub(crate) schema: SchemaBuilder,
61 pub(crate) plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
62 pub(crate) routes: Vec<RouteDef<D>>,
63 pub(crate) hooks: HashMap<TypeId, EndpointHooks<D>>,
64 pub(crate) hook_targets: Vec<(TypeId, &'static str, &'static str)>,
65 pub(crate) server_endpoints: Vec<TypeId>,
66 pub(crate) gates: Vec<OwnedGate<D>>,
67 pub(crate) resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
68 pub(crate) response_hooks: Vec<ErasedResponseHook<D>>,
69 pub(crate) session_hooks: Vec<ErasedSessionHook<D>>,
70 pub(crate) session_gates: Vec<ErasedSessionGate<D>>,
71 pub(crate) fixed_expiry: Vec<FixedExpiry>,
72 pub(crate) claim_hooks: Vec<ErasedClaimHook<D>>,
73 pub(crate) user_input_hooks: Vec<ErasedUserInputHook<D>>,
74 pub(crate) events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
75 pub(crate) rate_rules: Vec<Rule>,
76 pub(crate) error_codes: Vec<(&'static str, &'static str)>,
77 pub(crate) errors: Vec<String>,
78 pub(crate) owner: &'static str,
79}
80
81impl<D: Adapter> Registry<D> {
82 pub(crate) fn new() -> Self {
83 Self {
84 schema: SchemaBuilder::new(),
85 plugins: HashMap::new(),
86 routes: Vec::new(),
87 hooks: HashMap::new(),
88 hook_targets: Vec::new(),
89 server_endpoints: Vec::new(),
90 gates: Vec::new(),
91 resolvers: Vec::new(),
92 response_hooks: Vec::new(),
93 session_hooks: Vec::new(),
94 session_gates: Vec::new(),
95 fixed_expiry: Vec::new(),
96 claim_hooks: Vec::new(),
97 user_input_hooks: Vec::new(),
98 events: HashMap::new(),
99 rate_rules: Vec::new(),
100 error_codes: Vec::new(),
101 errors: Vec::new(),
102 owner: "core",
103 }
104 }
105
106 pub(crate) fn set_owner(&mut self, owner: &'static str) {
107 self.owner = owner;
108 self.schema.owner = owner;
109 }
110
111 pub(crate) fn register_plugin<P: Plugin>(&mut self, plugin: &Arc<P>) {
112 if self
113 .plugins
114 .insert(TypeId::of::<P>(), plugin.clone())
115 .is_some()
116 {
117 self.errors
118 .push(format!("plugin `{}` is registered twice", P::ID));
119 return;
120 }
121 let previous = self.owner;
122 self.set_owner(P::ID);
123 self.schema.extend("user", P::UserFields::columns());
124 self.schema.extend("session", P::SessionFields::columns());
125 plugin.schema(&mut self.schema);
126 plugin.init(&mut PluginBuilder { registry: self });
127 self.set_owner(previous);
128 }
129}
130
131pub struct PluginBuilder<'r, D> {
133 pub(crate) registry: &'r mut Registry<D>,
134}
135
136impl<D: Adapter> PluginBuilder<'_, D> {
137 pub fn owner(&self) -> &'static str {
139 self.registry.owner
140 }
141
142 pub fn schema(&mut self) -> &mut SchemaBuilder {
144 &mut self.registry.schema
145 }
146
147 pub fn endpoint<E: Endpoint<D>>(&mut self, endpoint: E) -> &mut Self {
148 let registry = &mut *self.registry;
149 if let Some(clash) = registry
150 .routes
151 .iter()
152 .find(|r| r.method == E::METHOD && r.path == E::PATH)
153 {
154 registry.errors.push(format!(
155 "route {} {} is registered by both `{}` and `{}`",
156 E::METHOD,
157 E::PATH,
158 clash.owner,
159 registry.owner
160 ));
161 return self;
162 }
163 registry.routes.push(RouteDef {
164 method: E::METHOD,
165 path: E::PATH,
166 owner: registry.owner,
167 type_id: TypeId::of::<E>(),
168 endpoint: Arc::new(Erased(endpoint)),
169 });
170 self
171 }
172
173 pub fn server_endpoint<E: Endpoint<D>>(&mut self) -> &mut Self {
176 self.registry.server_endpoints.push(TypeId::of::<E>());
177 self
178 }
179
180 pub fn hook<E: Endpoint<D>>(&mut self) -> HookBuilder<'_, D, E> {
182 self.registry
183 .hook_targets
184 .push((TypeId::of::<E>(), type_name::<E>(), self.registry.owner));
185 HookBuilder {
186 registry: self.registry,
187 _endpoint: PhantomData,
188 }
189 }
190
191 pub fn sign_in_gate<F, Fut>(&mut self, gate: F) -> &mut Self
196 where
197 F: Fn(HookCtx<D>, SignInAttempt) -> Fut + Send + Sync + 'static,
198 Fut: Future<Output = Result<Gate, AuthError>> + Send + 'static,
199 {
200 let owner = self.registry.owner;
201 self.registry.gates.push(OwnedGate {
202 owner,
203 gate: Arc::new(move |ctx, attempt| Box::pin(gate(ctx, attempt))),
204 });
205 self
206 }
207
208 pub fn session_gate<F, Fut>(&mut self, gate: F) -> &mut Self
214 where
215 F: Fn(HookCtx<D>, SessionView, SessionUse) -> Fut + Send + Sync + 'static,
216 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
217 {
218 self.registry
219 .session_gates
220 .push(Arc::new(move |ctx, session, usage| {
221 Box::pin(gate(ctx, session, usage))
222 }));
223 self
224 }
225
226 pub fn fixed_session_expiry(
230 &mut self,
231 fixed: impl Fn(&SessionView) -> bool + Send + Sync + 'static,
232 ) -> &mut Self {
233 self.registry.fixed_expiry.push(Arc::new(fixed));
234 self
235 }
236
237 pub fn session_resolver(&mut self, resolver: impl SessionResolver<D>) -> &mut Self {
239 self.registry.resolvers.push(Arc::new(resolver));
240 self
241 }
242
243 pub fn on_response(
248 &mut self,
249 hook: impl Fn(&Ctx<D>, &mut Response) + Send + Sync + 'static,
250 ) -> &mut Self {
251 self.registry.response_hooks.push(Arc::new(hook));
252 self
253 }
254
255 pub fn on_session_created<F, Fut>(&mut self, hook: F) -> &mut Self
268 where
269 F: Fn(HookCtx<D>, SessionView) -> Fut + Send + Sync + 'static,
270 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
271 {
272 self.registry
273 .session_hooks
274 .push(Arc::new(move |ctx, session| Box::pin(hook(ctx, session))));
275 self
276 }
277
278 pub fn on_claim<F>(&mut self, cleanup: F) -> &mut Self
296 where
297 F: for<'a> Fn(Claim<'a, D>) -> BoxFuture<'a, Result<(), AuthError>> + Send + Sync + 'static,
298 {
299 self.registry.claim_hooks.push(Arc::new(cleanup));
300 self
301 }
302
303 pub fn prepare_user_input<F, Fut>(&mut self, hook: F) -> &mut Self
311 where
312 F: Fn(HookCtx<D>, serde_json::Map<String, serde_json::Value>, UserInput) -> Fut
313 + Send
314 + Sync
315 + 'static,
316 Fut: Future<Output = Result<serde_json::Map<String, serde_json::Value>, AuthError>>
317 + Send
318 + 'static,
319 {
320 self.registry
321 .user_input_hooks
322 .push(Arc::new(move |ctx, input, kind| {
323 Box::pin(hook(ctx, input, kind))
324 }));
325 self
326 }
327
328 pub fn on<Ev, F, Fut>(&mut self, handler: F) -> &mut Self
330 where
331 Ev: Event,
332 F: Fn(Ev, Ctx<D>) -> Fut + Send + Sync + 'static,
333 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
334 {
335 let erased: ErasedEventHandler<D> = Arc::new(move |event, ctx| {
336 let event = event
337 .downcast_ref::<Ev>()
338 .expect("event routed by TypeId")
339 .clone();
340 Box::pin(handler(event, ctx))
341 });
342 self.registry
343 .events
344 .entry(TypeId::of::<Ev>())
345 .or_default()
346 .push(erased);
347 self
348 }
349
350 pub fn rate_limit(&mut self, pattern: impl Into<String>, limit: Limit) -> &mut Self {
352 self.registry.rate_rules.push(Rule {
353 pattern: pattern.into(),
354 limit,
355 });
356 self
357 }
358
359 pub fn errors<E: ErrorCodes>(&mut self) -> &mut Self {
361 let owner = self.registry.owner;
362 for code in E::CODES {
363 if let Some((_, first)) = self.registry.error_codes.iter().find(|(c, _)| c == code) {
364 self.registry.errors.push(format!(
365 "error code `{code}` is registered by both `{first}` and `{owner}`"
366 ));
367 continue;
368 }
369 self.registry.error_codes.push((code, owner));
370 }
371 self
372 }
373}
374
375pub struct HookBuilder<'r, D, E> {
376 registry: &'r mut Registry<D>,
377 _endpoint: PhantomData<fn() -> E>,
378}
379
380impl<D: Adapter, E: Endpoint<D>> HookBuilder<'_, D, E> {
381 pub fn before<F, Fut>(self, hook: F) -> Self
383 where
384 F: Fn(HookCtx<D>, E::Input) -> Fut + Send + Sync + 'static,
385 Fut: Future<Output = Result<Before<E::Input>, AuthError>> + Send + 'static,
386 {
387 let hook = Arc::new(hook);
388 let erased: ErasedBefore<D> = Arc::new(move |ctx, input| {
389 let hook = hook.clone();
390 Box::pin(async move {
391 let input = *input.downcast::<E::Input>().expect("hook input type");
392 Ok(match hook(ctx, input).await? {
393 Before::Continue(input) => {
394 Before::Continue(Box::new(input) as Box<dyn Any + Send>)
395 }
396 Before::Respond(response) => Before::Respond(response),
397 })
398 })
399 });
400 self.registry
401 .hooks
402 .entry(TypeId::of::<E>())
403 .or_default()
404 .before
405 .push(erased);
406 self
407 }
408
409 pub fn after<F, Fut>(self, hook: F) -> Self
411 where
412 F: Fn(HookCtx<D>, E::Output) -> Fut + Send + Sync + 'static,
413 Fut: Future<Output = Result<After<E::Output>, AuthError>> + Send + 'static,
414 {
415 let hook = Arc::new(hook);
416 let erased: ErasedAfter<D> = Arc::new(move |ctx, output| {
417 let hook = hook.clone();
418 Box::pin(async move {
419 let output = *output.downcast::<E::Output>().expect("hook output type");
420 Ok(match hook(ctx, output).await? {
421 After::Continue(output) => {
422 After::Continue(Box::new(output) as Box<dyn Any + Send>)
423 }
424 After::Respond(response) => After::Respond(response),
425 })
426 })
427 });
428 self.registry
429 .hooks
430 .entry(TypeId::of::<E>())
431 .or_default()
432 .after
433 .push(erased);
434 self
435 }
436}