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, Copy, PartialEq, Eq)]
217pub struct ClientIp(pub Option<std::net::IpAddr>);
218
219impl FromContext for ClientIp {
220 fn from_context(ctx: &Ctx) -> Result<Self> {
221 ctx.require_request("ClientIp")?;
222 Ok(ClientIp(crate::request::client_ip_from(&ctx.headers, ctx.remote_addr, crate::trust_proxy())))
223 }
224}
225
226#[derive(Debug, Clone)]
228pub struct RequestInfo {
229 pub method: Method,
230 pub uri: Uri,
231 pub remote_addr: Option<SocketAddr>,
232}
233
234impl FromContext for RequestInfo {
235 fn from_context(ctx: &Ctx) -> Result<Self> {
236 ctx.require_request("RequestInfo")?;
237 Ok(RequestInfo { method: ctx.method.clone(), uri: ctx.uri.clone(), remote_addr: ctx.remote_addr })
238 }
239}
240
241#[derive(Debug, Clone)]
246pub struct Extension<T>(pub T);
247
248impl<T: Clone + Send + Sync + 'static> FromContext for Extension<T> {
249 fn from_context(ctx: &Ctx) -> Result<Self> {
250 ctx.require_request("Extension")?;
251 ctx.extensions.get::<T>().cloned().map(Extension).ok_or_else(|| {
252 Error::msg(format!(
253 "Extension<{}> is not set; insert it in middleware with `req.insert_extension(..)`",
254 std::any::type_name::<T>()
255 ))
256 })
257 }
258}
259
260impl<T: Clone + Send + Sync + 'static> FromContext for Option<Extension<T>> {
261 fn from_context(ctx: &Ctx) -> Result<Self> {
262 ctx.require_request("Extension")?;
263 Ok(ctx.extensions.get::<T>().cloned().map(Extension))
264 }
265}
266
267#[derive(Debug, Clone)]
270pub struct Auth<T>(pub Option<T>);
271
272impl<T> Auth<T> {
273 pub fn user(&self) -> Option<&T> {
274 self.0.as_ref()
275 }
276
277 pub fn is_authenticated(&self) -> bool {
278 self.0.is_some()
279 }
280
281 pub fn require(self, login: &str) -> Result<T> {
283 self.0.ok_or_else(|| crate::error::redirect(login))
284 }
285}
286
287#[derive(Debug, Clone)]
289pub struct AuthUser<T>(pub T);
290
291impl<T: Clone + Send + Sync + 'static> FromContext for Auth<T> {
292 fn from_context(ctx: &Ctx) -> Result<Self> {
293 ctx.require_request("Auth")?;
294 Ok(Auth(ctx.extensions.get::<AuthUser<T>>().map(|u| u.0.clone())))
295 }
296}
297
298#[derive(Debug, Clone)]
300pub struct Nonce(pub String);
301
302impl FromContext for Nonce {
303 fn from_context(ctx: &Ctx) -> Result<Self> {
304 Ok(Nonce(ctx.nonce.clone()))
305 }
306}
307
308#[derive(Clone)]
310pub struct ResponseHeaders(Ctx);
311
312impl ResponseHeaders {
313 pub fn set(&self, name: &str, value: &str) {
314 if let (Ok(n), Ok(v)) = (http::HeaderName::from_bytes(name.as_bytes()), http::HeaderValue::from_str(value)) {
315 self.0.response_headers.lock().unwrap_or_else(|e| e.into_inner()).insert(n, v);
316 }
317 }
318}
319
320impl FromContext for ResponseHeaders {
321 fn from_context(ctx: &Ctx) -> Result<Self> {
322 ctx.require_request("ResponseHeaders")?;
323 Ok(ResponseHeaders(ctx.clone()))
324 }
325}
326
327#[derive(Debug, Clone)]
329pub struct Data<T>(pub T);
330
331#[derive(Debug, Clone, PartialEq, Eq)]
333pub struct CsrfToken(pub String);
334
335impl CsrfToken {
336 pub fn field(&self) -> next_rust_view::Element {
338 next_rust_view::Element::new_void("input")
339 .with(next_rust_view::attrs::type_("hidden"))
340 .with(next_rust_view::attrs::name("_csrf"))
341 .with(next_rust_view::attrs::value(self.0.clone()))
342 }
343}
344
345impl FromContext for CsrfToken {
346 fn from_context(ctx: &Ctx) -> Result<Self> {
347 ctx.require_request("CsrfToken")?;
348 Ok(ctx
349 .extensions
350 .get::<CsrfToken>()
351 .cloned()
352 .or_else(|| ctx.cookies.get(crate::CSRF_COOKIE).map(CsrfToken))
353 .unwrap_or_else(|| {
354 let t = crate::random_hex(32);
355 ctx.cookies.set(crate::Cookie::new(crate::CSRF_COOKIE, t.clone()).http_only(false));
356 CsrfToken(t)
357 }))
358 }
359}
360
361#[derive(Debug, Clone, Default, PartialEq, Eq)]
364pub struct FormState {
365 pub errors: BTreeMap<String, String>,
366 pub message: Option<String>,
367 pub values: BTreeMap<String, String>,
368}
369
370impl FormState {
371 pub fn error(&self, field: &str) -> Option<&str> {
372 self.errors.get(field).map(String::as_str)
373 }
374
375 pub fn value(&self, field: &str) -> &str {
376 self.values.get(field).map(String::as_str).unwrap_or("")
377 }
378
379 pub fn has_errors(&self) -> bool {
380 !self.errors.is_empty() || self.message.is_some()
381 }
382}
383
384impl FromContext for FormState {
385 fn from_context(ctx: &Ctx) -> Result<Self> {
386 ctx.require_request("FormState")?;
387 let Some(raw) = ctx.cookies.get_decoded(crate::actions::FLASH_COOKIE) else { return Ok(FormState::default()) };
388 ctx.cookies.delete(crate::actions::FLASH_COOKIE);
389 Ok(crate::actions::decode_flash(&raw))
390 }
391}