1use std::any::{Any, TypeId};
4use std::collections::HashMap;
5
6use serde::de::DeserializeOwned;
7
8use crate::auth::Auth;
9use crate::config::Config;
10use crate::container::Container;
11use crate::error::{Error, Result};
12use crate::http::{Request, Response};
13use crate::session::Session;
14
15#[derive(Debug, Default, Clone)]
17pub struct Params(HashMap<String, String>);
18
19impl Params {
20 pub(crate) fn new(inner: HashMap<String, String>) -> Self {
21 Self(inner)
22 }
23
24 pub fn raw(&self, key: &str) -> Option<&str> {
25 self.0.get(key).map(String::as_str)
26 }
27
28 pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<T> {
31 let raw = self
32 .raw(key)
33 .ok_or_else(|| Error::BadRequest(format!("route parameter `{key}` is missing")))?;
34
35 crate::http::decode_param(key, raw)
36 }
37
38 pub fn try_get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>> {
39 match self.raw(key) {
40 Some(raw) => crate::http::decode_param(key, raw).map(Some),
41 None => Ok(None),
42 }
43 }
44}
45
46#[derive(Default)]
53pub struct Extensions(HashMap<TypeId, Box<dyn Any + Send + Sync>>);
54
55impl Extensions {
56 pub fn new() -> Self {
57 Self::default()
58 }
59
60 pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<T> {
62 self.0
63 .insert(TypeId::of::<T>(), Box::new(value))
64 .and_then(|previous| previous.downcast().ok().map(|boxed| *boxed))
65 }
66
67 pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
68 self.0
69 .get(&TypeId::of::<T>())
70 .and_then(|value| value.downcast_ref())
71 }
72
73 pub fn get_mut<T: Any + Send + Sync>(&mut self) -> Option<&mut T> {
74 self.0
75 .get_mut(&TypeId::of::<T>())
76 .and_then(|value| value.downcast_mut())
77 }
78
79 pub fn take<T: Any + Send + Sync>(&mut self) -> Option<T> {
80 self.0
81 .remove(&TypeId::of::<T>())
82 .and_then(|value| value.downcast().ok().map(|boxed| *boxed))
83 }
84
85 pub fn contains<T: Any + Send + Sync>(&self) -> bool {
86 self.0.contains_key(&TypeId::of::<T>())
87 }
88
89 pub fn len(&self) -> usize {
90 self.0.len()
91 }
92
93 pub fn is_empty(&self) -> bool {
94 self.0.is_empty()
95 }
96}
97
98impl std::fmt::Debug for Extensions {
99 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100 f.debug_struct("Extensions")
101 .field("entries", &self.0.len())
102 .finish()
103 }
104}
105
106#[non_exhaustive]
112#[derive(Debug)]
113pub struct HttpContext {
114 pub request: Request,
115 pub response: Response,
116 pub params: Params,
117 pub extensions: Extensions,
118 pub services: Container,
120 pub auth: Auth,
122 pub config: Config,
124 pub session: Session,
126 pub inertia: crate::inertia::InertiaRequest,
128}
129
130impl HttpContext {
131 pub fn authorize<T>(&self, policy: impl FnOnce(&Auth, &T) -> bool, subject: &T) -> Result<()> {
145 if policy(&self.auth, subject) {
146 return Ok(());
147 }
148
149 Err(Error::Forbidden)
150 }
151
152 pub fn can<T>(&self, policy: impl FnOnce(&Auth, &T) -> bool, subject: &T) -> bool {
154 policy(&self.auth, subject)
155 }
156
157 pub(crate) fn new(
158 request: Request,
159 params: Params,
160 services: Container,
161 config: Config,
162 ) -> Self {
163 Self {
164 request,
165 response: Response::default(),
166 params,
167 extensions: Extensions::new(),
168 services,
169 auth: Auth::default(),
170 config,
171 session: Session::detached(),
172 inertia: crate::inertia::InertiaRequest::default(),
173 }
174 }
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 #[derive(Debug, PartialEq)]
182 struct CurrentUser(i64);
183
184 #[derive(Debug, PartialEq)]
185 struct RequestId(String);
186
187 #[test]
188 fn stores_and_reads_values_by_type() {
189 let mut extensions = Extensions::new();
190 extensions.insert(CurrentUser(7));
191 extensions.insert(RequestId("abc".into()));
192
193 assert_eq!(extensions.get::<CurrentUser>(), Some(&CurrentUser(7)));
194 assert_eq!(
195 extensions.get::<RequestId>(),
196 Some(&RequestId("abc".into()))
197 );
198 assert_eq!(extensions.len(), 2);
199 }
200
201 #[test]
202 fn inserting_the_same_type_returns_the_previous_value() {
203 let mut extensions = Extensions::new();
204 assert_eq!(extensions.insert(CurrentUser(1)), None);
205 assert_eq!(extensions.insert(CurrentUser(2)), Some(CurrentUser(1)));
206 assert_eq!(extensions.get::<CurrentUser>(), Some(&CurrentUser(2)));
207 }
208
209 #[test]
210 fn missing_types_read_as_none() {
211 let extensions = Extensions::new();
212 assert_eq!(extensions.get::<CurrentUser>(), None);
213 assert!(!extensions.contains::<CurrentUser>());
214 assert!(extensions.is_empty());
215 }
216
217 #[test]
218 fn take_removes_the_value() {
219 let mut extensions = Extensions::new();
220 extensions.insert(CurrentUser(9));
221
222 assert_eq!(extensions.take::<CurrentUser>(), Some(CurrentUser(9)));
223 assert_eq!(extensions.take::<CurrentUser>(), None);
224 assert!(extensions.is_empty());
225 }
226}