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