chhoto-url/actix/src/auth.rs

41 lines
1.2 KiB
Rust
Raw Normal View History

2023-04-08 17:52:16 +10:00
use actix_session::Session;
use std::{env, time::SystemTime};
2023-04-08 17:52:16 +10:00
pub fn validate(session: Session) -> bool {
// If there's no password provided, just return true
if env::var("password").is_err() {
return true;
}
2023-04-09 06:36:33 +10:00
let token = session.get::<String>("session-token");
2023-04-27 05:40:54 +10:00
token.is_ok() && check(token.unwrap())
2023-04-08 17:52:16 +10:00
}
2023-04-09 06:36:33 +10:00
fn check(token: Option<String>) -> bool {
2023-04-27 05:40:54 +10:00
if let Some(token_body) = token {
let token_parts: Vec<&str> = token_body.split(';').collect();
2023-04-09 06:36:33 +10:00
if token_parts.len() < 2 {
false
} else {
let token_text = token_parts[0];
let token_time = token_parts[1].parse::<u64>().unwrap_or(0);
let time_now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Time went backwards!")
.as_secs();
2023-04-27 05:40:54 +10:00
token_text == "session-token" && time_now < token_time + 1209600 // There are 1209600 seconds in 14 days
2023-04-09 06:36:33 +10:00
}
2023-04-27 05:40:54 +10:00
} else {
false
2023-04-08 17:52:16 +10:00
}
}
2023-04-09 06:36:33 +10:00
pub fn gen_token() -> String {
let token_text = String::from("session-token");
2023-04-09 06:36:33 +10:00
let time = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.expect("Time went backwards!")
.as_secs();
format!("{token_text};{time}")
}