1use std::sync::Arc;
2
3use axum::{
4 Extension, Json,
5 extract::State,
6 http::{HeaderMap, HeaderValue, header},
7 response::IntoResponse,
8};
9use axum_extra::extract::{
10 CookieJar,
11 cookie::{Cookie, SameSite},
12};
13use redis::AsyncCommands;
14use serde_json::json;
15
16use crate::{
17 AppState, Config,
18 jwt_auth::{
19 JWTAuthMiddleware, REUSE_GRACE_SECS, Redemption, Rotation, end_session, mint_failed,
20 rotate_refresh,
21 },
22 response::{UNAVAILABLE_MESSAGE, WebError},
23 token::{TokenDetails, TokenType},
24};
25use rust_i18n::t;
26
27pub(crate) fn append_set_cookies(
31 headers: &mut HeaderMap,
32 cookies: impl IntoIterator<Item = String>,
33) {
34 for cookie in cookies {
35 if let Ok(value) = cookie.parse() {
36 headers.append(header::SET_COOKIE, value);
37 }
38 }
39}
40
41pub(crate) fn session_cookies(conf: &Config, access: String, refresh: String) -> [String; 2] {
43 let build = |name: &'static str, value: String, max_age: i64| {
44 Cookie::build((name, value))
45 .path("/")
46 .max_age(time::Duration::minutes(max_age))
47 .same_site(SameSite::Lax)
48 .secure(crate::auth_keys::secure_cookies())
49 .http_only(true)
50 .to_string()
51 };
52 [
53 build("access_token", access, conf.access_token_max_age),
54 build("refresh_token", refresh, conf.refresh_token_max_age),
55 ]
56}
57
58pub(crate) async fn mint_token(
59 user_id: uuid::Uuid,
60 max_age: i64,
61 token_type: TokenType,
62 generation: i32,
63) -> Result<TokenDetails, WebError> {
64 crate::auth_keys::mint(user_id, max_age, token_type, generation)
65 .await
66 .map_err(mint_failed)
67}
68
69pub(crate) async fn save_token_data_to_redis(
70 data: &Arc<AppState>,
71 token_details: &TokenDetails,
72 max_age: i64,
73) -> Result<(), WebError> {
74 let mut redis_client = redis_connection(data).await?;
75 redis_client
76 .set_ex::<_, _, ()>(
77 token_details.token_uuid.to_string(),
78 token_details.user_id.to_string(),
79 (max_age * 60) as u64,
80 )
81 .await
82 .map_err(|e| WebError::internal("Saving the session failed", e))
83}
84
85async fn redis_connection(
86 data: &Arc<AppState>,
87) -> Result<redis::aio::MultiplexedConnection, WebError> {
88 data.redis_client
89 .get_multiplexed_async_connection()
90 .await
91 .map_err(|e| {
92 tracing::error!("Session store unreachable: {e}");
93 WebError::unavailable(UNAVAILABLE_MESSAGE)
94 })
95}
96
97fn expired() -> WebError {
98 WebError::unauthorized(t!("Token is invalid or session has expired").to_string())
99}
100
101async fn own_refresh_token(
106 cookie_jar: &CookieJar,
107 user_id: uuid::Uuid,
108) -> Result<TokenDetails, WebError> {
109 let refresh_token = cookie_jar
110 .get("refresh_token")
111 .map(|cookie| cookie.value().to_string())
112 .ok_or_else(expired)?;
113
114 let details = crate::auth_keys::verify(&refresh_token, TokenType::Refresh)
115 .await
116 .map_err(|e| {
118 tracing::error!("Token directory unreadable: {e}");
119 WebError::unavailable(UNAVAILABLE_MESSAGE)
120 })?
121 .ok_or_else(expired)?;
122
123 if details.user_id != user_id {
124 return Err(expired());
125 }
126 Ok(details)
127}
128
129fn refreshed_by_session() -> (HeaderMap, Json<serde_json::Value>) {
130 (
131 HeaderMap::new(),
132 Json(json!({"status": "success", "refreshed_by": "session"})),
133 )
134}
135
136pub async fn refresh_access_token_handler(
137 cookie_jar: CookieJar,
138 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
139 State(data): State<Arc<AppState>>,
140) -> Result<impl IntoResponse, WebError> {
141 if jwt_auth.refreshed {
145 return Ok(refreshed_by_session());
146 }
147
148 let refresh_token_details = own_refresh_token(&cookie_jar, jwt_auth.user.id).await?;
149 let mut redis_client = redis_connection(&data).await?;
150 let user_id = jwt_auth.user.id;
151
152 let access_token_details = mint_token(
156 user_id,
157 data.conf.access_token_max_age,
158 TokenType::Access,
159 refresh_token_details.generation,
160 )
161 .await?;
162 let new_refresh_details = mint_token(
163 user_id,
164 data.conf.refresh_token_max_age,
165 TokenType::Refresh,
166 refresh_token_details.generation,
167 )
168 .await?;
169
170 let redemption = rotate_refresh(
171 &mut redis_client,
172 &Rotation {
173 token_uuid: refresh_token_details.token_uuid,
174 owner: user_id,
175 successor: new_refresh_details.token_uuid,
176 access_uuid: access_token_details.token_uuid,
177 superseded: Some(jwt_auth.access_token_uuid),
178 refresh_ttl: (data.conf.refresh_token_max_age * 60) as u64,
179 access_ttl: (data.conf.access_token_max_age * 60) as u64,
180 grace: REUSE_GRACE_SECS,
181 },
182 )
183 .await?;
184 match redemption {
185 Redemption::Rotated => {}
186 Redemption::Reused => return Ok(refreshed_by_session()),
187 Redemption::Refused => return Err(expired()),
188 }
189
190 let access = access_token_details.token.unwrap_or_default();
191 let mut headers = HeaderMap::new();
192 append_set_cookies(
193 &mut headers,
194 session_cookies(
195 &data.conf,
196 access.clone(),
197 new_refresh_details.token.unwrap_or_default(),
198 ),
199 );
200 Ok((
201 headers,
202 Json(json!({"status": "success", "access_token": access})),
203 ))
204}
205
206pub async fn logout_handler(
207 cookie_jar: CookieJar,
208 Extension(auth_guard): Extension<JWTAuthMiddleware>,
209 State(data): State<Arc<AppState>>,
210) -> Result<impl IntoResponse, WebError> {
211 let refresh_token_details = own_refresh_token(&cookie_jar, auth_guard.user.id).await?;
212 let mut redis_client = redis_connection(&data).await?;
213
214 end_session(
215 &mut redis_client,
216 refresh_token_details.token_uuid,
217 auth_guard.access_token_uuid,
218 auth_guard.user.id,
219 )
220 .await?;
221
222 Ok((session_end_headers("/"), Json(json!({"status": "success"}))))
223}
224
225pub fn session_end_headers(target: &'static str) -> HeaderMap {
229 let expire = |name: &'static str| {
230 Cookie::build((name, ""))
231 .path("/")
232 .max_age(time::Duration::minutes(-1))
233 .same_site(SameSite::Lax)
234 .secure(crate::auth_keys::secure_cookies())
235 .http_only(true)
236 .to_string()
237 };
238
239 let mut headers = HeaderMap::new();
240 append_set_cookies(&mut headers, ["access_token", "refresh_token"].map(expire));
241 headers.append("HX-Redirect", HeaderValue::from_static(target));
242 headers
243}
244
245#[derive(serde::Deserialize)]
246pub struct ChangePasswordSchema {
247 pub current_password: String,
248 pub new_password: String,
249 pub confirm_password: String,
250}
251
252fn password_change_error(user_id: uuid::Uuid, e: server::command::CmdError) -> WebError {
255 tracing::warn!("password change refused for user_id={user_id}: {e}");
256 match e {
257 server::command::CmdError::Args(_) => {
258 WebError::bad_request(t!("Invalid email or password").to_string())
259 }
260 e => WebError::from(e),
261 }
262}
263
264pub async fn change_password_handler(
271 Extension(jwtauth): Extension<JWTAuthMiddleware>,
272 Json(body): Json<ChangePasswordSchema>,
273) -> Result<impl IntoResponse, WebError> {
274 if body.new_password != body.confirm_password {
278 return Err(WebError::bad_request(
279 t!("The new passwords do not match").to_string(),
280 ));
281 }
282
283 server::command::user::change_password(
284 jwtauth.user.id,
285 &body.current_password,
286 &body.new_password,
287 )
288 .await
289 .map_err(|e| password_change_error(jwtauth.user.id, e))?;
290
291 Ok((
292 session_end_headers("/login"),
293 Json(json!({ "status": "success" })),
294 ))
295}
296
297#[cfg(test)]
298#[path = "session_tests.rs"]
299mod tests;