use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthUser {
pub id: i64,
pub email: String,
pub role: String,
}
impl AuthUser {
pub fn new(id: i64, email: impl Into<String>, role: impl Into<String>) -> Self {
Self {
id,
email: email.into(),
role: role.into(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub token: String,
pub user_id: i64,
pub expires_at: chrono::NaiveDateTime,
}
impl Session {
pub fn new(token: impl Into<String>, user_id: i64, expires_at: chrono::NaiveDateTime) -> Self {
Self {
token: token.into(),
user_id,
expires_at,
}
}
pub fn is_expired(&self) -> bool {
chrono::Utc::now().naive_utc() > self.expires_at
}
pub fn remaining_time(&self) -> Option<chrono::Duration> {
let now = chrono::Utc::now().naive_utc();
if now < self.expires_at {
Some(self.expires_at - now)
} else {
None
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Credentials {
pub email: String,
pub password: String,
}
impl Credentials {
pub fn new(email: impl Into<String>, password: impl Into<String>) -> Self {
Self {
email: email.into(),
password: password.into(),
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct LoginResponse {
pub token: String,
pub user: AuthUser,
pub expires_at: chrono::NaiveDateTime,
}
impl LoginResponse {
pub fn new(session: Session, user: AuthUser) -> Self {
Self {
token: session.token,
expires_at: session.expires_at,
user,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
#[test]
fn test_auth_user_creation() {
let user = AuthUser::new(1, "test@example.com", "admin");
assert_eq!(user.id, 1);
assert_eq!(user.email, "test@example.com");
assert_eq!(user.role, "admin");
}
#[test]
fn test_session_expiration() {
let future = chrono::Utc::now().naive_utc() + Duration::hours(1);
let session = Session::new("token123", 1, future);
assert!(!session.is_expired());
assert!(session.remaining_time().is_some());
let past = chrono::Utc::now().naive_utc() - Duration::hours(1);
let expired_session = Session::new("token456", 1, past);
assert!(expired_session.is_expired());
assert!(expired_session.remaining_time().is_none());
}
#[test]
fn test_credentials_creation() {
let creds = Credentials::new("user@example.com", "password123");
assert_eq!(creds.email, "user@example.com");
assert_eq!(creds.password, "password123");
}
}