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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use auto_impl::auto_impl;
#[cfg(feature = "serde")]
use etwin_serde_tools::{buffer_to_hex, hex_to_buffer, Deserialize, Serialize};
#[cfg(feature = "sqlx")]
use sqlx::{database, postgres, Database, Postgres};
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Password(
#[cfg_attr(
feature = "serde",
serde(serialize_with = "buffer_to_hex", deserialize_with = "hex_to_buffer")
)]
pub Vec<u8>,
);
impl From<&[u8]> for Password {
fn from(value: &[u8]) -> Self {
Self(Vec::from(value))
}
}
impl From<&str> for Password {
fn from(value: &str) -> Self {
Self(Vec::from(value.as_bytes()))
}
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PasswordHash(
#[cfg_attr(
feature = "serde",
serde(serialize_with = "buffer_to_hex", deserialize_with = "hex_to_buffer")
)]
pub Vec<u8>,
);
impl PasswordHash {
pub fn as_slice(&self) -> &[u8] {
&self.0
}
}
#[cfg(feature = "sqlx")]
impl sqlx::Type<Postgres> for PasswordHash {
fn type_info() -> postgres::PgTypeInfo {
postgres::PgTypeInfo::with_name("password_hash")
}
fn compatible(ty: &postgres::PgTypeInfo) -> bool {
*ty == Self::type_info() || <&[u8] as sqlx::Type<Postgres>>::compatible(ty)
}
}
#[cfg(feature = "sqlx")]
impl<'r, Db: Database> sqlx::Decode<'r, Db> for PasswordHash
where
&'r [u8]: sqlx::Decode<'r, Db>,
{
fn decode(
value: <Db as database::HasValueRef<'r>>::ValueRef,
) -> Result<PasswordHash, Box<dyn std::error::Error + 'static + Send + Sync>> {
let value: &[u8] = <&[u8] as sqlx::Decode<Db>>::decode(value)?;
Ok(value.into())
}
}
#[cfg(feature = "sqlx")]
impl<'q, Db: Database> sqlx::Encode<'q, Db> for PasswordHash
where
Vec<u8>: sqlx::Encode<'q, Db>,
{
fn encode_by_ref(&self, buf: &mut <Db as database::HasArguments<'q>>::ArgumentBuffer) -> sqlx::encode::IsNull {
self.as_slice().to_vec().encode(buf)
}
}
impl From<&[u8]> for PasswordHash {
fn from(value: &[u8]) -> Self {
Self(Vec::from(value))
}
}
#[auto_impl(&, Arc)]
pub trait PasswordService: Send + Sync {
fn hash(&self, clear_text: Password) -> PasswordHash;
fn verify(&self, hash: PasswordHash, clear_text: Password) -> bool;
}