diff options
Diffstat (limited to 'server/src/routes/ui/account/session.rs')
-rw-r--r-- | server/src/routes/ui/account/session.rs | 32 |
1 files changed, 28 insertions, 4 deletions
diff --git a/server/src/routes/ui/account/session.rs b/server/src/routes/ui/account/session.rs index 6059311..6795c06 100644 --- a/server/src/routes/ui/account/session.rs +++ b/server/src/routes/ui/account/session.rs @@ -5,19 +5,36 @@ */ use crate::{ database::{Database, User}, - routes::ui::error::MyError, + routes::ui::error::MyError, CONF, }; use anyhow::anyhow; +use chrono::{DateTime, Duration, Utc}; use rocket::{ outcome::Outcome, request::{self, FromRequest}, Request, State, }; +use serde::{Deserialize, Serialize}; pub struct Session { pub user: User, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SessionCookie { + name: String, + expire: DateTime<Utc>, +} + +impl SessionCookie { + pub fn new(name: String) -> Self { + Self { + name, + expire: Utc::now() + Duration::days(CONF.login_expire), + } + } +} + impl Session { pub async fn from_request_ut(req: &Request<'_>) -> Result<Self, MyError> { #[cfg(not(feature = "bypass-auth"))] @@ -26,14 +43,21 @@ impl Session { .get_private("user") .ok_or(anyhow!("login required"))?; #[cfg(not(feature = "bypass-auth"))] - let username = cookie.value(); + let cookie = serde_json::from_str::<SessionCookie>(cookie.value())?; #[cfg(feature = "bypass-auth")] - let username = crate::CONF.admin_username.to_string(); + let cookie = SessionCookie { + name: crate::CONF.admin_username.to_string(), + expire: Utc::now() + Duration::days(CONF.login_expire), + }; + + if cookie.expire < Utc::now() { + Err(anyhow!("cookie expired"))?; + } let db = req.guard::<&State<Database>>().await.unwrap(); let user = db .users - .get(&username.to_string())? + .get(&cookie.name.to_string())? .ok_or(anyhow!("user not found"))?; Ok(Session { user }) |