use crate::errors::{AuthError, Result};
use crate::storage::AuthStorage;
fn rejected(message: &str) -> AuthError {
AuthError::token(message.to_string())
}
fn credentials_not_before_key(user_id: &str) -> String {
format!("user:{user_id}:credentials_not_before")
}
pub(crate) async fn revoke_user_credentials(
storage: &dyn AuthStorage,
user_id: &str,
) -> Result<()> {
let now_ms = chrono::Utc::now().timestamp_millis();
storage
.store_kv(
&credentials_not_before_key(user_id),
now_ms.to_string().as_bytes(),
None,
)
.await?;
for session in storage.list_user_sessions(user_id).await? {
storage.delete_session(&session.session_id).await?;
}
for token in storage.list_user_tokens(user_id).await? {
storage.delete_token(&token.token_id).await?;
}
Ok(())
}
pub(crate) async fn ensure_issued_after_revocation(
storage: &dyn AuthStorage,
user_id: &str,
issued_ms: i64,
) -> Result<()> {
match storage.get_kv(&credentials_not_before_key(user_id)).await {
Ok(None) => Ok(()),
Ok(Some(bytes)) => match String::from_utf8_lossy(&bytes).trim().parse::<i64>() {
Ok(not_before) if issued_ms > not_before => Ok(()),
Ok(_) => Err(rejected(
"Credential was issued before the account's credentials were reset",
)),
Err(_) => Err(rejected("Unable to verify credential status")),
},
Err(e) => {
tracing::error!("Could not read credential state: {}", e);
Err(rejected("Unable to verify credential status"))
}
}
}
pub(crate) async fn ensure_account_active(storage: &dyn AuthStorage, user_id: &str) -> Result<()> {
match storage.get_kv(&format!("user:{user_id}")).await {
Ok(None) => Ok(()),
Ok(Some(bytes)) => match serde_json::from_slice::<serde_json::Value>(&bytes) {
Ok(record) if record["active"].as_bool().unwrap_or(true) => Ok(()),
Ok(_) => Err(rejected("Account has been deactivated")),
Err(_) => Err(rejected("Unable to verify account status")),
},
Err(e) => {
tracing::error!("Could not read account record: {}", e);
Err(rejected("Unable to verify account status"))
}
}
}