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 pub(crate) account_providers: Vec<String>,
80}
81
82impl<D: Adapter> Registry<D> {
83 pub(crate) fn new() -> Self {
84 Self {
85 schema: SchemaBuilder::new(),
86 plugins: HashMap::new(),
87 routes: Vec::new(),
88 hooks: HashMap::new(),
89 hook_targets: Vec::new(),
90 server_endpoints: Vec::new(),
91 gates: Vec::new(),
92 resolvers: Vec::new(),
93 response_hooks: Vec::new(),
94 session_hooks: Vec::new(),
95 session_gates: Vec::new(),
96 fixed_expiry: Vec::new(),
97 claim_hooks: Vec::new(),
98 user_input_hooks: Vec::new(),
99 events: HashMap::new(),
100 rate_rules: Vec::new(),
101 error_codes: Vec::new(),
102 errors: Vec::new(),
103 owner: "core",
104 account_providers: Vec::new(),
105 }
106 }
107
108 pub(crate) fn set_owner(&mut self, owner: &'static str) {
109 self.owner = owner;
110 self.schema.owner = owner;
111 }
112
113 pub(crate) fn register_plugin<P: Plugin>(&mut self, plugin: &Arc<P>) {
114 if self
115 .plugins
116 .insert(TypeId::of::<P>(), plugin.clone())
117 .is_some()
118 {
119 self.errors
120 .push(format!("plugin `{}` is registered twice", P::ID));
121 return;
122 }
123 let previous = self.owner;
124 self.set_owner(P::ID);
125 self.schema.extend("user", P::UserFields::columns());
126 self.schema.extend("session", P::SessionFields::columns());
127 plugin.schema(&mut self.schema);
128 plugin.init(&mut PluginBuilder { registry: self });
129 self.set_owner(previous);
130 }
131}
132
133pub struct PluginBuilder<'r, D> {
135 pub(crate) registry: &'r mut Registry<D>,
136}
137
138impl<D: Adapter> PluginBuilder<'_, D> {
139 pub fn owner(&self) -> &'static str {
141 self.registry.owner
142 }
143
144 pub fn schema(&mut self) -> &mut SchemaBuilder {
146 &mut self.registry.schema
147 }
148
149 pub fn endpoint<E: Endpoint<D>>(&mut self, endpoint: E) -> &mut Self {
150 let registry = &mut *self.registry;
151 if let Some(clash) = registry
152 .routes
153 .iter()
154 .find(|r| r.method == E::METHOD && r.path == E::PATH)
155 {
156 registry.errors.push(format!(
157 "route {} {} is registered by both `{}` and `{}`",
158 E::METHOD,
159 E::PATH,
160 clash.owner,
161 registry.owner
162 ));
163 return self;
164 }
165 registry.routes.push(RouteDef {
166 method: E::METHOD,
167 path: E::PATH,
168 owner: registry.owner,
169 type_id: TypeId::of::<E>(),
170 endpoint: Arc::new(Erased(endpoint)),
171 });
172 self
173 }
174
175 pub fn server_endpoint<E: Endpoint<D>>(&mut self) -> &mut Self {
178 self.registry.server_endpoints.push(TypeId::of::<E>());
179 self
180 }
181
182 pub fn hook<E: Endpoint<D>>(&mut self) -> HookBuilder<'_, D, E> {
184 self.registry
185 .hook_targets
186 .push((TypeId::of::<E>(), type_name::<E>(), self.registry.owner));
187 HookBuilder {
188 registry: self.registry,
189 _endpoint: PhantomData,
190 }
191 }
192
193 pub fn sign_in_gate<F, Fut>(&mut self, gate: F) -> &mut Self
198 where
199 F: Fn(HookCtx<D>, SignInAttempt) -> Fut + Send + Sync + 'static,
200 Fut: Future<Output = Result<Gate, AuthError>> + Send + 'static,
201 {
202 let owner = self.registry.owner;
203 self.registry.gates.push(OwnedGate {
204 owner,
205 gate: Arc::new(move |ctx, attempt| Box::pin(gate(ctx, attempt))),
206 });
207 self
208 }
209
210 pub fn session_gate<F, Fut>(&mut self, gate: F) -> &mut Self
216 where
217 F: Fn(HookCtx<D>, SessionView, SessionUse) -> Fut + Send + Sync + 'static,
218 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
219 {
220 self.registry
221 .session_gates
222 .push(Arc::new(move |ctx, session, usage| {
223 Box::pin(gate(ctx, session, usage))
224 }));
225 self
226 }
227
228 pub fn fixed_session_expiry(
232 &mut self,
233 fixed: impl Fn(&SessionView) -> bool + Send + Sync + 'static,
234 ) -> &mut Self {
235 self.registry.fixed_expiry.push(Arc::new(fixed));
236 self
237 }
238
239 pub fn session_resolver(&mut self, resolver: impl SessionResolver<D>) -> &mut Self {
241 self.registry.resolvers.push(Arc::new(resolver));
242 self
243 }
244
245 pub fn on_response(
250 &mut self,
251 hook: impl Fn(&Ctx<D>, &mut Response) + Send + Sync + 'static,
252 ) -> &mut Self {
253 self.registry.response_hooks.push(Arc::new(hook));
254 self
255 }
256
257 pub fn on_session_created<F, Fut>(&mut self, hook: F) -> &mut Self
270 where
271 F: Fn(HookCtx<D>, SessionView) -> Fut + Send + Sync + 'static,
272 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
273 {
274 self.registry
275 .session_hooks
276 .push(Arc::new(move |ctx, session| Box::pin(hook(ctx, session))));
277 self
278 }
279
280 pub fn on_claim<F>(&mut self, cleanup: F) -> &mut Self
298 where
299 F: for<'a> Fn(Claim<'a, D>) -> BoxFuture<'a, Result<(), AuthError>> + Send + Sync + 'static,
300 {
301 self.registry.claim_hooks.push(Arc::new(cleanup));
302 self
303 }
304
305 pub fn prepare_user_input<F, Fut>(&mut self, hook: F) -> &mut Self
313 where
314 F: Fn(HookCtx<D>, serde_json::Map<String, serde_json::Value>, UserInput) -> Fut
315 + Send
316 + Sync
317 + 'static,
318 Fut: Future<Output = Result<serde_json::Map<String, serde_json::Value>, AuthError>>
319 + Send
320 + 'static,
321 {
322 self.registry
323 .user_input_hooks
324 .push(Arc::new(move |ctx, input, kind| {
325 Box::pin(hook(ctx, input, kind))
326 }));
327 self
328 }
329
330 pub fn on<Ev, F, Fut>(&mut self, handler: F) -> &mut Self
332 where
333 Ev: Event,
334 F: Fn(Ev, Ctx<D>) -> Fut + Send + Sync + 'static,
335 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
336 {
337 let erased: ErasedEventHandler<D> = Arc::new(move |event, ctx| {
338 let event = event
339 .downcast_ref::<Ev>()
340 .expect("event routed by TypeId")
341 .clone();
342 Box::pin(handler(event, ctx))
343 });
344 self.registry
345 .events
346 .entry(TypeId::of::<Ev>())
347 .or_default()
348 .push(erased);
349 self
350 }
351
352 pub fn rate_limit(&mut self, pattern: impl Into<String>, limit: Limit) -> &mut Self {
354 self.registry.rate_rules.push(Rule {
355 pattern: pattern.into(),
356 limit,
357 });
358 self
359 }
360
361 pub fn account_provider(&mut self, provider_id: impl Into<String>) -> &mut Self {
365 self.registry.account_providers.push(provider_id.into());
366 self
367 }
368
369 pub fn errors<E: ErrorCodes>(&mut self) -> &mut Self {
371 let owner = self.registry.owner;
372 for code in E::CODES {
373 if let Some((_, first)) = self.registry.error_codes.iter().find(|(c, _)| c == code) {
374 self.registry.errors.push(format!(
375 "error code `{code}` is registered by both `{first}` and `{owner}`"
376 ));
377 continue;
378 }
379 self.registry.error_codes.push((code, owner));
380 }
381 self
382 }
383}
384
385pub struct HookBuilder<'r, D, E> {
386 registry: &'r mut Registry<D>,
387 _endpoint: PhantomData<fn() -> E>,
388}
389
390impl<D: Adapter, E: Endpoint<D>> HookBuilder<'_, D, E> {
391 pub fn before<F, Fut>(self, hook: F) -> Self
393 where
394 F: Fn(HookCtx<D>, E::Input) -> Fut + Send + Sync + 'static,
395 Fut: Future<Output = Result<Before<E::Input>, AuthError>> + Send + 'static,
396 {
397 let hook = Arc::new(hook);
398 let erased: ErasedBefore<D> = Arc::new(move |ctx, input| {
399 let hook = hook.clone();
400 Box::pin(async move {
401 let input = *input.downcast::<E::Input>().expect("hook input type");
402 Ok(match hook(ctx, input).await? {
403 Before::Continue(input) => {
404 Before::Continue(Box::new(input) as Box<dyn Any + Send>)
405 }
406 Before::Respond(response) => Before::Respond(response),
407 })
408 })
409 });
410 self.registry
411 .hooks
412 .entry(TypeId::of::<E>())
413 .or_default()
414 .before
415 .push(erased);
416 self
417 }
418
419 pub fn after<F, Fut>(self, hook: F) -> Self
421 where
422 F: Fn(HookCtx<D>, E::Output) -> Fut + Send + Sync + 'static,
423 Fut: Future<Output = Result<After<E::Output>, AuthError>> + Send + 'static,
424 {
425 let hook = Arc::new(hook);
426 let erased: ErasedAfter<D> = Arc::new(move |ctx, output| {
427 let hook = hook.clone();
428 Box::pin(async move {
429 let output = *output.downcast::<E::Output>().expect("hook output type");
430 Ok(match hook(ctx, output).await? {
431 After::Continue(output) => {
432 After::Continue(Box::new(output) as Box<dyn Any + Send>)
433 }
434 After::Respond(response) => After::Respond(response),
435 })
436 })
437 });
438 self.registry
439 .hooks
440 .entry(TypeId::of::<E>())
441 .or_default()
442 .after
443 .push(erased);
444 self
445 }
446}