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;
pub mod blacklist;
pub mod rbac;
pub use blacklist::TokenBlacklist;
pub use rbac::{HasRolesAndPermissions, Role, Permission};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AuthUser {
pub sub: String, #[serde(default)]
pub name: 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 {
Self::with_name(user_id, "", email, role, permissions, hours)
}
pub fn with_name(
user_id: i64,
name: impl Into<String>,
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;
let mut n = name.into();
if n.is_empty() {
n = email.split('@').next().unwrap_or("Pengguna").to_string();
}
Self {
sub: user_id.to_string(),
name: n,
email,
role,
permissions,
iat: now,
exp: now + (hours * 3600),
}
}
pub fn display_name(&self) -> &str {
if !self.name.is_empty() {
&self.name
} else {
self.email.split('@').next().unwrap_or("Pengguna")
}
}
pub fn can(&self, permission: &str) -> bool {
<Self as HasRolesAndPermissions>::can(self, permission)
}
pub fn has_role(&self, role: &str) -> bool {
<Self as HasRolesAndPermissions>::has_role(self, role)
}
}
#[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;
}
}