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, Gate, HookCtx, OwnedGate, Response,
15 SessionResolver, 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;
22
23pub trait Plugin: Send + Sync + Sized + 'static {
25 const ID: &'static str;
27 type Requires;
29 type UserFields: Fields;
31 type SessionFields: Fields;
33
34 fn schema(&self, schema: &mut SchemaBuilder) {
37 let _ = schema;
38 }
39
40 fn init<D: Adapter>(self: &Arc<Self>, app: &mut PluginBuilder<'_, D>) {
43 let _ = app;
44 }
45}
46
47pub(crate) struct RouteDef<D> {
48 pub method: Method,
49 pub path: &'static str,
50 pub owner: &'static str,
51 pub type_id: TypeId,
52 pub endpoint: Arc<dyn ErasedEndpoint<D>>,
53}
54
55pub struct Registry<D> {
57 pub(crate) schema: SchemaBuilder,
58 pub(crate) plugins: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
59 pub(crate) routes: Vec<RouteDef<D>>,
60 pub(crate) hooks: HashMap<TypeId, EndpointHooks<D>>,
61 pub(crate) hook_targets: Vec<(TypeId, &'static str, &'static str)>,
62 pub(crate) server_endpoints: Vec<TypeId>,
63 pub(crate) gates: Vec<OwnedGate<D>>,
64 pub(crate) resolvers: Vec<Arc<dyn ErasedResolver<D>>>,
65 pub(crate) response_hooks: Vec<ErasedResponseHook<D>>,
66 pub(crate) events: HashMap<TypeId, Vec<ErasedEventHandler<D>>>,
67 pub(crate) rate_rules: Vec<Rule>,
68 pub(crate) error_codes: Vec<(&'static str, &'static str)>,
69 pub(crate) errors: Vec<String>,
70 pub(crate) owner: &'static str,
71}
72
73impl<D: Adapter> Registry<D> {
74 pub(crate) fn new() -> Self {
75 Self {
76 schema: SchemaBuilder::new(),
77 plugins: HashMap::new(),
78 routes: Vec::new(),
79 hooks: HashMap::new(),
80 hook_targets: Vec::new(),
81 server_endpoints: Vec::new(),
82 gates: Vec::new(),
83 resolvers: Vec::new(),
84 response_hooks: Vec::new(),
85 events: HashMap::new(),
86 rate_rules: Vec::new(),
87 error_codes: Vec::new(),
88 errors: Vec::new(),
89 owner: "core",
90 }
91 }
92
93 pub(crate) fn set_owner(&mut self, owner: &'static str) {
94 self.owner = owner;
95 self.schema.owner = owner;
96 }
97
98 pub(crate) fn register_plugin<P: Plugin>(&mut self, plugin: &Arc<P>) {
99 if self
100 .plugins
101 .insert(TypeId::of::<P>(), plugin.clone())
102 .is_some()
103 {
104 self.errors
105 .push(format!("plugin `{}` is registered twice", P::ID));
106 return;
107 }
108 let previous = self.owner;
109 self.set_owner(P::ID);
110 self.schema.extend("user", P::UserFields::columns());
111 self.schema.extend("session", P::SessionFields::columns());
112 plugin.schema(&mut self.schema);
113 plugin.init(&mut PluginBuilder { registry: self });
114 self.set_owner(previous);
115 }
116}
117
118pub struct PluginBuilder<'r, D> {
120 pub(crate) registry: &'r mut Registry<D>,
121}
122
123impl<D: Adapter> PluginBuilder<'_, D> {
124 pub fn owner(&self) -> &'static str {
126 self.registry.owner
127 }
128
129 pub fn schema(&mut self) -> &mut SchemaBuilder {
131 &mut self.registry.schema
132 }
133
134 pub fn endpoint<E: Endpoint<D>>(&mut self, endpoint: E) -> &mut Self {
135 let registry = &mut *self.registry;
136 if let Some(clash) = registry
137 .routes
138 .iter()
139 .find(|r| r.method == E::METHOD && r.path == E::PATH)
140 {
141 registry.errors.push(format!(
142 "route {} {} is registered by both `{}` and `{}`",
143 E::METHOD,
144 E::PATH,
145 clash.owner,
146 registry.owner
147 ));
148 return self;
149 }
150 registry.routes.push(RouteDef {
151 method: E::METHOD,
152 path: E::PATH,
153 owner: registry.owner,
154 type_id: TypeId::of::<E>(),
155 endpoint: Arc::new(Erased(endpoint)),
156 });
157 self
158 }
159
160 pub fn server_endpoint<E: Endpoint<D>>(&mut self) -> &mut Self {
163 self.registry.server_endpoints.push(TypeId::of::<E>());
164 self
165 }
166
167 pub fn hook<E: Endpoint<D>>(&mut self) -> HookBuilder<'_, D, E> {
169 self.registry
170 .hook_targets
171 .push((TypeId::of::<E>(), type_name::<E>(), self.registry.owner));
172 HookBuilder {
173 registry: self.registry,
174 _endpoint: PhantomData,
175 }
176 }
177
178 pub fn sign_in_gate<F, Fut>(&mut self, gate: F) -> &mut Self
183 where
184 F: Fn(HookCtx<D>, SignInAttempt) -> Fut + Send + Sync + 'static,
185 Fut: Future<Output = Result<Gate, AuthError>> + Send + 'static,
186 {
187 let owner = self.registry.owner;
188 self.registry.gates.push(OwnedGate {
189 owner,
190 gate: Arc::new(move |ctx, attempt| Box::pin(gate(ctx, attempt))),
191 });
192 self
193 }
194
195 pub fn session_resolver(&mut self, resolver: impl SessionResolver<D>) -> &mut Self {
197 self.registry.resolvers.push(Arc::new(resolver));
198 self
199 }
200
201 pub fn on_response(
206 &mut self,
207 hook: impl Fn(&Ctx<D>, &mut Response) + Send + Sync + 'static,
208 ) -> &mut Self {
209 self.registry.response_hooks.push(Arc::new(hook));
210 self
211 }
212
213 pub fn on<Ev, F, Fut>(&mut self, handler: F) -> &mut Self
215 where
216 Ev: Event,
217 F: Fn(Ev, Ctx<D>) -> Fut + Send + Sync + 'static,
218 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
219 {
220 let erased: ErasedEventHandler<D> = Arc::new(move |event, ctx| {
221 let event = event
222 .downcast_ref::<Ev>()
223 .expect("event routed by TypeId")
224 .clone();
225 Box::pin(handler(event, ctx))
226 });
227 self.registry
228 .events
229 .entry(TypeId::of::<Ev>())
230 .or_default()
231 .push(erased);
232 self
233 }
234
235 pub fn rate_limit(&mut self, pattern: impl Into<String>, limit: Limit) -> &mut Self {
237 self.registry.rate_rules.push(Rule {
238 pattern: pattern.into(),
239 limit,
240 });
241 self
242 }
243
244 pub fn errors<E: ErrorCodes>(&mut self) -> &mut Self {
246 let owner = self.registry.owner;
247 for code in E::CODES {
248 if let Some((_, first)) = self.registry.error_codes.iter().find(|(c, _)| c == code) {
249 self.registry.errors.push(format!(
250 "error code `{code}` is registered by both `{first}` and `{owner}`"
251 ));
252 continue;
253 }
254 self.registry.error_codes.push((code, owner));
255 }
256 self
257 }
258}
259
260pub struct HookBuilder<'r, D, E> {
261 registry: &'r mut Registry<D>,
262 _endpoint: PhantomData<fn() -> E>,
263}
264
265impl<D: Adapter, E: Endpoint<D>> HookBuilder<'_, D, E> {
266 pub fn before<F, Fut>(self, hook: F) -> Self
268 where
269 F: Fn(HookCtx<D>, E::Input) -> Fut + Send + Sync + 'static,
270 Fut: Future<Output = Result<Before<E::Input>, AuthError>> + Send + 'static,
271 {
272 let hook = Arc::new(hook);
273 let erased: ErasedBefore<D> = Arc::new(move |ctx, input| {
274 let hook = hook.clone();
275 Box::pin(async move {
276 let input = *input.downcast::<E::Input>().expect("hook input type");
277 Ok(match hook(ctx, input).await? {
278 Before::Continue(input) => {
279 Before::Continue(Box::new(input) as Box<dyn Any + Send>)
280 }
281 Before::Respond(response) => Before::Respond(response),
282 })
283 })
284 });
285 self.registry
286 .hooks
287 .entry(TypeId::of::<E>())
288 .or_default()
289 .before
290 .push(erased);
291 self
292 }
293
294 pub fn after<F, Fut>(self, hook: F) -> Self
296 where
297 F: Fn(HookCtx<D>, E::Output) -> Fut + Send + Sync + 'static,
298 Fut: Future<Output = Result<After<E::Output>, AuthError>> + Send + 'static,
299 {
300 let hook = Arc::new(hook);
301 let erased: ErasedAfter<D> = Arc::new(move |ctx, output| {
302 let hook = hook.clone();
303 Box::pin(async move {
304 let output = *output.downcast::<E::Output>().expect("hook output type");
305 Ok(match hook(ctx, output).await? {
306 After::Continue(output) => {
307 After::Continue(Box::new(output) as Box<dyn Any + Send>)
308 }
309 After::Respond(response) => After::Respond(response),
310 })
311 })
312 });
313 self.registry
314 .hooks
315 .entry(TypeId::of::<E>())
316 .or_default()
317 .after
318 .push(erased);
319 self
320 }
321}