use sqlx::{sqlite::Sqlite, SqliteConnection, Transaction}; use uuid::Uuid; use crate::{ clock::DateTime, db::NotFound, event::{Instant, Sequence}, login::{self, History, Login}, name::{self, Name}, token::{Id, Secret}, }; pub trait Provider { fn tokens(&mut self) -> Tokens; } impl<'c> Provider for Transaction<'c, Sqlite> { fn tokens(&mut self) -> Tokens { Tokens(self) } } pub struct Tokens<'t>(&'t mut SqliteConnection); impl<'c> Tokens<'c> { // Issue a new token for an existing login. The issued_at timestamp will // be used to control expiry, until the token is actually used. pub async fn issue( &mut self, login: &History, issued_at: &DateTime, ) -> Result { let id = Id::generate(); let secret = Uuid::new_v4().to_string(); let login = login.id(); let secret = sqlx::query_scalar!( r#" insert into token (id, secret, login, issued_at, last_used_at) values ($1, $2, $3, $4, $4) returning secret as "secret!: Secret" "#, id, secret, login, issued_at, ) .fetch_one(&mut *self.0) .await?; Ok(secret) } pub async fn require(&mut self, token: &Id) -> Result<(), sqlx::Error> { sqlx::query_scalar!( r#" select id as "id: Id" from token where id = $1 "#, token, ) .fetch_one(&mut *self.0) .await?; Ok(()) } // Revoke a token by its secret. pub async fn revoke(&mut self, token: &Id) -> Result<(), sqlx::Error> { sqlx::query_scalar!( r#" delete from token where id = $1 returning id as "id: Id" "#, token, ) .fetch_one(&mut *self.0) .await?; Ok(()) } // Revoke tokens for a login pub async fn revoke_all(&mut self, login: &login::History) -> Result, sqlx::Error> { let login = login.id(); let tokens = sqlx::query_scalar!( r#" delete from token where login = $1 returning id as "id: Id" "#, login, ) .fetch_all(&mut *self.0) .await?; Ok(tokens) } // Expire and delete all tokens that haven't been used more recently than // `expire_at`. pub async fn expire(&mut self, expire_at: &DateTime) -> Result, sqlx::Error> { let tokens = sqlx::query_scalar!( r#" delete from token where last_used_at < $1 returning id as "id: Id" "#, expire_at, ) .fetch_all(&mut *self.0) .await?; Ok(tokens) } // Validate a token by its secret, retrieving the associated Login record. // Will return an error if the token is not valid. If successful, the // retrieved token's last-used timestamp will be set to `used_at`. pub async fn validate( &mut self, secret: &Secret, used_at: &DateTime, ) -> Result<(Id, History), LoadError> { // I would use `update … returning` to do this in one query, but // sqlite3, as of this writing, does not allow an update's `returning` // clause to reference columns from tables joined into the update. Two // queries is fine, but it feels untidy. let (token, login) = sqlx::query!( r#" update token set last_used_at = $1 where secret = $2 returning id as "token: Id", login as "login: login::Id" "#, used_at, secret, ) .map(|row| (row.token, row.login)) .fetch_one(&mut *self.0) .await?; let login = sqlx::query!( r#" select id as "id: login::Id", display_name as "display_name: String", canonical_name as "canonical_name: String", created_sequence as "created_sequence: Sequence", created_at as "created_at: DateTime" from login where id = $1 "#, login, ) .map(|row| { Ok::<_, name::Error>(History { login: Login { id: row.id, name: Name::new(row.display_name, row.canonical_name)?, }, created: Instant::new(row.created_at, row.created_sequence), }) }) .fetch_one(&mut *self.0) .await??; Ok((token, login)) } } #[derive(Debug, thiserror::Error)] #[error(transparent)] pub enum LoadError { Database(#[from] sqlx::Error), Name(#[from] name::Error), } impl NotFound for Result { type Ok = T; type Error = LoadError; fn optional(self) -> Result, LoadError> { match self { Ok(value) => Ok(Some(value)), Err(LoadError::Database(sqlx::Error::RowNotFound)) => Ok(None), Err(other) => Err(other), } } }