1use std::collections::BTreeMap;
14use std::net::SocketAddr;
15use std::sync::atomic::{AtomicU16, Ordering};
16use std::sync::{Arc, Mutex};
17
18use http::{HeaderMap, Method, Uri};
19use next_rust_core::Config;
20use next_rust_router::Params;
21use serde::de::DeserializeOwned;
22
23use crate::cookies::Cookies;
24use crate::error::{Error, ErrorKind, Result, not_found};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum RenderMode {
29 Request,
30 Static,
31}
32
33pub struct RequestContext {
35 pub method: Method,
36 pub uri: Uri,
37 pub headers: HeaderMap,
38 pub params: Params,
39 pub cookies: Cookies,
40 pub extensions: http::Extensions,
41 pub remote_addr: Option<SocketAddr>,
42 pub nonce: String,
44 pub mode: RenderMode,
45 pub dev: bool,
47 pub config: Arc<Config>,
48 pub(crate) status: AtomicU16,
49 pub(crate) response_headers: Mutex<HeaderMap>,
50}
51
52pub type Ctx = Arc<RequestContext>;
54
55impl RequestContext {
56 pub fn path(&self) -> &str {
57 self.uri.path()
58 }
59
60 pub fn is_static(&self) -> bool {
61 self.mode == RenderMode::Static
62 }
63
64 pub fn set_status(&self, code: u16) {
66 self.status.store(code, Ordering::Relaxed);
67 }
68
69 pub fn status(&self) -> u16 {
70 self.status.load(Ordering::Relaxed)
71 }
72
73 pub(crate) fn raise_status(&self, code: u16) {
74 let _ = self.status.compare_exchange(200, code, Ordering::Relaxed, Ordering::Relaxed);
76 }
77
78 fn require_request(&self, what: &'static str) -> Result<()> {
79 if self.is_static() { Err(Error::new(ErrorKind::DynamicUsage(what))) } else { Ok(()) }
80 }
81
82 pub fn for_static(path: &str, params: Params, config: Arc<Config>) -> Ctx {
84 Self::for_static_with(path, params, config, crate::is_dev())
85 }
86
87 pub(crate) fn for_static_with(path: &str, params: Params, config: Arc<Config>, dev: bool) -> Ctx {
88 Arc::new(RequestContext {
89 method: Method::GET,
90 uri: path.parse().unwrap_or_else(|_| Uri::from_static("/")),
91 headers: HeaderMap::new(),
92 params,
93 cookies: Cookies::default(),
94 extensions: http::Extensions::new(),
95 remote_addr: None,
96 nonce: crate::random_hex(16),
97 mode: RenderMode::Static,
98 dev,
99 config,
100 status: AtomicU16::new(200),
101 response_headers: Mutex::new(HeaderMap::new()),
102 })
103 }
104
105 pub(crate) fn from_request(req: &crate::Request, config: Arc<Config>, nonce: String, dev: bool) -> Ctx {
106 Arc::new(RequestContext {
107 method: req.method().clone(),
108 uri: req.uri().clone(),
109 headers: req.headers().clone(),
110 params: req.params().clone(),
111 cookies: req.cookies().clone(),
112 extensions: req.extensions().clone(),
113 remote_addr: req.remote_addr(),
114 nonce,
115 mode: RenderMode::Request,
116 dev,
117 config,
118 status: AtomicU16::new(200),
119 response_headers: Mutex::new(HeaderMap::new()),
120 })
121 }
122}
123
124pub trait FromContext: Sized {
126 fn from_context(ctx: &Ctx) -> Result<Self>;
127}
128
129impl FromContext for Ctx {
130 fn from_context(ctx: &Ctx) -> Result<Self> {
131 Ok(ctx.clone())
132 }
133}
134
135impl FromContext for Params {
136 fn from_context(ctx: &Ctx) -> Result<Self> {
137 Ok(ctx.params.clone())
138 }
139}
140
141#[derive(Debug, Clone)]
144pub struct Path<T>(pub T);
145
146impl<T: DeserializeOwned> FromContext for Path<T> {
147 fn from_context(ctx: &Ctx) -> Result<Self> {
148 crate::params_de::from_params(&ctx.params).map(Path).map_err(|_| not_found())
149 }
150}
151
152#[derive(Debug, Clone)]
154pub struct Query<T = QueryMap>(pub T);
155
156#[derive(Debug, Clone, Default, PartialEq, Eq)]
158pub struct QueryMap(pub Vec<(String, String)>);
159
160impl QueryMap {
161 pub fn get(&self, name: &str) -> Option<&str> {
162 self.0.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
163 }
164
165 pub fn get_all(&self, name: &str) -> Vec<&str> {
166 self.0.iter().filter(|(k, _)| k == name).map(|(_, v)| v.as_str()).collect()
167 }
168}
169
170impl<'de> serde::Deserialize<'de> for QueryMap {
171 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
172 Vec::<(String, String)>::deserialize(d).map(QueryMap)
173 }
174}
175
176impl<T: DeserializeOwned> FromContext for Query<T> {
177 fn from_context(ctx: &Ctx) -> Result<Self> {
178 ctx.require_request("Query")?;
179 serde_urlencoded::from_str(ctx.uri.query().unwrap_or(""))
180 .map(Query)
181 .map_err(|e| Error::http(400, format!("invalid query string: {e}")))
182 }
183}
184
185impl FromContext for Cookies {
186 fn from_context(ctx: &Ctx) -> Result<Self> {
187 ctx.require_request("Cookies")?;
188 Ok(ctx.cookies.clone())
189 }
190}
191
192#[derive(Debug, Clone)]
194pub struct Headers(pub HeaderMap);
195
196impl Headers {
197 pub fn get(&self, name: &str) -> Option<&str> {
198 self.0.get(name).and_then(|v| v.to_str().ok())
199 }
200}
201
202impl FromContext for Headers {
203 fn from_context(ctx: &Ctx) -> Result<Self> {
204 ctx.require_request("Headers")?;
205 Ok(Headers(ctx.headers.clone()))
206 }
207}
208
209#[derive(Debug, Clone)]
211pub struct RequestInfo {
212 pub method: Method,
213 pub uri: Uri,
214 pub remote_addr: Option<SocketAddr>,
215}
216
217impl FromContext for RequestInfo {
218 fn from_context(ctx: &Ctx) -> Result<Self> {
219 ctx.require_request("RequestInfo")?;
220 Ok(RequestInfo { method: ctx.method.clone(), uri: ctx.uri.clone(), remote_addr: ctx.remote_addr })
221 }
222}
223
224#[derive(Debug, Clone)]
229pub struct Extension<T>(pub T);
230
231impl<T: Clone + Send + Sync + 'static> FromContext for Extension<T> {
232 fn from_context(ctx: &Ctx) -> Result<Self> {
233 ctx.require_request("Extension")?;
234 ctx.extensions.get::<T>().cloned().map(Extension).ok_or_else(|| {
235 Error::msg(format!(
236 "Extension<{}> is not set; insert it in middleware with `req.insert_extension(..)`",
237 std::any::type_name::<T>()
238 ))
239 })
240 }
241}
242
243impl<T: Clone + Send + Sync + 'static> FromContext for Option<Extension<T>> {
244 fn from_context(ctx: &Ctx) -> Result<Self> {
245 ctx.require_request("Extension")?;
246 Ok(ctx.extensions.get::<T>().cloned().map(Extension))
247 }
248}
249
250#[derive(Debug, Clone)]
253pub struct Auth<T>(pub Option<T>);
254
255impl<T> Auth<T> {
256 pub fn user(&self) -> Option<&T> {
257 self.0.as_ref()
258 }
259
260 pub fn is_authenticated(&self) -> bool {
261 self.0.is_some()
262 }
263
264 pub fn require(self, login: &str) -> Result<T> {
266 self.0.ok_or_else(|| crate::error::redirect(login))
267 }
268}
269
270#[derive(Debug, Clone)]
272pub struct AuthUser<T>(pub T);
273
274impl<T: Clone + Send + Sync + 'static> FromContext for Auth<T> {
275 fn from_context(ctx: &Ctx) -> Result<Self> {
276 ctx.require_request("Auth")?;
277 Ok(Auth(ctx.extensions.get::<AuthUser<T>>().map(|u| u.0.clone())))
278 }
279}
280
281#[derive(Debug, Clone)]
283pub struct Nonce(pub String);
284
285impl FromContext for Nonce {
286 fn from_context(ctx: &Ctx) -> Result<Self> {
287 Ok(Nonce(ctx.nonce.clone()))
288 }
289}
290
291#[derive(Clone)]
293pub struct ResponseHeaders(Ctx);
294
295impl ResponseHeaders {
296 pub fn set(&self, name: &str, value: &str) {
297 if let (Ok(n), Ok(v)) = (http::HeaderName::from_bytes(name.as_bytes()), http::HeaderValue::from_str(value)) {
298 self.0.response_headers.lock().unwrap_or_else(|e| e.into_inner()).insert(n, v);
299 }
300 }
301}
302
303impl FromContext for ResponseHeaders {
304 fn from_context(ctx: &Ctx) -> Result<Self> {
305 ctx.require_request("ResponseHeaders")?;
306 Ok(ResponseHeaders(ctx.clone()))
307 }
308}
309
310#[derive(Debug, Clone)]
312pub struct Data<T>(pub T);
313
314#[derive(Debug, Clone, PartialEq, Eq)]
316pub struct CsrfToken(pub String);
317
318impl CsrfToken {
319 pub fn field(&self) -> next_rust_view::Element {
321 next_rust_view::Element::new_void("input")
322 .with(next_rust_view::attrs::type_("hidden"))
323 .with(next_rust_view::attrs::name("_csrf"))
324 .with(next_rust_view::attrs::value(self.0.clone()))
325 }
326}
327
328impl FromContext for CsrfToken {
329 fn from_context(ctx: &Ctx) -> Result<Self> {
330 ctx.require_request("CsrfToken")?;
331 Ok(ctx
332 .extensions
333 .get::<CsrfToken>()
334 .cloned()
335 .or_else(|| ctx.cookies.get(crate::CSRF_COOKIE).map(CsrfToken))
336 .unwrap_or_else(|| {
337 let t = crate::random_hex(32);
338 ctx.cookies.set(crate::Cookie::new(crate::CSRF_COOKIE, t.clone()).http_only(false));
339 CsrfToken(t)
340 }))
341 }
342}
343
344#[derive(Debug, Clone, Default, PartialEq, Eq)]
347pub struct FormState {
348 pub errors: BTreeMap<String, String>,
349 pub message: Option<String>,
350 pub values: BTreeMap<String, String>,
351}
352
353impl FormState {
354 pub fn error(&self, field: &str) -> Option<&str> {
355 self.errors.get(field).map(String::as_str)
356 }
357
358 pub fn value(&self, field: &str) -> &str {
359 self.values.get(field).map(String::as_str).unwrap_or("")
360 }
361
362 pub fn has_errors(&self) -> bool {
363 !self.errors.is_empty() || self.message.is_some()
364 }
365}
366
367impl FromContext for FormState {
368 fn from_context(ctx: &Ctx) -> Result<Self> {
369 ctx.require_request("FormState")?;
370 let Some(raw) = ctx.cookies.get_decoded(crate::actions::FLASH_COOKIE) else { return Ok(FormState::default()) };
371 ctx.cookies.delete(crate::actions::FLASH_COOKIE);
372 Ok(crate::actions::decode_flash(&raw))
373 }
374}