89 lines
2.4 KiB
Rust
89 lines
2.4 KiB
Rust
use chrono::{DateTime, Utc};
|
|
|
|
use super::RepositoryError;
|
|
use crate::{
|
|
database::{dtos::TokenRow, tokens as db},
|
|
domain::Token,
|
|
};
|
|
|
|
pub async fn get_by_access_token_hash<'e, E>(
|
|
executor: E,
|
|
access_token_hash: &[u8],
|
|
) -> Result<Option<Token>, RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
let token = db::get_by_access_token_hash(executor, access_token_hash)
|
|
.await?
|
|
.map(decode)
|
|
.transpose()?;
|
|
|
|
Ok(token)
|
|
}
|
|
|
|
pub async fn issue<'e, E>(executor: E, token: Token) -> Result<(), RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
Ok(db::issue(executor, encode(token)).await?)
|
|
}
|
|
|
|
pub async fn rotate_refresh_token<'e, E>(
|
|
executor: E,
|
|
old_refresh_hash: &[u8],
|
|
access_token_hash: &[u8],
|
|
refresh_token_hash: &[u8],
|
|
access_expires_at: DateTime<Utc>,
|
|
refresh_expires_at: DateTime<Utc>,
|
|
) -> Result<bool, RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
Ok(db::rotate_refresh_token(
|
|
executor,
|
|
old_refresh_hash,
|
|
access_token_hash,
|
|
refresh_token_hash,
|
|
access_expires_at,
|
|
refresh_expires_at,
|
|
)
|
|
.await?)
|
|
}
|
|
|
|
pub async fn revoke<'e, E>(executor: E, token_hash: &[u8]) -> Result<(), RepositoryError>
|
|
where
|
|
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
|
{
|
|
Ok(db::revoke(executor, token_hash).await?)
|
|
}
|
|
|
|
fn decode(token: TokenRow) -> Result<Token, RepositoryError> {
|
|
Ok(Token {
|
|
id: token.id,
|
|
user_id: token.user_id,
|
|
user_app_id: token.user_app_id,
|
|
access_token_hash: token.access_token_hash,
|
|
refresh_token_hash: token.refresh_token_hash,
|
|
access_expires_at: token.access_expires_at,
|
|
refresh_expires_at: token.refresh_expires_at,
|
|
refreshed_at: token.refreshed_at,
|
|
revoked_at: token.revoked_at,
|
|
created_at: token.created_at,
|
|
})
|
|
}
|
|
|
|
fn encode(token: Token) -> TokenRow {
|
|
TokenRow {
|
|
id: token.id,
|
|
user_id: token.user_id,
|
|
user_app_id: token.user_app_id,
|
|
access_token_hash: token.access_token_hash,
|
|
refresh_token_hash: token.refresh_token_hash,
|
|
access_expires_at: token.access_expires_at,
|
|
refresh_expires_at: token.refresh_expires_at,
|
|
refreshed_at: token.refreshed_at,
|
|
revoked_at: token.revoked_at,
|
|
created_at: token.created_at,
|
|
}
|
|
}
|