1use std::collections::BTreeMap;
4use std::future::Future;
5use std::marker::PhantomData;
6use std::net::IpAddr;
7use std::sync::{Arc, Mutex};
8
9use bytes::Bytes;
10use http::header::{CACHE_CONTROL, COOKIE, ORIGIN, REFERER, USER_AGENT};
11use http::{HeaderMap, HeaderValue, Method, StatusCode};
12use serde::Serialize;
13use url::Url;
14
15use crate::adapter::{Adapter, Transaction};
16use crate::config::{
17 ClientIp, CookieConfig, CoreConfig, EmailPassword, EmailVerification, IdStrategy, Secure,
18 SessionConfig,
19};
20use crate::crypto::{Argon2id, Keys, Passwords, Secret, SignPurpose};
21use crate::endpoint::{
22 Effects, Endpoint, Executed, Outcome, RequestInfo, Response, Shared, dispatch_events, execute,
23 header_str,
24};
25use crate::error::{AuthError, BuildError, codes};
26use crate::events::{DeferredEvents, Event};
27use crate::hlist::{Append, Has, Nil, PluginSet, Satisfied};
28use crate::mail::{DynMailer, Mailer};
29use crate::migrate::Migrator;
30use crate::model::{Fields, Model};
31use crate::models::{Session, User};
32use crate::plugin::{Plugin, PluginBuilder, Registry};
33use crate::query::Db;
34use crate::rate_limit::{RateLimit, RateLimiter};
35use crate::routes;
36use crate::schema::Schema;
37use crate::session::{self, SessionData, UserView};
38
39#[derive(Debug)]
41pub struct FastAuth;
42
43#[derive(Debug)]
45pub struct NoDatabase;
46#[derive(Debug)]
48pub struct Missing;
49#[derive(Debug)]
51pub struct Present;
52
53impl FastAuth {
54 pub fn builder() -> Builder<NoDatabase, (), Nil, Missing, Missing> {
55 Builder {
56 db: NoDatabase,
57 plugins: Nil,
58 secrets: Vec::new(),
59 base_url: None,
60 app_name: "fastauth".into(),
61 base_path: "/api/auth".into(),
62 trusted_origins: Vec::new(),
63 session: SessionConfig::default(),
64 cookies: CookieConfig::default(),
65 email_password: None,
66 email_verification: EmailVerification::default(),
67 rate_limit: RateLimit::default(),
68 client_ip: ClientIp::Socket,
69 ids: IdStrategy::default(),
70 mailer: None,
71 allow_insecure: false,
72 app_init: Vec::new(),
73 _state: PhantomData,
74 }
75 }
76}
77
78type AppInit<D> = Box<dyn FnOnce(&mut PluginBuilder<'_, D>) + Send>;
79
80pub struct Builder<D, U, P, S, B> {
83 db: D,
84 plugins: P,
85 secrets: Vec<Secret>,
86 base_url: Option<String>,
87 app_name: String,
88 base_path: String,
89 trusted_origins: Vec<String>,
90 session: SessionConfig,
91 cookies: CookieConfig,
92 email_password: Option<EmailPassword>,
93 email_verification: EmailVerification,
94 rate_limit: RateLimit,
95 client_ip: ClientIp,
96 ids: IdStrategy,
97 mailer: Option<Arc<dyn DynMailer>>,
98 allow_insecure: bool,
99 app_init: Vec<AppInit<D>>,
100 _state: PhantomData<BuilderState<U, S, B>>,
101}
102
103type BuilderState<U, S, B> = fn() -> (U, S, B);
104
105impl<D, U, P, S, B> std::fmt::Debug for Builder<D, U, P, S, B> {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.debug_struct("Builder")
108 .field("base_url", &self.base_url)
109 .finish_non_exhaustive()
110 }
111}
112
113impl<D, U, P, S, B> Builder<D, U, P, S, B> {
114 fn retype<U2, P2, S2, B2>(self, plugins: impl FnOnce(P) -> P2) -> Builder<D, U2, P2, S2, B2> {
115 Builder {
116 db: self.db,
117 plugins: plugins(self.plugins),
118 secrets: self.secrets,
119 base_url: self.base_url,
120 app_name: self.app_name,
121 base_path: self.base_path,
122 trusted_origins: self.trusted_origins,
123 session: self.session,
124 cookies: self.cookies,
125 email_password: self.email_password,
126 email_verification: self.email_verification,
127 rate_limit: self.rate_limit,
128 client_ip: self.client_ip,
129 ids: self.ids,
130 mailer: self.mailer,
131 allow_insecure: self.allow_insecure,
132 app_init: self.app_init,
133 _state: PhantomData,
134 }
135 }
136
137 pub fn secret(mut self, secret: Secret) -> Builder<D, U, P, Present, B> {
139 self.secrets = vec![secret];
140 self.retype(|p| p)
141 }
142
143 pub fn secrets(
145 mut self,
146 secrets: impl IntoIterator<Item = Secret>,
147 ) -> Builder<D, U, P, Present, B> {
148 self.secrets = secrets.into_iter().collect();
149 self.retype(|p| p)
150 }
151
152 pub fn base_url(mut self, url: impl Into<String>) -> Builder<D, U, P, S, Present> {
154 self.base_url = Some(url.into());
155 self.retype(|p| p)
156 }
157
158 pub fn app_name(mut self, name: impl Into<String>) -> Self {
159 self.app_name = name.into();
160 self
161 }
162
163 pub fn base_path(mut self, path: impl Into<String>) -> Self {
165 self.base_path = path.into();
166 self
167 }
168
169 pub fn trusted_origins(mut self, origins: impl IntoIterator<Item = impl Into<String>>) -> Self {
171 self.trusted_origins.extend(
172 origins
173 .into_iter()
174 .map(|o| o.into().trim_end_matches('/').to_owned()),
175 );
176 self
177 }
178
179 pub fn email_password(mut self, config: EmailPassword) -> Self {
180 self.email_password = Some(config);
181 self
182 }
183
184 pub fn email_verification(mut self, config: EmailVerification) -> Self {
185 self.email_verification = config;
186 self
187 }
188
189 pub fn session(mut self, config: SessionConfig) -> Self {
190 self.session = config;
191 self
192 }
193
194 pub fn cookies(mut self, config: CookieConfig) -> Self {
195 self.cookies = config;
196 self
197 }
198
199 pub fn rate_limit(mut self, config: RateLimit) -> Self {
200 self.rate_limit = config;
201 self
202 }
203
204 pub fn client_ip(mut self, source: ClientIp) -> Self {
205 self.client_ip = source;
206 self
207 }
208
209 pub fn ids(mut self, strategy: IdStrategy) -> Self {
214 self.ids = strategy;
215 self
216 }
217
218 pub fn mailer(mut self, mailer: impl Mailer) -> Self {
219 self.mailer = Some(Arc::new(mailer));
220 self
221 }
222
223 pub fn allow_insecure_config(mut self, allow: bool) -> Self {
228 self.allow_insecure = allow;
229 self
230 }
231
232 pub fn user_fields<U2: Fields>(self) -> Builder<D, U2, P, S, B> {
234 self.retype(|p| p)
235 }
236
237 pub fn plugin<Pl: Plugin, I>(self, plugin: Pl) -> Builder<D, U, P::Out, S, B>
239 where
240 P: Append<Pl>,
241 Pl::Requires: Satisfied<P, I>,
242 {
243 self.retype(|plugins| plugins.append(Arc::new(plugin)))
244 }
245}
246
247impl<U, P, S, B> Builder<NoDatabase, U, P, S, B> {
248 pub fn database<D: Adapter>(self, db: D) -> Builder<D, U, P, S, B> {
249 Builder {
250 db,
251 plugins: self.plugins,
252 secrets: self.secrets,
253 base_url: self.base_url,
254 app_name: self.app_name,
255 base_path: self.base_path,
256 trusted_origins: self.trusted_origins,
257 session: self.session,
258 cookies: self.cookies,
259 email_password: self.email_password,
260 email_verification: self.email_verification,
261 rate_limit: self.rate_limit,
262 client_ip: self.client_ip,
263 ids: self.ids,
264 mailer: self.mailer,
265 allow_insecure: self.allow_insecure,
266 app_init: Vec::new(),
267 _state: PhantomData,
268 }
269 }
270}
271
272impl<D: Adapter, U, P, S, B> Builder<D, U, P, S, B> {
273 pub fn configure(
275 mut self,
276 init: impl FnOnce(&mut PluginBuilder<'_, D>) + Send + 'static,
277 ) -> Self {
278 self.app_init.push(Box::new(init));
279 self
280 }
281
282 pub fn on<Ev, F, Fut>(self, handler: F) -> Self
284 where
285 Ev: Event,
286 F: Fn(Ev, crate::endpoint::Ctx<D>) -> Fut + Send + Sync + 'static,
287 Fut: Future<Output = Result<(), AuthError>> + Send + 'static,
288 {
289 self.configure(move |app| {
290 app.on(handler);
291 })
292 }
293}
294
295impl<D: Adapter, U: Fields, P: PluginSet> Builder<D, U, P, Present, Present> {
296 pub fn build(self) -> Result<Auth<D, U, P>, BuildError> {
297 let mut problems = Vec::new();
298 if self.secrets.is_empty() || self.secrets.iter().any(|s| s.len() < Secret::MIN_LEN) {
299 problems.push(format!(
300 "every secret must be at least {} bytes; generate one with `fastauth secret`",
301 Secret::MIN_LEN
302 ));
303 }
304 let base_url = match Url::parse(self.base_url.as_deref().unwrap_or_default()) {
305 Ok(url) if matches!(url.scheme(), "http" | "https") => url,
306 _ => {
307 problems.push(format!(
308 "base_url `{}` is not an http(s) URL",
309 self.base_url.unwrap_or_default()
310 ));
311 Url::parse("http://localhost").expect("valid URL")
312 }
313 };
314 if !base_url.username().is_empty()
315 || base_url.password().is_some()
316 || base_url.query().is_some()
317 || base_url.fragment().is_some()
318 {
319 problems.push(format!(
320 "base_url `{base_url}` has credentials, a query or a fragment; emailed links are \
321 built from it, so give only the scheme, host, port and path"
322 ));
323 }
324 let local = is_local(&base_url);
325 let mut unsafe_in_production = Vec::new();
326 if let Some(bits) = self
327 .secrets
328 .iter()
329 .map(Secret::entropy_bits)
330 .min_by(f64::total_cmp)
331 .filter(|bits| *bits < Secret::MIN_ENTROPY_BITS)
332 {
333 unsafe_in_production.push(format!(
334 "a secret has about {bits:.0} bits of entropy, less than {:.0}; generate one with \
335 `fastauth secret`",
336 Secret::MIN_ENTROPY_BITS
337 ));
338 }
339 if base_url.scheme() == "http" && !local {
340 unsafe_in_production.push(format!(
341 "base_url `{base_url}` is http:// on a host other than localhost, so cookies \
342 would be sent without Secure; serve the app over https"
343 ));
344 }
345 if local || self.allow_insecure {
346 for problem in &unsafe_in_production {
347 tracing::warn!("fastauth: {problem} (allowed outside production)");
348 }
349 } else {
350 problems.extend(unsafe_in_production.into_iter().map(|problem| {
351 format!("{problem} (for local development: .allow_insecure_config(true))")
352 }));
353 }
354 let base_path = format!("/{}", self.base_path.trim_matches('/'));
355 if self
356 .email_password
357 .as_ref()
358 .is_some_and(|e| e.require_email_verification)
359 && self.mailer.is_none()
360 {
361 problems.push("require_email_verification needs a mailer: call .mailer(..)".into());
362 }
363 if matches!(self.client_ip, ClientIp::TrustedProxies { proxies: 0, .. }) {
364 problems.push("ClientIp::TrustedProxies needs at least one proxy".into());
365 }
366
367 let mut registry = Registry::<D>::new();
368 crate::models::register(&mut registry.schema);
369 routes::register(
370 &mut PluginBuilder {
371 registry: &mut registry,
372 },
373 self.email_password.is_some(),
374 );
375 registry.set_owner("app");
376 registry.schema.extend(User::TABLE, U::columns());
377 self.plugins.register(&mut registry);
378 registry.set_owner("app");
379 for init in self.app_init {
380 init(&mut PluginBuilder {
381 registry: &mut registry,
382 });
383 }
384
385 problems.append(&mut registry.errors);
386 for (type_id, name, owner) in ®istry.hook_targets {
387 if !registry.routes.iter().any(|r| r.type_id == *type_id)
388 && !registry.server_endpoints.contains(type_id)
389 {
390 problems.push(format!(
391 "`{owner}` hooks endpoint `{name}`, which no plugin registers"
392 ));
393 }
394 }
395
396 let mut by_path: BTreeMap<&'static str, Vec<_>> = BTreeMap::new();
397 for route in registry.routes {
398 by_path
399 .entry(route.path)
400 .or_default()
401 .push((route.method, route.endpoint));
402 }
403 let mut router = matchit::Router::new();
404 for (path, methods) in by_path {
405 if let Err(err) = router.insert(path, methods) {
406 problems.push(format!("route {path}: {err}"));
407 }
408 }
409
410 let schema = match registry.schema.finish(self.ids.storage()) {
411 Ok(schema) => schema,
412 Err(mut errors) => {
413 problems.append(&mut errors);
414 Schema::default()
415 }
416 };
417 if !problems.is_empty() {
418 return Err(BuildError { problems });
419 }
420
421 let mut rate_limit = self.rate_limit;
422 rate_limit.rules.extend(registry.rate_rules);
423 rate_limit.rules.extend(RateLimit::core_rules());
424
425 let secure_cookies = match self.cookies.secure {
426 Secure::Always => true,
427 Secure::Never => false,
428 Secure::Auto => base_url.scheme() == "https",
429 };
430 let hasher = self.email_password.as_ref().map_or_else(
431 || Arc::new(Argon2id::owasp()) as Arc<dyn crate::crypto::PasswordHasher>,
432 |e| e.hasher.clone(),
433 );
434 let cache_fingerprint =
435 session::fingerprint(schema.expect(Session::TABLE), schema.expect(User::TABLE));
436 let config = CoreConfig {
437 app_name: self.app_name,
438 base_url,
439 base_path,
440 trusted_origins: self.trusted_origins,
441 session: self.session,
442 cookies: self.cookies,
443 email_password: self.email_password,
444 email_verification: self.email_verification,
445 rate_limit: rate_limit.clone(),
446 client_ip: self.client_ip,
447 ids: self.ids,
448 secure_cookies,
449 };
450 let shared = Shared {
451 db: self.db,
452 schema,
453 keys: Keys::new(self.secrets),
454 config,
455 passwords: Passwords::new(hasher),
456 mailer: self.mailer,
457 plugins: registry.plugins,
458 hooks: registry.hooks,
459 gates: registry.gates,
460 resolvers: registry.resolvers,
461 response_hooks: registry.response_hooks,
462 session_hooks: registry.session_hooks,
463 session_gates: registry.session_gates,
464 fixed_expiry: registry.fixed_expiry,
465 claim_hooks: registry.claim_hooks,
466 user_input_hooks: registry.user_input_hooks,
467 events: registry.events,
468 router,
469 rate_limiter: RateLimiter::new(rate_limit, !local && !self.allow_insecure),
470 cache_fingerprint,
471 };
472 Ok(Auth {
473 shared: Arc::new(shared),
474 plugins: Arc::new(self.plugins),
475 _user: PhantomData,
476 })
477 }
478}
479
480fn is_local(url: &Url) -> bool {
482 match url.host() {
483 Some(url::Host::Domain(domain)) => domain == "localhost" || domain.ends_with(".localhost"),
484 Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
485 Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
486 None => false,
487 }
488}
489
490#[derive(Clone, Copy, Debug, PartialEq, Eq)]
492pub struct ClientAddr(pub IpAddr);
493
494pub struct Auth<D, U = (), P = Nil> {
499 shared: Arc<Shared<D>>,
500 plugins: Arc<P>,
501 _user: PhantomData<fn() -> U>,
502}
503
504impl<D, U, P> Clone for Auth<D, U, P> {
505 fn clone(&self) -> Self {
506 Self {
507 shared: self.shared.clone(),
508 plugins: self.plugins.clone(),
509 _user: PhantomData,
510 }
511 }
512}
513
514impl<D, U, P> std::fmt::Debug for Auth<D, U, P> {
515 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516 f.debug_struct("Auth")
517 .field("base_path", &self.shared.config.base_path)
518 .finish_non_exhaustive()
519 }
520}
521
522const MAX_BODY: usize = 64 * 1024;
523
524fn origin_of(value: &str) -> Option<String> {
525 Url::parse(value)
526 .ok()
527 .map(|u| u.origin().ascii_serialization())
528}
529
530impl<D: Adapter, U: Fields, P: PluginSet> Auth<D, U, P> {
531 pub fn config(&self) -> &CoreConfig {
532 &self.shared.config
533 }
534
535 pub fn schema(&self) -> &Schema {
536 &self.shared.schema
537 }
538
539 pub fn adapter(&self) -> &D {
540 &self.shared.db
541 }
542
543 pub fn migrator(&self) -> Migrator<'_, D> {
544 Migrator::new(&self.shared.db, &self.shared.schema)
545 }
546
547 pub fn plugin<Pl: Plugin, I>(&self) -> &Pl
549 where
550 P: Has<Pl, I>,
551 {
552 self.plugins.get()
553 }
554
555 pub fn api(&self) -> Api<'_, D> {
557 Api {
558 shared: &self.shared,
559 headers: HeaderMap::new(),
560 within: None,
561 }
562 }
563
564 pub async fn handle(&self, request: http::Request<Bytes>) -> Response {
566 let shared = &self.shared;
567 let config = &shared.config;
568 let (parts, body) = request.into_parts();
569 let Some(path) = parts.uri.path().strip_prefix(config.base_path.as_str()) else {
570 return AuthError::not_found().into_response();
571 };
572 let path = if path.is_empty() { "/" } else { path };
573 let Ok(matched) = shared.router.at(path) else {
574 return AuthError::not_found().into_response();
575 };
576 let Some((_, endpoint)) = matched.value.iter().find(|(m, _)| *m == parts.method) else {
577 return AuthError::new(
578 StatusCode::METHOD_NOT_ALLOWED,
579 codes::METHOD_NOT_ALLOWED,
580 "method not allowed",
581 )
582 .into_response();
583 };
584 if body.len() > MAX_BODY {
585 return AuthError::new(
586 StatusCode::PAYLOAD_TOO_LARGE,
587 codes::INVALID_BODY,
588 "request body is too large",
589 )
590 .into_response();
591 }
592
593 let client = config.client_ip.resolve(&parts);
594 let allowed = match client {
595 Some(client) => shared.rate_limiter.check(client, path, &body),
596 None => shared
597 .rate_limiter
598 .check_without_ip(&config.client_ip, path, &body),
599 };
600 let ip = client.map(|ip| ip.to_string());
601 if !allowed {
602 return AuthError::too_many_requests().into_response();
603 }
604
605 if !matches!(parts.method, Method::GET | Method::HEAD | Method::OPTIONS) {
606 let origin = header_str(&parts.headers, ORIGIN)
607 .filter(|o| o != "null")
608 .or_else(|| header_str(&parts.headers, REFERER).and_then(|r| origin_of(&r)));
609 let rejected = match &origin {
610 Some(origin) if !config.is_trusted_origin(origin) => {
611 Some((codes::INVALID_ORIGIN, "invalid origin"))
612 }
613 None if parts.headers.contains_key(COOKIE) => {
614 Some((codes::MISSING_OR_NULL_ORIGIN, "missing or null origin"))
615 }
616 _ => None,
617 };
618 if let Some((code, message)) = rejected {
619 return AuthError::new(StatusCode::FORBIDDEN, code, message).into_response();
620 }
621 }
622
623 let request = RequestInfo {
624 method: parts.method.clone(),
625 path: path.to_owned(),
626 params: matched
627 .params
628 .iter()
629 .map(|(k, v)| (k.to_owned(), v.to_owned()))
630 .collect(),
631 query: parts.uri.query().map(str::to_owned),
632 user_agent: header_str(&parts.headers, USER_AGENT),
633 headers: parts.headers,
634 ip,
635 };
636 let mut response = endpoint
637 .clone()
638 .handle(shared, Arc::new(request), body)
639 .await;
640 response
641 .headers_mut()
642 .entry(CACHE_CONTROL)
643 .or_insert(HeaderValue::from_static("no-store"));
644 response
645 }
646
647 pub async fn session_with_cookies(
650 &self,
651 headers: &HeaderMap,
652 ) -> (
653 Result<Option<SessionData<U, P>>, AuthError>,
654 Vec<HeaderValue>,
655 ) {
656 let request = Arc::new(RequestInfo::synthetic(
657 Method::GET,
658 "/get-session",
659 headers.clone(),
660 ));
661 let effects = Arc::new(Mutex::new(Effects::default()));
662 let result = session::resolve(&self.shared, None, &request, &effects)
663 .await
664 .and_then(|view| {
665 view.map(SessionData::from_view)
666 .transpose()
667 .map_err(AuthError::internal)
668 });
669 let cookies = effects
670 .lock()
671 .unwrap()
672 .cookies
673 .iter()
674 .filter_map(|c| HeaderValue::from_str(&c.to_header(&self.shared.config)).ok())
675 .collect();
676 (result, cookies)
677 }
678
679 pub async fn get_session(
681 &self,
682 headers: &HeaderMap,
683 ) -> Result<Option<SessionData<U, P>>, AuthError> {
684 self.session_with_cookies(headers).await.0
685 }
686
687 pub async fn get_session_by_token(
689 &self,
690 token: &str,
691 ) -> Result<Option<SessionData<U, P>>, AuthError> {
692 let view = session::by_token(&self.shared, &self.shared.db, token).await?;
693 view.map(SessionData::from_view)
694 .transpose()
695 .map_err(AuthError::internal)
696 }
697}
698
699pub trait AuthInstance: Clone + Send + Sync + 'static {
702 type Db: Adapter;
703 type UserFields: Fields;
704 type Plugins: PluginSet;
705
706 fn config(&self) -> &CoreConfig;
707 fn api(&self) -> Api<'_, Self::Db>;
708 fn try_plugin<P: Plugin>(&self) -> Option<&P>;
712 fn handle(&self, request: http::Request<Bytes>) -> impl Future<Output = Response> + Send;
713 #[allow(clippy::type_complexity)]
714 fn session_with_cookies(
715 &self,
716 headers: &HeaderMap,
717 ) -> impl Future<
718 Output = (
719 Result<Option<SessionData<Self::UserFields, Self::Plugins>>, AuthError>,
720 Vec<HeaderValue>,
721 ),
722 > + Send;
723}
724
725impl<D: Adapter, U: Fields, P: PluginSet> AuthInstance for Auth<D, U, P> {
726 type Db = D;
727 type UserFields = U;
728 type Plugins = P;
729
730 fn config(&self) -> &CoreConfig {
731 Auth::config(self)
732 }
733
734 fn api(&self) -> Api<'_, D> {
735 Auth::api(self)
736 }
737
738 fn try_plugin<Pl: Plugin>(&self) -> Option<&Pl> {
739 self.shared
740 .plugins
741 .get(&std::any::TypeId::of::<Pl>())
742 .and_then(|plugin| plugin.downcast_ref::<Pl>())
743 }
744
745 fn handle(&self, request: http::Request<Bytes>) -> impl Future<Output = Response> + Send {
746 Auth::handle(self, request)
747 }
748
749 fn session_with_cookies(
750 &self,
751 headers: &HeaderMap,
752 ) -> impl Future<
753 Output = (
754 Result<Option<SessionData<U, P>>, AuthError>,
755 Vec<HeaderValue>,
756 ),
757 > + Send {
758 Auth::session_with_cookies(self, headers)
759 }
760}
761
762#[diagnostic::on_unimplemented(
763 message = "plugin `{Pl}` is not registered on this auth instance",
764 note = "register it with `.plugin(...)` on the builder and list it in your `plugins![..]` alias"
765)]
766pub trait HasPlugin<Pl, I>: AuthInstance {
769 fn plugin_arc(&self) -> &Arc<Pl>;
770}
771
772impl<D: Adapter, U: Fields, P: Has<Pl, I>, Pl: Plugin, I> HasPlugin<Pl, I> for Auth<D, U, P> {
773 fn plugin_arc(&self) -> &Arc<Pl> {
774 self.plugins.get()
775 }
776}
777
778pub struct Api<'a, D> {
781 shared: &'a Arc<Shared<D>>,
782 headers: HeaderMap,
783 within: Option<(Arc<D>, DeferredEvents)>,
784}
785
786impl<D> std::fmt::Debug for Api<'_, D> {
787 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
788 f.write_str("Api")
789 }
790}
791
792#[derive(Debug)]
794pub struct ApiResponse<T> {
795 pub data: T,
796 pub set_cookies: Vec<HeaderValue>,
797}
798
799impl<T: Serialize> ApiResponse<T> {
800 pub fn into_http(self) -> Response {
802 let body = serde_json::to_vec(&self.data).unwrap_or_default();
803 let mut response = Response::new(Bytes::from(body));
804 response.headers_mut().insert(
805 http::header::CONTENT_TYPE,
806 HeaderValue::from_static("application/json"),
807 );
808 for cookie in self.set_cookies {
809 response
810 .headers_mut()
811 .append(http::header::SET_COOKIE, cookie);
812 }
813 response
814 }
815}
816
817#[cfg(feature = "axum")]
820impl<T: Serialize> axum_core::response::IntoResponse for ApiResponse<T> {
821 fn into_response(self) -> axum_core::response::Response {
822 self.into_http().map(axum_core::body::Body::from)
823 }
824}
825
826#[cfg(feature = "actix")]
829impl<T: Serialize> actix_web::Responder for ApiResponse<T> {
830 type Body = actix_web::body::BoxBody;
831
832 fn respond_to(self, _: &actix_web::HttpRequest) -> actix_web::HttpResponse {
833 crate::error::to_actix(self.into_http())
834 }
835}
836
837impl<D: Adapter> Api<'_, D> {
838 pub fn adapter(&self) -> &D {
840 &self.shared.db
841 }
842
843 pub fn db(&self) -> Db<'_, D> {
846 Db::new(&self.shared.db, &self.shared.schema)
847 }
848
849 pub fn within(mut self, db: D, events: &DeferredEvents) -> Self {
859 self.within = Some((Arc::new(db), events.clone()));
860 self
861 }
862
863 pub fn headers(mut self, headers: &HeaderMap) -> Self {
865 self.headers = headers.clone();
866 self
867 }
868
869 pub fn session_token(mut self, token: &str) -> Self {
871 let name = self.shared.config.cookie_name(session::SESSION_TOKEN);
872 let signed = self.shared.keys.sign(SignPurpose::Cookie, token);
873 if let Ok(value) = HeaderValue::from_str(&format!("{name}={signed}")) {
874 self.headers.insert(COOKIE, value);
875 }
876 self
877 }
878
879 pub async fn call<E: Endpoint<D>>(
881 &self,
882 endpoint: &E,
883 input: E::Input,
884 ) -> Result<ApiResponse<E::Output>, AuthError> {
885 let request = Arc::new(RequestInfo::synthetic(
886 E::METHOD,
887 E::PATH,
888 self.headers.clone(),
889 ));
890 let Some((db, events)) = &self.within else {
891 let mut executed = execute(self.shared, None, endpoint, request, input).await;
892 if executed.result.is_ok() {
893 let pending = std::mem::take(&mut executed.effects.events);
894 dispatch_events(self.shared, pending).await;
895 }
896 return self.respond(executed);
897 };
898 let savepoint = db.begin().await?;
899 let mut executed = execute(self.shared, Some(db.clone()), endpoint, request, input).await;
900 if !matches!(executed.result, Ok(Outcome::Output(_))) {
901 savepoint.rollback().await?;
902 return self.respond(executed);
903 }
904 savepoint.commit().await?;
905 let pending = std::mem::take(&mut executed.effects.events);
906 let shared = self.shared.clone();
907 events.push(Box::new(move || {
908 Box::pin(async move { dispatch_events(&shared, pending).await })
909 }));
910 self.respond(executed)
911 }
912
913 fn respond<O>(&self, executed: Executed<O>) -> Result<ApiResponse<O>, AuthError> {
914 let set_cookies = executed
915 .effects
916 .cookies
917 .iter()
918 .filter_map(|c| HeaderValue::from_str(&c.to_header(&self.shared.config)).ok())
919 .collect();
920 match executed.result? {
921 Outcome::Output(data) => Ok(ApiResponse { data, set_cookies }),
922 Outcome::Response(response) => Err(AuthError::with_message(
923 response.status(),
924 "HOOK_RESPONDED",
925 String::from_utf8_lossy(response.body()).into_owned(),
926 )),
927 }
928 }
929
930 pub async fn create_user(&self, input: routes::CreateUserInput) -> Result<UserView, AuthError> {
934 Ok(self.call(&routes::CreateUser, input).await?.data)
935 }
936
937 pub async fn sign_up_email(
938 &self,
939 input: routes::SignUpEmailInput,
940 ) -> Result<ApiResponse<routes::SignUpOutput>, AuthError> {
941 self.call(&routes::SignUpEmail, input).await
942 }
943
944 pub async fn sign_in_email(
945 &self,
946 input: routes::SignInEmailInput,
947 ) -> Result<ApiResponse<routes::SignInOutput>, AuthError> {
948 self.call(&routes::SignInEmail, input).await
949 }
950
951 pub async fn sign_out(&self) -> Result<ApiResponse<routes::SignOutOutput>, AuthError> {
952 self.call(&routes::SignOut, crate::endpoint::Empty {}).await
953 }
954
955 pub async fn list_sessions(
956 &self,
957 ) -> Result<ApiResponse<Vec<serde_json::Map<String, serde_json::Value>>>, AuthError> {
958 self.call(&routes::ListSessions, serde_json::Map::new())
959 .await
960 }
961
962 pub async fn revoke_other_sessions(&self) -> Result<ApiResponse<routes::Status>, AuthError> {
963 self.call(&routes::RevokeOtherSessions, crate::endpoint::Empty {})
964 .await
965 }
966
967 pub async fn change_password(
968 &self,
969 input: routes::ChangePasswordInput,
970 ) -> Result<ApiResponse<routes::ChangePasswordOutput>, AuthError> {
971 self.call(&routes::ChangePassword, input).await
972 }
973
974 pub async fn request_password_reset(
975 &self,
976 input: routes::RequestPasswordResetInput,
977 ) -> Result<ApiResponse<routes::RequestPasswordResetOutput>, AuthError> {
978 self.call(&routes::RequestPasswordReset, input).await
979 }
980
981 pub async fn reset_password(
982 &self,
983 input: routes::ResetPasswordInput,
984 ) -> Result<ApiResponse<routes::Status>, AuthError> {
985 self.call(&routes::ResetPassword, input).await
986 }
987}