Skip to main content

reinhardt_testkit/auth/
server_fn_builder.rs

1use super::identity::SessionIdentity;
2use super::traits::ForceLoginUser;
3use crate::server_fn::MockSession;
4use crate::server_fn::ServerFnTestContext;
5
6/// Builder for auth configuration in server_fn test contexts.
7///
8/// Mirrors the [`crate::client::APIClient`] auth builder API for primary auth.
9/// Uses [`MockSession`] instead of a real `AsyncSessionBackend`.
10///
11/// Secondary auth layers (MFA, etc.) are not supported in server_fn contexts
12/// because `MockSession` does not process HTTP headers. Use
13/// [`crate::auth::SessionAuthBuilder`] with an `APIClient` for MFA testing.
14pub struct ServerFnAuthBuilder {
15	ctx: ServerFnTestContext,
16	identity: Option<SessionIdentity>,
17}
18
19impl ServerFnAuthBuilder {
20	pub(crate) fn new(ctx: ServerFnTestContext) -> Self {
21		Self {
22			ctx,
23			identity: None,
24		}
25	}
26
27	/// Authenticate as the given user via session.
28	///
29	/// No `AsyncSessionBackend` is required — uses [`MockSession`] internally.
30	pub fn session(mut self, user: &impl ForceLoginUser) -> Self {
31		self.identity = Some(SessionIdentity::from_user(user));
32		self
33	}
34
35	/// Authenticate via JWT (sets identity for mock session).
36	#[cfg(native)]
37	pub fn jwt(
38		mut self,
39		user: &impl ForceLoginUser,
40		_config: &super::builder::JwtTestConfig,
41	) -> Self {
42		self.identity = Some(SessionIdentity::from_user(user));
43		self
44	}
45
46	/// Override the `is_staff` flag.
47	pub fn with_staff(mut self, is_staff: bool) -> Self {
48		if let Some(ref mut id) = self.identity {
49			id.is_staff = is_staff;
50		}
51		self
52	}
53
54	/// Override the `is_superuser` flag.
55	pub fn with_superuser(mut self, is_superuser: bool) -> Self {
56		if let Some(ref mut id) = self.identity {
57			id.is_superuser = is_superuser;
58		}
59		self
60	}
61
62	/// Finalize auth configuration and return the configured [`ServerFnTestContext`].
63	///
64	/// Call `.build()` or `.build_context()` on the result to get the test environment.
65	pub fn done(mut self) -> ServerFnTestContext {
66		if let Some(identity) = &self.identity {
67			let mock_session = MockSession::from_identity(identity);
68			self.ctx = self.ctx.with_session(mock_session);
69		}
70		self.ctx
71	}
72}