Added user apps and token resources.
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
|
||||
use super::{DatabaseError, dtos::TokenRow};
|
||||
|
||||
pub async fn issue<'e, E>(executor: E, token: TokenRow) -> Result<(), DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO tokens (
|
||||
id, app_id, access_token_hash, refresh_token_hash,
|
||||
access_expires_at, refresh_expires_at, revoked_at, created_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
"#,
|
||||
token.id,
|
||||
token.app_id,
|
||||
token.access_token_hash,
|
||||
token.refresh_token_hash,
|
||||
token.access_expires_at,
|
||||
token.refresh_expires_at,
|
||||
token.revoked_at,
|
||||
token.created_at,
|
||||
)
|
||||
.execute(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
let row = sqlx::query!(
|
||||
r#"
|
||||
UPDATE tokens
|
||||
SET access_token_hash = $2,
|
||||
refresh_token_hash = $3,
|
||||
access_expires_at = $4,
|
||||
refresh_expires_at = $5
|
||||
WHERE refresh_token_hash = $1
|
||||
AND revoked_at IS NULL
|
||||
AND refresh_expires_at > now()
|
||||
RETURNING id
|
||||
"#,
|
||||
old_refresh_hash,
|
||||
access_token_hash,
|
||||
refresh_token_hash,
|
||||
access_expires_at,
|
||||
refresh_expires_at,
|
||||
)
|
||||
.fetch_optional(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
Ok(row.is_some())
|
||||
}
|
||||
|
||||
pub async fn revoke<'e, E>(executor: E, token_hash: &[u8]) -> Result<(), DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'e, Database = sqlx::Postgres>,
|
||||
{
|
||||
sqlx::query!(
|
||||
r#"
|
||||
UPDATE tokens
|
||||
SET revoked_at = COALESCE(revoked_at, now())
|
||||
WHERE access_token_hash = $1 OR refresh_token_hash = $1
|
||||
"#,
|
||||
token_hash,
|
||||
)
|
||||
.execute(executor)
|
||||
.await
|
||||
.map_err(DatabaseError::from)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user