about summary refs log tree commit diff stats
path: root/crates/rocie-server/src/storage/sql/user.rs
blob: dd0cf06e2ee94d6711f138bcdcf65d38a69a3151 (plain) (blame)
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
// rocie - An enterprise grocery management system
//
// Copyright (C) 2026 Benedikt Peetz <benedikt.peetz@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Rocie.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::fmt::Display;

use argon2::{
    Argon2, PasswordHasher, PasswordVerifier,
    password_hash::{SaltString, rand_core::OsRng},
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

use crate::storage::sql::mk_id;

/// The definition of an rocie user.
#[derive(ToSchema, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
pub(crate) struct User {
    /// The unique ID for this user.
    pub(crate) id: UserId,

    /// The user-displayed name of this user.
    pub(crate) name: String,

    /// The hash of the user's password.
    pub(crate) password_hash: PasswordHash,

    /// An description of this user.
    #[schema(nullable = false)]
    pub(crate) description: Option<String>,
}

/// This is stored as an PHC password string.
///
/// This type corresponds to the string representation of a PHC string as
/// described in the [PHC string format specification][1].
///
/// PHC strings have the following format:
///
/// ```text
/// $<id>[$v=<version>][$<param>=<value>(,<param>=<value>)*][$<salt>[$<hash>]]
/// ```
#[derive(ToSchema, Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Serialize, Deserialize)]
pub(crate) struct PasswordHash {
    value: String,
}
impl PasswordHash {
    pub(crate) fn from_db(password_hash: String) -> PasswordHash {
        Self {
            value: password_hash,
        }
    }

    pub(crate) fn from_password(password: &str) -> Self {
        let salt = SaltString::generate(&mut OsRng);

        let argon2 = Argon2::default();

        let password_hash = argon2
            .hash_password(password.as_bytes(), &salt)
            .expect("to not fail")
            .to_string();

        Self {
            value: password_hash,
        }
    }

    /// Check that self, and the other password have the same hash.
    pub(crate) fn verify(&self, other: &str) -> bool {
        let argon2 = Argon2::default();

        argon2
            .verify_password(other.as_bytes(), &self.as_argon_hash())
            .is_ok()
    }

    fn as_argon_hash(&self) -> argon2::PasswordHash<'_> {
        argon2::PasswordHash::new(&self.value)
            .expect("to be valid, as we are just deserializing a previously serialize value")
    }
}

impl Display for PasswordHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.value.fmt(f)
    }
}

mk_id!(UserId and UserIdStub);