1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
// ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX)         ┃
// ┃ SPDX-License-Identifier: MPL-2.0                                          ┃
// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
// ┃                                                                           ┃
// ┃  This Source Code Form is subject to the terms of the Mozilla Public      ┃
// ┃  License, v. 2.0. If a copy of the MPL was not distributed with this      ┃
// ┃  file, You can obtain one at https://mozilla.org/MPL/2.0/.                ┃
// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

use std::ops;
use std::sync::Arc;

// --------- //
// Interface //
// --------- //

#[async_trait::async_trait]
pub trait HttpContextInterface: Send + Sync {
	type State;

	async fn new(
		extensions: &super::Extensions,
		state: Self::State,
	) -> Option<Self>
	where
		Self: Sized;

	fn shared(self) -> Arc<Self>
	where
		Self: Sized,
	{
		Arc::new(self)
	}
}

// --------- //
// Structure //
// --------- //

pub struct HttpContext<T> {
	pub(crate) context: Arc<T>,
	pub request: HttpRequest<T>,
	pub response: HttpResponse<T>,
	#[cfg(feature = "cookies")]
	pub cookies: crate::http::cookies::Cookies,

	#[cfg(feature = "cookies")]
	pub session: SessionContext,
}

pub struct HttpRequest<T> {
	pub(crate) context: Arc<T>,
	pub ip: std::net::SocketAddr,
	pub method: hyper::Method,
	pub uri: hyper::Uri,
	pub raw_query: Option<String>,
	pub referer: Option<axum::headers::Referer>,
}

pub struct HttpResponse<T> {
	pub(crate) context: Arc<T>,
}

#[cfg(feature = "cookies")]
pub struct SessionContext {
	pub(crate) handle: axum_sessions::SessionHandle,
}

// -------------- //
// Implémentation //
// -------------- //

impl<T> HttpContext<T> {
	#[cfg(feature = "auth")]
	/// Déconnecte l'utilisateur de la session, et détruit le cookie de
	/// connexion associé à l'utilisateur.
	pub async fn logout_user(&mut self) {
		let mut session = self.session.write().await;
		session.remove(crate::auth::AUTH_USER_ID_SESSION);
		session.remove(crate::auth::AUTH_ADMIN_ID_SESSION);
		session.regenerate();

		if let Some(mut user_cookie) = self
			.cookies
			.private()
			.get(crate::auth::AUTH_USER_ID_SESSION)
		{
			let expires_in = time::OffsetDateTime::now_utc()
				.checked_sub(time::Duration::days(100));
			user_cookie.set_path("/");
			user_cookie.set_expires(expires_in);
			self.cookies.private().add(user_cookie);
		}

		if let Some(mut adm_cookie) = self
			.cookies
			.private()
			.get(crate::auth::AUTH_ADMIN_ID_SESSION)
		{
			let expires_in = time::OffsetDateTime::now_utc()
				.checked_sub(time::Duration::days(100));
			adm_cookie.set_path("/");
			adm_cookie.set_expires(expires_in);
			self.cookies.private().add(adm_cookie);
		}
	}
}

impl<T> HttpResponse<T> {
	/// Rend l'HTML d'une vue.
	#[inline]
	pub fn html<R>(
		&self,
		html: impl Into<axum::response::Html<R>>,
	) -> axum::response::Html<R>
	where
		R: Into<axum::body::Full<hyper::body::Bytes>>,
	{
		html.into()
	}

	/// Retourne un JSON en réponse.
	//
	// BUG(phisyx): provoque une erreur avec la commande `cargo doc`.
	// ISSUE(rust): "rustdoc RPITIT ICE:
	//               compiler\rustc_middle\src\ty\generic_args.rs:900:9: type
	//               parameter impl ToString/#1 (impl ToString/1) out of range
	//               when substituting, args=[MyStruct] "
	//               https://github.com/rust-lang/rust/issues/113929
	// ISSUE(rust): Closed (Fixed by https://github.com/rust-lang/rust/pull/113956).
	#[inline]
	pub fn json<D>(&self, data: D) -> axum::response::Json<D>
	where
		D: serde::Serialize,
	{
		// axum::response::Json(serde_json::json!(data))
		data.into()
	}

	/// Redirige le client vers une URL (Code HTTP 303).
	#[inline]
	pub fn redirect_to(&self, uri: impl ToString) -> axum::response::Redirect
	where
		Self: Sized,
	{
		axum::response::Redirect::to(uri.to_string().as_ref())
	}

	/// Redirige le client vers une URL de manière permanente (Code HTTP 308).
	#[inline]
	pub fn redirect_permanent(
		&self,
		uri: impl ToString,
	) -> axum::response::Redirect
	where
		Self: Sized,
	{
		axum::response::Redirect::permanent(uri.to_string().as_ref())
	}

	/// Redirige le client vers une URL de manière temporaire (Code HTTP 307).
	#[inline]
	pub fn redirect_temporary(
		&self,
		uri: impl ToString,
	) -> axum::response::Redirect
	where
		Self: Sized,
	{
		axum::response::Redirect::temporary(uri.to_string().as_ref())
	}
}

#[cfg(feature = "cookies")]
impl SessionContext {
	pub async fn read(
		&self,
	) -> tokio::sync::RwLockReadGuard<'_, axum_sessions::async_session::Session>
	{
		self.handle.read().await
	}

	pub async fn write(
		&mut self,
	) -> tokio::sync::RwLockWriteGuard<'_, axum_sessions::async_session::Session>
	{
		self.handle.write().await
	}

	#[cfg(feature = "auth")]
	pub async fn is_logged<User>(&self) -> bool
	where
		User: serde::de::DeserializeOwned,
	{
		self.read()
			.await
			.get::<User>(crate::auth::AUTH_ADMIN_ID_SESSION)
			.is_some() || self
			.read()
			.await
			.get::<User>(crate::auth::AUTH_USER_ID_SESSION)
			.is_some()
	}

	#[cfg(feature = "auth")]
	pub async fn is_logged_as_admin<User>(&self) -> bool
	where
		User: serde::de::DeserializeOwned,
	{
		self.read()
			.await
			.get::<User>(crate::auth::AUTH_ADMIN_ID_SESSION)
			.is_some()
	}

	#[cfg(feature = "auth")]
	pub async fn is_logged_as_user<User>(&self) -> bool
	where
		User: serde::de::DeserializeOwned,
	{
		self.read()
			.await
			.get::<User>(crate::auth::AUTH_USER_ID_SESSION)
			.is_some()
	}
}

// -------------- //
// Implémentation // -> Interface
// -------------- //

impl<T> ops::Deref for HttpContext<T> {
	type Target = Arc<T>;

	fn deref(&self) -> &Self::Target {
		&self.context
	}
}