use async_trait::async_trait;
use axum::{extract::FromRequestParts, http::request::Parts};
use serde::{Deserialize, Serialize};
use tower_sessions::Session;
pub mod hash;
pub mod socialite;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AuthUser {
pub sub: String, pub email: String,
pub role: String,
pub permissions: Vec<String>,
pub exp: usize, pub iat: usize, }
impl AuthUser {
pub fn new(
user_id: i64,
email: String,
role: String,
permissions: Vec<String>,
hours: usize,
) -> Self {
use std::time::{SystemTime, UNIX_EPOCH};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs() as usize;
Self {
sub: user_id.to_string(),
email,
role,
permissions,
iat: now,
exp: now + (hours * 3600),
}
}
pub fn can(&self, permission: &str) -> bool {
self.permissions.iter().any(|p| p == permission)
}
pub fn has_role(&self, role: &str) -> bool {
self.role == role || self.role == "admin"
}
}
#[async_trait]
impl<S> FromRequestParts<S> for AuthUser
where
S: Send + Sync,
{
type Rejection = crate::core::error::AppError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<Self>()
.cloned()
.ok_or(crate::core::error::AppError::Unauthorized)
}
}
pub struct Auth;
impl Auth {
pub fn make_hash(plain: &str) -> String {
self::hash::make(plain)
}
pub fn verify(plain: &str, hashed: &str) -> bool {
self::hash::check(plain, hashed)
}
pub fn check(plain: &str, hashed: &str) -> bool {
self::hash::check(plain, hashed)
}
pub fn user(user_id: i64, email: String, role: String, permissions: Vec<String>) -> AuthUser {
AuthUser::new(user_id, email, role, permissions, 24)
}
pub async fn login(session: &Session, auth_user: AuthUser) -> Result<(), tower_sessions::session::Error> {
let _ = session.insert("user", auth_user.clone()).await;
if let Ok(token) = crate::http::auth::generate_token(&auth_user) {
let _ = session.insert("jwt", token).await;
}
Ok(())
}
pub async fn logout(session: &Session) {
session.clear().await;
}
}