1use bcrypt::{hash, verify, DEFAULT_COST};
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, Debug, Serialize, Deserialize)]
5pub struct BasicAuth {
6 pub username: String,
7 pub hash: String,
8}
9
10pub fn hash_password(password: &str, cost: u32) -> String {
11 hash(password, cost).expect("Failed to hash password")
12}
13
14pub fn verify_password(password: &str, hash: &str) -> bool {
15 verify(password, hash).unwrap_or(false)
16}
17
18pub fn generate_hash(password: &str) -> String {
19 hash_password(password, DEFAULT_COST)
20}
21
22#[cfg(test)]
23mod tests {
24 use super::*;
25
26 #[test]
27 fn test_hash_and_verify() {
28 let password = "secret123";
29 let hash = generate_hash(password);
30 assert!(!hash.is_empty());
31 assert!(verify_password(password, &hash));
32 assert!(!verify_password("wrongpassword", &hash));
33 }
34
35 #[test]
36 fn test_different_hashes_same_password() {
37 let password = "secret123";
38 let hash1 = generate_hash(password);
39 let hash2 = generate_hash(password);
40 assert_ne!(hash1, hash2);
41 assert!(verify_password(password, &hash1));
42 assert!(verify_password(password, &hash2));
43 }
44}