Skip to main content

reinhardt_testkit/auth/
traits.rs

1/// Trait for extracting session-storable identity from any user type.
2///
3/// Blanket-implemented for all `AuthIdentity` types (generated by the `#[user]` macro).
4/// Users with custom user types that don't use `#[user]` can implement this trait directly.
5pub trait ForceLoginUser: Send + Sync {
6	/// The user ID to store as `"user_id"` in session data.
7	fn session_user_id(&self) -> String;
8
9	/// Whether the user has staff privileges. Defaults to `false`.
10	///
11	/// Override via the builder's `.with_staff(true)` if your user type
12	/// implements `FullUser` but this blanket impl returns `false`.
13	fn session_is_staff(&self) -> bool {
14		false
15	}
16
17	/// Whether the user has superuser privileges. Defaults to `false`.
18	fn session_is_superuser(&self) -> bool {
19		false
20	}
21}
22
23#[cfg(native)]
24impl<T: reinhardt_auth::AuthIdentity> ForceLoginUser for T {
25	fn session_user_id(&self) -> String {
26		self.id()
27	}
28
29	fn session_is_superuser(&self) -> bool {
30		self.is_admin()
31	}
32}
33
34#[cfg(test)]
35mod tests {
36	use super::*;
37	use rstest::*;
38
39	struct StubUser {
40		id: String,
41		staff: bool,
42		superuser: bool,
43	}
44
45	impl ForceLoginUser for StubUser {
46		fn session_user_id(&self) -> String {
47			self.id.clone()
48		}
49		fn session_is_staff(&self) -> bool {
50			self.staff
51		}
52		fn session_is_superuser(&self) -> bool {
53			self.superuser
54		}
55	}
56
57	#[rstest]
58	fn extracts_user_id() {
59		let user = StubUser {
60			id: "user-42".into(),
61			staff: false,
62			superuser: false,
63		};
64		assert_eq!(user.session_user_id(), "user-42");
65	}
66
67	#[rstest]
68	fn defaults_staff_to_false() {
69		let user = StubUser {
70			id: "u1".into(),
71			staff: false,
72			superuser: false,
73		};
74		assert!(!user.session_is_staff());
75	}
76
77	#[rstest]
78	fn respects_explicit_staff() {
79		let user = StubUser {
80			id: "u1".into(),
81			staff: true,
82			superuser: false,
83		};
84		assert!(user.session_is_staff());
85	}
86
87	#[rstest]
88	fn respects_explicit_superuser() {
89		let user = StubUser {
90			id: "u1".into(),
91			staff: false,
92			superuser: true,
93		};
94		assert!(user.session_is_superuser());
95	}
96}