2024-04-04 11:40:26 +10:00
|
|
|
// SPDX-FileCopyrightText: 2023 Sayantan Santra <sayantan.santra689@gmail.com>
|
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
|
2023-04-08 17:52:16 +10:00
|
|
|
use actix_session::Session;
|
2023-04-10 08:19:54 +10:00
|
|
|
use std::{env, time::SystemTime};
|
2023-04-08 17:52:16 +10:00
|
|
|
|
2024-04-03 08:57:49 +10:00
|
|
|
// Validate a given password
|
2023-04-08 17:52:16 +10:00
|
|
|
pub fn validate(session: Session) -> bool {
|
2023-04-10 08:19:54 +10:00
|
|
|
// If there's no password provided, just return true
|
2024-10-03 14:52:23 +10:00
|
|
|
if env::var("password")
|
|
|
|
.ok()
|
|
|
|
.filter(|s| !s.trim().is_empty())
|
|
|
|
.is_none()
|
|
|
|
{
|
2023-04-10 08:19:54 +10:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2024-04-03 08:57:49 +10:00
|
|
|
if let Ok(token) = session.get::<String>("chhoto-url-auth") {
|
2024-04-03 08:43:36 +10:00
|
|
|
check(token)
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
2023-04-08 17:52:16 +10:00
|
|
|
}
|
|
|
|
|
2024-04-03 08:57:49 +10:00
|
|
|
// Check a token cryptographically
|
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();
|
2024-04-03 08:57:49 +10:00
|
|
|
token_text == "chhoto-url-auth" && 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
|
|
|
|
2024-04-03 08:57:49 +10:00
|
|
|
// Generate a new cryptographic token
|
2023-04-09 06:36:33 +10:00
|
|
|
pub fn gen_token() -> String {
|
2024-04-03 08:57:49 +10:00
|
|
|
let token_text = String::from("chhoto-url-auth");
|
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}")
|
|
|
|
}
|