feat: add hash_token function for SHA-256 session token hashing
This commit is contained in:
parent
81555d920e
commit
5be0cab525
@ -1,4 +1,5 @@
|
|||||||
use chrono::{DateTime, Duration, Utc};
|
use chrono::{DateTime, Duration, Utc};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@ -6,6 +7,13 @@ pub fn generate_token() -> String {
|
|||||||
Uuid::new_v4().to_string()
|
Uuid::new_v4().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub fn hash_token(token: &str) -> String {
|
||||||
|
let mut hasher = Sha256::new();
|
||||||
|
hasher.update(token.as_bytes());
|
||||||
|
hex::encode(hasher.finalize())
|
||||||
|
}
|
||||||
|
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub fn default_expiry() -> DateTime<Utc> {
|
pub fn default_expiry() -> DateTime<Utc> {
|
||||||
Utc::now() + Duration::days(30)
|
Utc::now() + Duration::days(30)
|
||||||
@ -99,4 +107,29 @@ mod tests {
|
|||||||
let diff = expiry - chrono::Utc::now();
|
let diff = expiry - chrono::Utc::now();
|
||||||
assert!(diff.num_days() >= 29 && diff.num_days() <= 31);
|
assert!(diff.num_days() >= 29 && diff.num_days() <= 31);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hash_token_is_deterministic() {
|
||||||
|
let token = "test-token-123";
|
||||||
|
assert_eq!(hash_token(token), hash_token(token));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hash_token_is_64_chars() {
|
||||||
|
let hash = hash_token("any-token");
|
||||||
|
assert_eq!(hash.len(), 64);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hash_token_differs_from_input() {
|
||||||
|
let token = "my-secret-token";
|
||||||
|
assert_ne!(hash_token(token), token);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hash_token_known_value() {
|
||||||
|
let hash = hash_token("hello");
|
||||||
|
let expected = sha2::Sha256::digest(b"hello");
|
||||||
|
assert_eq!(hash, hex::encode(expected));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user