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