;
This commit is contained in:
1 parent
9268833a3c
commit
314b7445a1
27 files changed
+1830
No files matched your search
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "chronos-auth"
|
||||
version = { workspace = true }
|
||||
edition = "2021"
|
||||
authors = ["Chronos Team"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
homepage = "https://github.com/chronos/chronos"
|
||||
repository = "https://github.com/chronos/chronos"
|
||||
|
||||
[dependencies]
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
sqlx = { version = "0.7", features = ["postgres", "runtime-tokio-rustls"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
tracing = "0.1"
|
||||
thiserror = "1.0"
|
||||
anyhow = "1.0"
|
||||
argon2 = "0.5"
|
||||
uuid = { version = "1.0", features = ["v4"] }
|
||||
chronos-core = { path = "../chronos-core" }
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Error types for the authentication module.
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Error, Debug, Clone)]
|
||||
pub enum AuthError {
|
||||
#[error("Invalid credentials")]
|
||||
InvalidCredentials,
|
||||
|
||||
#[error("User not found")]
|
||||
UserNotFound,
|
||||
|
||||
#[error("Invalid session")]
|
||||
InvalidSession,
|
||||
|
||||
#[error("Password hashing failed")]
|
||||
PasswordHashingFailed,
|
||||
|
||||
#[error("Database error: {0}")]
|
||||
Database(String),
|
||||
|
||||
#[error("Authentication required")]
|
||||
AuthenticationRequired,
|
||||
}
|
||||
|
||||
impl From<sqlx::Error> for AuthError {
|
||||
fn from(error: sqlx::Error) -> Self {
|
||||
AuthError::Database(error.to_string())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Authentication module for Chronos
|
||||
//!
|
||||
//! Provides user authentication, session management, and access control.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::{PgPool, Row};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub mod error;
|
||||
pub use error::AuthError;
|
||||
|
||||
/// User role enumeration
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, sqlx::Type)]
|
||||
#[sqlx(type_name = "role", rename_all = "lowercase")]
|
||||
pub enum Role {
|
||||
Administrator,
|
||||
Operator,
|
||||
Viewer,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Role {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Role::Administrator => write!(f, "administrator"),
|
||||
Role::Operator => write!(f, "operator"),
|
||||
Role::Viewer => write!(f, "viewer"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// User entity
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
pub password_hash: String,
|
||||
pub role: Role,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
/// Session entity
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Session {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub token: String,
|
||||
pub expires_at: chrono::DateTime<chrono::Utc>,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
/// Authentication service
|
||||
pub struct AuthService {
|
||||
pool: PgPool,
|
||||
}
|
||||
|
||||
impl AuthService {
|
||||
/// Create a new authentication service
|
||||
pub fn new(pool: PgPool) -> Self {
|
||||
AuthService { pool }
|
||||
}
|
||||
|
||||
/// Authenticate a user with username and password
|
||||
pub async fn authenticate(
|
||||
&self,
|
||||
username: &str,
|
||||
password: &str,
|
||||
) -> Result<User, AuthError> {
|
||||
let user = self.get_user_by_username(username).await?;
|
||||
|
||||
// Verify password using Argon2id
|
||||
if !verify_password(password, &user.password_hash) {
|
||||
return Err(AuthError::InvalidCredentials);
|
||||
}
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
|
||||
/// Create a new session for a user
|
||||
pub async fn create_session(&self, user_id: Uuid) -> Result<Session, AuthError> {
|
||||
let token = generate_token();
|
||||
let expires_at = chrono::Utc::now() + chrono::Duration::hours(24);
|
||||
|
||||
let session = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO sessions (user_id, token, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, user_id, token, expires_at, created_at
|
||||
"#,
|
||||
user_id,
|
||||
token,
|
||||
expires_at
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Session {
|
||||
id: session.id,
|
||||
user_id: session.user_id,
|
||||
token: session.token,
|
||||
expires_at: session.expires_at,
|
||||
created_at: session.created_at,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate a session token
|
||||
pub async fn validate_session(&self, token: &str) -> Result<Session, AuthError> {
|
||||
let session = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, user_id, token, expires_at, created_at
|
||||
FROM sessions
|
||||
WHERE token = $1 AND expires_at > NOW()
|
||||
"#,
|
||||
token
|
||||
)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
match session {
|
||||
Some(s) => Ok(Session {
|
||||
id: s.id,
|
||||
user_id: s.user_id,
|
||||
token: s.token,
|
||||
expires_at: s.expires_at,
|
||||
created_at: s.created_at,
|
||||
}),
|
||||
None => Err(AuthError::InvalidSession),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a user by username
|
||||
pub async fn get_user_by_username(&self, username: &str) -> Result<User, AuthError> {
|
||||
let user = sqlx::query!(
|
||||
r#"
|
||||
SELECT id, username, password_hash, role, created_at, updated_at
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
"#,
|
||||
username
|
||||
)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
|
||||
match user {
|
||||
Some(u) => Ok(User {
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
password_hash: u.password_hash,
|
||||
role: u.role,
|
||||
created_at: u.created_at,
|
||||
updated_at: u.updated_at,
|
||||
}),
|
||||
None => Err(AuthError::UserNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new user
|
||||
pub async fn create_user(
|
||||
&self,
|
||||
username: String,
|
||||
password: String,
|
||||
role: Role,
|
||||
) -> Result<User, AuthError> {
|
||||
let password_hash = hash_password(&password)?;
|
||||
let id = Uuid::new_v4();
|
||||
|
||||
let user = sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO users (id, username, password_hash, role)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, password_hash, role, created_at, updated_at
|
||||
"#,
|
||||
id,
|
||||
username,
|
||||
password_hash,
|
||||
role
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(User {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
password_hash: user.password_hash,
|
||||
role: user.role,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at,
|
||||
})
|
||||
}
|
||||
|
||||
/// Logout a user by invalidating their session
|
||||
pub async fn logout(&self, token: &str) -> Result<(), AuthError> {
|
||||
sqlx::query!(
|
||||
r#"
|
||||
DELETE FROM sessions WHERE token = $1
|
||||
"#,
|
||||
token
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Hash a password using Argon2id
|
||||
fn hash_password(password: &str) -> Result<String, AuthError> {
|
||||
use argon2::{
|
||||
password_hash::{rand_core::OsRng, PasswordHasher, SaltString},
|
||||
Algorithm, Params, Version,
|
||||
};
|
||||
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
let params = Params::new(15000, 2, 1, None).map_err(|_| AuthError::PasswordHashingFailed)?;
|
||||
|
||||
let password_hash = argon2::Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
|
||||
.hash_password(password.as_bytes(), &salt)
|
||||
.map_err(|_| AuthError::PasswordHashingFailed)?
|
||||
.to_string();
|
||||
|
||||
Ok(password_hash)
|
||||
}
|
||||
|
||||
/// Verify a password against a hash
|
||||
fn verify_password(password: &str, hash: &str) -> bool {
|
||||
use argon2::{password_hash::PasswordVerifier, Algorithm, Version};
|
||||
|
||||
let parsed_hash = match argon2::password_hash::PasswordHash::new(hash) {
|
||||
Ok(h) => h,
|
||||
Err(_) => return false,
|
||||
};
|
||||
|
||||
let params = argon2::Params::default();
|
||||
let argon2 = argon2::Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
||||
|
||||
argon2
|
||||
.verify_password(password.as_bytes(), &parsed_hash)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
/// Generate a random token for sessions
|
||||
fn generate_token() -> String {
|
||||
use rand::Rng;
|
||||
let mut rng = rand::thread_rng();
|
||||
let mut token = String::with_capacity(64);
|
||||
for _ in 0..64 {
|
||||
token.push(rng.gen_range(b'a'..=b'z') as char);
|
||||
}
|
||||
token
|
||||
}
|
||||
Reference in new issue
Block a user