HomeDisk/types/src/database/user.rs

89 lines
2.3 KiB
Rust
Raw Normal View History

use rust_utilities::crypto::sha::{encode, Algorithm, CryptographicHash};
use uuid::Uuid;
2022-06-08 19:16:12 +00:00
/// SQL user table
#[derive(Debug, sqlx::FromRow)]
pub struct User {
pub id: String,
pub username: String,
pub password: String,
}
impl User {
2022-04-23 10:52:56 +00:00
/// **Note this doesn't create a new user in the database!**
///
2022-04-23 10:52:56 +00:00
/// This function creates a unique UUID for a user and creates a password hash using SHA-512
/// and returns in the User type
/// ```
/// use homedisk_types::database::User;
///
2022-04-19 11:08:30 +00:00
/// let user = User::new("medzik", "SuperSecretPassword123!");
/// ```
pub fn new(username: &str, password: &str) -> Self {
2022-04-23 10:52:56 +00:00
// change username to lowercase
let username = username.to_lowercase();
2022-06-08 17:08:06 +00:00
// generate a user UUID
2022-04-23 10:52:56 +00:00
let sha1_name = CryptographicHash::hash(Algorithm::SHA1, username.as_bytes());
let id = Uuid::new_v5(&Uuid::NAMESPACE_X500, &sha1_name).to_string();
// hash password using SHA-512
let password = encode(CryptographicHash::hash(
Algorithm::SHA512,
password.as_bytes(),
));
Self {
id,
username,
password,
}
}
2022-05-01 18:34:28 +00:00
/// User directory
/// function returns the directory where the user file is located
/// e.g.
/// ```
/// use homedisk_types::database::User;
///
/// let user = User::new("medzik", "whatever");
///
2022-05-01 20:44:28 +00:00
/// let dir = user.user_dir("/home/homedisk"); // will return `/home/homedisk/medzik`
///
/// assert_eq!(dir, "/home/homedisk/medzik")
2022-05-01 18:34:28 +00:00
/// ```
pub fn user_dir(&self, storage: &str) -> String {
2022-06-08 19:16:12 +00:00
// get a user storage path
2022-05-01 18:34:28 +00:00
let path = format!(
"{path}/{username}",
path = storage,
username = self.username,
);
2022-06-08 19:16:12 +00:00
// return user storage path
2022-05-01 18:34:28 +00:00
path
}
}
#[cfg(test)]
mod tests {
use super::User;
2022-06-07 20:36:26 +00:00
/// Check if the username has been changed to lowercase
#[test]
fn check_username_is_in_lowercase() {
let user = User::new("MEdzIk", "SuperSecretPassword123!");
assert_eq!(user.username, "medzik")
}
2022-06-07 20:36:26 +00:00
/// Check that the password is a checksum
#[test]
fn check_if_password_is_hashed() {
2022-04-23 10:52:56 +00:00
let password = "password";
let user = User::new("test", password);
assert!(user.password != password)
}
}