about summary refs log tree commit diff
path: root/knowing/src/password.rs
blob: 013a9f7510599f5a829793564731ca469698b600 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use argon2::{Argon2, PasswordHasher, PasswordVerifier as ArgonPasswordVerifier};
use somethings::auth::HashedPassword;

use crate::Error;

pub trait IntoHashedPassword {
	fn hash_password(self) -> HashedPassword;
}

impl IntoHashedPassword for String {
	fn hash_password(self) -> HashedPassword {
		let a2 = Argon2::default();
		let a2_hash = a2.hash_password(self.as_bytes()).unwrap();

		HashedPassword::new(a2_hash.to_string())
	}
}

pub trait PasswordVerifier: Sized {
	fn get_password_hash(&self) -> &HashedPassword;
	fn verify_password(&self, plain: String) -> Result<(), Error> {
		let a2_phash = argon2::PasswordHash::new(&self.get_password_hash().to_string())
			.map_err(|_| Error::AuthenticationFailed)?;

		Argon2::default()
			.verify_password(plain.as_bytes(), &a2_phash)
			.map_err(|_| Error::AuthenticationFailed)
	}
}

impl PasswordVerifier for HashedPassword {
	fn get_password_hash(&self) -> &HashedPassword {
		self
	}
}