```
Add user authentication with password hashing - Integrated Argon2 for password hashing and verification - Added bcrypt and thiserror dependencies - Updated database schema with admin and ban flags - Implemented user account creation and login logic - Enhanced error handling for database operations ```
This commit is contained in:
parent
ba22b22ecc
commit
b98a890738
9 changed files with 278 additions and 10 deletions
|
@ -4,6 +4,7 @@ pub(crate) mod handlers {
|
|||
Aes256Gcm, Key, Nonce,
|
||||
};
|
||||
|
||||
use crate::db::users::{check_for_account, create_user, hash_password, verify_password};
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
|
||||
use log::{debug, error, info};
|
||||
use serde::Deserialize;
|
||||
|
@ -12,8 +13,6 @@ pub(crate) mod handlers {
|
|||
use tokio::net::TcpStream;
|
||||
use tokio::sync::broadcast;
|
||||
use x25519_dalek::{EphemeralSecret, PublicKey};
|
||||
|
||||
use crate::db::users::create_user;
|
||||
/*
|
||||
Specifications of the packet
|
||||
32 bytes - Command name
|
||||
|
@ -86,8 +85,90 @@ pub(crate) mod handlers {
|
|||
let username = Arc::new(String::from_utf8(decrypted)?);
|
||||
let username_read = Arc::clone(&username); // Clone the Arc for read task
|
||||
let username_write = Arc::clone(&username); // Clone the Arc for write task
|
||||
info!("Username received: {}", username);
|
||||
|
||||
create_user(&username, "1234").await?;
|
||||
// Check if the user already exists in the database
|
||||
if check_for_account(&username).await? {
|
||||
info!("User {} already exists", username);
|
||||
// Send a message to the client
|
||||
let message = format!("User {} is registered, input your password", username);
|
||||
let encrypted = match cipher_writer.encrypt(&nonce_writer, message.as_bytes()) {
|
||||
Ok(encrypted) => encrypted,
|
||||
Err(e) => {
|
||||
error!("Encryption error: {}", e);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let message = format!("{}\n", BASE64.encode(&encrypted));
|
||||
writer.write_all(message.as_bytes()).await?;
|
||||
|
||||
// Read the password from the client
|
||||
line.clear();
|
||||
reader.read_line(&mut line).await?;
|
||||
let decoded = BASE64.decode(line.trim().as_bytes())?;
|
||||
let decrypted = cipher_reader
|
||||
.decrypt(&nonce_reader, decoded.as_ref())
|
||||
.unwrap();
|
||||
// verifiy password
|
||||
let password = String::from_utf8(decrypted)?;
|
||||
if verify_password(&password, &username).await.is_ok() {
|
||||
info!("Password verified successfully");
|
||||
// Send a success message to the client
|
||||
let message = format!("Welcome back, {}!", username);
|
||||
let encrypted = match cipher_writer.encrypt(&nonce_writer, message.as_bytes()) {
|
||||
Ok(encrypted) => encrypted,
|
||||
Err(e) => {
|
||||
error!("Encryption error: {}", e);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let message = format!("{}\n", BASE64.encode(&encrypted));
|
||||
writer.write_all(message.as_bytes()).await?;
|
||||
} else {
|
||||
info!("Password verification failed");
|
||||
// Send an error message to the client
|
||||
let message = format!("Invalid password for user {}", username);
|
||||
let encrypted = match cipher_writer.encrypt(&nonce_writer, message.as_bytes()) {
|
||||
Ok(encrypted) => encrypted,
|
||||
Err(e) => {
|
||||
error!("Encryption error: {}", e);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let message = format!("{}\n", BASE64.encode(&encrypted));
|
||||
writer.write_all(message.as_bytes()).await?;
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
// User does not exist, create a new account
|
||||
// Send a message to the client
|
||||
let message = format!("User {} is not registered, input your password", username);
|
||||
let encrypted = match cipher_writer.encrypt(&nonce_writer, message.as_bytes()) {
|
||||
Ok(encrypted) => encrypted,
|
||||
Err(e) => {
|
||||
error!("Encryption error: {}", e);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let message = format!("{}\n", BASE64.encode(&encrypted));
|
||||
writer.write_all(message.as_bytes()).await?;
|
||||
// Read the password from the client
|
||||
line.clear();
|
||||
reader.read_line(&mut line).await?;
|
||||
let decoded = BASE64.decode(line.trim().as_bytes())?;
|
||||
let decrypted = cipher_reader
|
||||
.decrypt(&nonce_reader, decoded.as_ref())
|
||||
.unwrap();
|
||||
let password = String::from_utf8(decrypted)?;
|
||||
info!("Password received");
|
||||
// Hash the password
|
||||
let password_hash = hash_password(&password).await;
|
||||
let password_hash = password_hash.as_str();
|
||||
info!("Password hashed successfully");
|
||||
debug!("Hash: {}", password_hash);
|
||||
// Create the user in the database
|
||||
create_user(&username, password_hash).await?;
|
||||
}
|
||||
|
||||
// Read task for receiving messages from the client
|
||||
let read_task = tokio::spawn(async move {
|
||||
|
|
121
src/db/mod.rs
121
src/db/mod.rs
|
@ -1,5 +1,21 @@
|
|||
pub(crate) mod users {
|
||||
use sqlx::sqlite::SqlitePool;
|
||||
use argon2::{
|
||||
password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
|
||||
Argon2,
|
||||
};
|
||||
use log::info;
|
||||
use sqlx::{sqlite::SqlitePool, Row};
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum DbError {
|
||||
#[error("Database error: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error("Password hashing error: {0}")]
|
||||
Hashing(argon2::password_hash::Error),
|
||||
#[error("User not found")]
|
||||
UserNotFound,
|
||||
}
|
||||
|
||||
pub async fn connect_to_db() -> Result<SqlitePool, sqlx::Error> {
|
||||
let pool = SqlitePool::connect("sqlite:./db.sqlite").await?;
|
||||
|
@ -12,6 +28,46 @@ pub(crate) mod users {
|
|||
Ok(pool)
|
||||
}
|
||||
|
||||
pub async fn get_user_by_username(
|
||||
username: &str,
|
||||
) -> Result<Option<(i64, String)>, sqlx::Error> {
|
||||
let pool = create_db_pool().await?;
|
||||
|
||||
let user = sqlx::query(
|
||||
r#"
|
||||
SELECT id, username
|
||||
FROM users
|
||||
WHERE username = ?
|
||||
"#,
|
||||
)
|
||||
.bind(username)
|
||||
.fetch_optional(&pool)
|
||||
.await?;
|
||||
|
||||
Ok(user.map(|row| (row.get(0), row.get(1))))
|
||||
}
|
||||
|
||||
pub async fn check_for_account(username: &str) -> Result<bool, sqlx::Error> {
|
||||
// Fixed error type
|
||||
let pool = create_db_pool().await?;
|
||||
|
||||
let exists = sqlx::query(
|
||||
r#"
|
||||
SELECT EXISTS(
|
||||
SELECT 1
|
||||
FROM users
|
||||
WHERE username = ?
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.bind(username)
|
||||
.fetch_one(&pool)
|
||||
.await?
|
||||
.get::<i64, _>(0);
|
||||
|
||||
Ok(exists == 1)
|
||||
}
|
||||
|
||||
pub async fn create_user(username: &str, password_hash: &str) -> Result<(), sqlx::Error> {
|
||||
let pool = create_db_pool().await?;
|
||||
|
||||
|
@ -27,4 +83,67 @@ pub(crate) mod users {
|
|||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn hash_password(password: &str) -> String {
|
||||
let salt = SaltString::generate(&mut rand::thread_rng());
|
||||
let argon2 = Argon2::default();
|
||||
let password_hash = argon2
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.expect("Failed to hash password");
|
||||
password_hash.to_string()
|
||||
}
|
||||
|
||||
pub async fn verify_password(
|
||||
// Use clearer argument names
|
||||
username: &str,
|
||||
provided_password: &str,
|
||||
) -> Result<bool, DbError> {
|
||||
let pool = create_db_pool().await?; // Propagates sqlx::Error
|
||||
|
||||
// Fetch the stored hash for the user
|
||||
let user_row = sqlx::query(
|
||||
r#"
|
||||
SELECT password_hash
|
||||
FROM users
|
||||
WHERE username = ?
|
||||
"#,
|
||||
)
|
||||
.bind(username)
|
||||
.fetch_optional(&pool) // Use fetch_optional to handle not found case
|
||||
.await?;
|
||||
|
||||
// Get the stored hash string or return error if user not found
|
||||
let stored_hash_str = match user_row {
|
||||
Some(row) => row.get::<String, _>(0),
|
||||
None => return Err(DbError::UserNotFound),
|
||||
};
|
||||
|
||||
// Parse the stored hash
|
||||
let parsed_hash = PasswordHash::new(&stored_hash_str).map_err(DbError::Hashing)?; // Manually map the error
|
||||
|
||||
let argon2 = Argon2::default();
|
||||
|
||||
let verification_result =
|
||||
argon2.verify_password(provided_password.as_bytes(), &parsed_hash);
|
||||
|
||||
// Check the result and return true/false accordingly
|
||||
match verification_result {
|
||||
Ok(()) => {
|
||||
info!("Password check successful for user: {}", username);
|
||||
Ok(true)
|
||||
}
|
||||
Err(argon2::password_hash::Error::Password) => {
|
||||
info!("Password check failed (mismatch) for user: {}", username);
|
||||
Ok(false)
|
||||
}
|
||||
Err(e) => {
|
||||
// Handle other potential argon2 errors (e.g., invalid hash format)
|
||||
info!(
|
||||
"Password check failed for user {} with error: {}",
|
||||
username, e
|
||||
);
|
||||
Err(DbError::Hashing(e))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
mod client;
|
||||
mod tui; // Add this new module
|
||||
mod db;
|
||||
mod tui;
|
||||
|
||||
use client::handlers::handle_client;
|
||||
use db::users::create_db_pool;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue