Add 'Remember Me' feature to login (extends session to 30 days)
All checks were successful
Build MIPS Binary / build (push) Successful in 4m7s

This commit is contained in:
spinline
2026-02-07 19:05:52 +03:00
parent 9b18b97c49
commit 575cfa4b38
2 changed files with 28 additions and 4 deletions

View File

@@ -13,6 +13,8 @@ use time::Duration;
pub struct LoginRequest {
username: String,
password: String,
#[serde(default)]
remember_me: bool,
}
#[derive(Serialize, ToSchema)]
@@ -61,8 +63,13 @@ pub async fn login_handler(
rand::thread_rng().sample(Alphanumeric) as char
}).collect();
// Expires in 30 days
let expires_in = 60 * 60 * 24 * 30;
// Expiration: 30 days if remember_me is true, else 1 day
let expires_in = if payload.remember_me {
60 * 60 * 24 * 30
} else {
60 * 60 * 24
};
let expires_at = time::OffsetDateTime::now_utc().unix_timestamp() + expires_in;
if let Err(e) = state.db.create_session(user_id, &token, expires_at).await {
@@ -70,13 +77,14 @@ pub async fn login_handler(
return (StatusCode::INTERNAL_SERVER_ERROR, "Failed to create session").into_response();
}
let cookie = Cookie::build(("auth_token", token))
let mut cookie = Cookie::build(("auth_token", token))
.path("/")
.http_only(true)
.same_site(SameSite::Lax)
.max_age(Duration::seconds(expires_in))
.build();
cookie.set_max_age(Duration::seconds(expires_in));
tracing::info!("Session created and cookie set for user: {}", payload.username);
(StatusCode::OK, jar.add(cookie), Json(UserResponse { username: payload.username })).into_response()
}