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, Ctx, Endpoint, EndpointHooks, Erased, ErasedAfter, ErasedBefore, ErasedEndpoint,
14 ErasedEventHandler, ErasedResolver, ErasedResponseHook, ErasedSessionGate, ErasedSessionHook,
15 FixedExpiry, Gate, HookCtx, OwnedGate, Response, SessionResolver, SessionUse, SignInAttempt,
16};
17use crate::error::{AuthError, ErrorCodes};
18use crate::events::Event;
19use crate::model::Fields;
20use crate::rate_limit::{Limit, Rule};
21use crate::schema::SchemaBuilder;
22use crate::session::SessionView;
23
24pub trait Plugin: Send + Sync + Sized + 'static {
26 const ID: &'static str;
28 type Requires;
30 type UserFields: Fields;
32 type SessionFields: Fields;
34
35 fn schema(&self, schema: &mut SchemaBuilder) {
38 let _ = schema;
39 }
40
41 fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
44 let _ = app;
45 }
46}
47
48pub(crate) struct RouteDef<D> {
49 pub method: Method,
50 pub path: &'static str,
51 pub owner: &'static str,
52 pub type_id: TypeId,
53 pub endpoint: Arc<dyn ErasedEndpoint<D>>,
54}
55
56pub struct Registry<D> {
58 pub(crate) schema: SchemaBuilder,
59 pub(crate) plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
60 pub(crate) routes: Vec<RouteDef<D>>,
61 pub(crate) hooks: HashMap<TypeId, EndpointHooks<D>>,
62 pub(crate) hook_targets: Vec<(TypeId, &'static str, &'static str)>,
63 pub(crate) server_endpoints: Vec<TypeId>,
64 pub(crate) gates: Vec<OwnedGate<D>>,
65 pub(crate) resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
66 pub(crate) response_hooks: Vec<ErasedResponseHook<D>>,
67 pub(crate) session_hooks: Vec<ErasedSessionHook<D>>,
68 pub(crate) session_gates: Vec<ErasedSessionGate<D>>,
69 pub(crate) fixed_expiry: Vec<FixedExpiry>,
70 pub(crate) events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
71 pub(crate) rate_rules: Vec<Rule>,
72 pub(crate) error_codes: Vec<(&'static str, &'static str)>,
73 pub(crate) errors: Vec<String>,
74 pub(crate) owner: &'static str,
75}
76
77impl<D: Adapter> Registry<D> {
78 pub(crate) fn new() -> Self {
79 Self {
80 schema: SchemaBuilder::new(),
81 plugins: HashMap::new(),
82 routes: Vec::new(),
83 hooks: HashMap::new(),
84 hook_targets: Vec::new(),
85 server_endpoints: Vec::new(),
86 gates: Vec::new(),
87 resolvers: Vec::new(),
88 response_hooks: Vec::new(),
89 session_hooks: Vec::new(),
90 session_gates: Vec::new(),
91 fixed_expiry: Vec::new(),
92 events: HashMap::new(),
93 rate_rules: Vec::new(),
94 error_codes: Vec::new(),
95 errors: Vec::new(),
96 owner: "core",
97 }
98 }
99
100 pub(crate) fn set_owner(&mut self, owner: &'static str) {
101 self.owner = owner;
102 self.schema.owner = owner;
103 }
104
105 pub(crate) fn register_plugin<P: Plugin>(&mut self, plugin: &Arc<P>) {
106 if self
107 .plugins
108 .insert(TypeId::of::<P>(), plugin.clone())
109 .is_some()
110 {
111 self.errors
112 .push(format!("plugin `{}` is registered twice", P::ID));
113 return;
114 }
115 let previous = self.owner;
116 self.set_owner(P::ID);
117 self.schema.extend("user", P::UserFields::columns());
118 self.schema.extend("session", P::SessionFields::columns());
119 plugin.schema(&mut self.schema);
120 plugin.init(&mut PluginBuilder { registry: self });
121 self.set_owner(previous);
122 }
123}
124
125pub struct PluginBuilder<'r, D> {
127 pub(crate) registry: &'r mut Registry<D>,
128}
129
130impl<D: Adapter> PluginBuilder<'_, D> {
131 pub fn owner(&self) -> &'static str {
133 self.registry.owner
134 }
135
136 pub fn schema(&mut self) -> &mut SchemaBuilder {
138 &mut self.registry.schema
139 }
140
141 pub fn endpoint<E: Endpoint<D>>(&mut self, endpoint: E) -> &mut Self {
142 let registry = &mut *self.registry;
143 if let Some(clash) = registry
144 .routes
145 .iter()
146 .find(|r| r.method == E::METHOD && r.path == E::PATH)
147 {
148 registry.errors.push(format!(
149 "route {} {} is registered by both `{}` and `{}`",
150 E::METHOD,
151 E::PATH,
152 clash.owner,
153 registry.owner
154 ));
155 return self;
156 }
157 registry.routes.push(RouteDef {
158 method: E::METHOD,
159 path: E::PATH,
160 owner: registry.owner,
161 type_id: TypeId::of::<E>(),
162 endpoint: Arc::new(Erased(endpoint)),
163 });
164 self
165 }
166
167 pub fn server_endpoint<E: Endpoint<D>>(&mut self) -> &mut Self {
170 self.registry.server_endpoints.push(TypeId::of::<E>());
171 self
172 }
173
174 pub fn hook<E: Endpoint<D>>(&mut self) -> HookBuilder<'_, D, E> {
176 self.registry
177 .hook_targets
178 .push((TypeId::of::<E>(), type_name::<E>(), self.registry.owner));
179 HookBuilder {
180 registry: self.registry,
181 _endpoint: PhantomData,
182 }
183 }
184
185 pub fn sign_in_gate<F, Fut>(&mut self, gate: F) -> &mut Self
190 where
191 F: Fn(HookCtx<D>, SignInAttempt) -> Fut + Send + Sync + 'static,
192 Fut: Future<Output = Result<Gate, AuthError>> + Send + 'static,
193 {
194 let owner = self.registry.owner;
195 self.registry.gates.push(OwnedGate {
196 owner,
197 gate: Arc::new(move |ctx, attempt| Box::pin(gate(ctx, attempt))),
198 });
199 self
200 }
201
202 pub fn session_gate<F, Fut>(&mut self, gate: F) -> &mut Self
208 where
209 F: Fn(HookCtx<D>, SessionView, SessionUse) -> Fut + Send + Sync + 'static,
210 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
211 {
212 self.registry
213 .session_gates
214 .push(Arc::new(move |ctx, session, usage| {
215 Box::pin(gate(ctx, session, usage))
216 }));
217 self
218 }
219
220 pub fn fixed_session_expiry(
224 &mut self,
225 fixed: impl Fn(&SessionView) -> bool + Send + Sync + 'static,
226 ) -> &mut Self {
227 self.registry.fixed_expiry.push(Arc::new(fixed));
228 self
229 }
230
231 pub fn session_resolver(&mut self, resolver: impl SessionResolver<D>) -> &mut Self {
233 self.registry.resolvers.push(Arc::new(resolver));
234 self
235 }
236
237 pub fn on_response(
242 &mut self,
243 hook: impl Fn(&Ctx<D>, &mut Response) + Send + Sync + 'static,
244 ) -> &mut Self {
245 self.registry.response_hooks.push(Arc::new(hook));
246 self
247 }
248
249 pub fn on_session_created<F, Fut>(&mut self, hook: F) -> &mut Self
262 where
263 F: Fn(HookCtx<D>, SessionView) -> Fut + Send + Sync + 'static,
264 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
265 {
266 self.registry
267 .session_hooks
268 .push(Arc::new(move |ctx, session| Box::pin(hook(ctx, session))));
269 self
270 }
271
272 pub fn on<Ev, F, Fut>(&mut self, handler: F) -> &mut Self
274 where
275 Ev: Event,
276 F: Fn(Ev, Ctx<D>) -> Fut + Send + Sync + 'static,
277 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
278 {
279 let erased: ErasedEventHandler<D> = Arc::new(move |event, ctx| {
280 let event = event
281 .downcast_ref::<Ev>()
282 .expect("event routed by TypeId")
283 .clone();
284 Box::pin(handler(event, ctx))
285 });
286 self.registry
287 .events
288 .entry(TypeId::of::<Ev>())
289 .or_default()
290 .push(erased);
291 self
292 }
293
294 pub fn rate_limit(&mut self, pattern: impl Into<String>, limit: Limit) -> &mut Self {
296 self.registry.rate_rules.push(Rule {
297 pattern: pattern.into(),
298 limit,
299 });
300 self
301 }
302
303 pub fn errors<E: ErrorCodes>(&mut self) -> &mut Self {
305 let owner = self.registry.owner;
306 for code in E::CODES {
307 if let Some((_, first)) = self.registry.error_codes.iter().find(|(c, _)| c == code) {
308 self.registry.errors.push(format!(
309 "error code `{code}` is registered by both `{first}` and `{owner}`"
310 ));
311 continue;
312 }
313 self.registry.error_codes.push((code, owner));
314 }
315 self
316 }
317}
318
319pub struct HookBuilder<'r, D, E> {
320 registry: &'r mut Registry<D>,
321 _endpoint: PhantomData<fn() -> E>,
322}
323
324impl<D: Adapter, E: Endpoint<D>> HookBuilder<'_, D, E> {
325 pub fn before<F, Fut>(self, hook: F) -> Self
327 where
328 F: Fn(HookCtx<D>, E::Input) -> Fut + Send + Sync + 'static,
329 Fut: Future<Output = Result<Before<E::Input>, AuthError>> + Send + 'static,
330 {
331 let hook = Arc::new(hook);
332 let erased: ErasedBefore<D> = Arc::new(move |ctx, input| {
333 let hook = hook.clone();
334 Box::pin(async move {
335 let input = *input.downcast::<E::Input>().expect("hook input type");
336 Ok(match hook(ctx, input).await? {
337 Before::Continue(input) => {
338 Before::Continue(Box::new(input) as Box<dyn Any + Send>)
339 }
340 Before::Respond(response) => Before::Respond(response),
341 })
342 })
343 });
344 self.registry
345 .hooks
346 .entry(TypeId::of::<E>())
347 .or_default()
348 .before
349 .push(erased);
350 self
351 }
352
353 pub fn after<F, Fut>(self, hook: F) -> Self
355 where
356 F: Fn(HookCtx<D>, E::Output) -> Fut + Send + Sync + 'static,
357 Fut: Future<Output = Result<After<E::Output>, AuthError>> + Send + 'static,
358 {
359 let hook = Arc::new(hook);
360 let erased: ErasedAfter<D> = Arc::new(move |ctx, output| {
361 let hook = hook.clone();
362 Box::pin(async move {
363 let output = *output.downcast::<E::Output>().expect("hook output type");
364 Ok(match hook(ctx, output).await? {
365 After::Continue(output) => {
366 After::Continue(Box::new(output) as Box<dyn Any + Send>)
367 }
368 After::Respond(response) => After::Respond(response),
369 })
370 })
371 });
372 self.registry
373 .hooks
374 .entry(TypeId::of::<E>())
375 .or_default()
376 .after
377 .push(erased);
378 self
379 }
380}