summaryrefslogtreecommitdiff
path: root/src/token
diff options
context:
space:
mode:
authorOwen Jacobson <owen@grimoire.ca>2025-08-24 17:03:16 -0400
committerOwen Jacobson <owen@grimoire.ca>2025-08-26 01:08:11 -0400
commit0bbc83f09cc7517dddf16770a15f9e90815f48ba (patch)
tree4b7ea51aab2e9255fb8832d3109b4bc8dc033f0c /src/token
parent218d6dbb56727721d19019c8514f5e4395596e98 (diff)
Generate tokens in memory and then store them.
This is the leading edge of a larger storage refactoring, where repo types stop doing things like generating secrets or deciding whether to carry out an operation. To make this work, there is now a `Token` type that holds the complete state of a token, in memory.
Diffstat (limited to 'src/token')
-rw-r--r--src/token/app.rs25
-rw-r--r--src/token/extract/identity.rs4
-rw-r--r--src/token/mod.rs32
-rw-r--r--src/token/repo/token.rs61
4 files changed, 77 insertions, 45 deletions
diff --git a/src/token/app.rs b/src/token/app.rs
index 8ec61c5..a7a843d 100644
--- a/src/token/app.rs
+++ b/src/token/app.rs
@@ -6,7 +6,7 @@ use futures::{
use sqlx::sqlite::SqlitePool;
use super::{
- Broadcaster, Event as TokenEvent, Id, Secret,
+ Broadcaster, Event as TokenEvent, Secret, Token,
extract::Identity,
repo::{self, Provider as _, auth::Provider as _},
};
@@ -48,12 +48,14 @@ impl<'a> Tokens<'a> {
// if the account is deleted during that time.
tx.commit().await?;
- user.as_snapshot().ok_or(LoginError::Rejected)?;
+ let user = user.as_snapshot().ok_or(LoginError::Rejected)?;
if stored_hash.verify(password)? {
let mut tx = self.db.begin().await?;
- let secret = tx.tokens().issue(&user, login_at).await?;
+ let (token, secret) = Token::generate(&user, login_at);
+ tx.tokens().create(&token, &secret).await?;
tx.commit().await?;
+
Ok(secret)
} else {
Err(LoginError::Rejected)
@@ -85,13 +87,16 @@ impl<'a> Tokens<'a> {
return Err(LoginError::Rejected);
}
- user.as_snapshot().ok_or(LoginError::Rejected)?;
+ let user_snapshot = user.as_snapshot().ok_or(LoginError::Rejected)?;
let to_hash = to.hash()?;
let mut tx = self.db.begin().await?;
- let tokens = tx.tokens().revoke_all(&user).await?;
tx.users().set_password(&user, &to_hash).await?;
- let secret = tx.tokens().issue(&user, changed_at).await?;
+
+ let tokens = tx.tokens().revoke_all(&user).await?;
+ let (token, secret) = Token::generate(&user_snapshot, changed_at);
+ tx.tokens().create(&token, &secret).await?;
+
tx.commit().await?;
for event in tokens.into_iter().map(TokenEvent::Revoked) {
@@ -121,13 +126,15 @@ impl<'a> Tokens<'a> {
pub async fn limit_stream<S, E>(
&self,
- token: Id,
+ token: &Token,
events: S,
) -> Result<impl Stream<Item = E> + std::fmt::Debug + use<S, E>, ValidateError>
where
S: Stream<Item = E> + std::fmt::Debug,
E: std::fmt::Debug,
{
+ let token = token.id.clone();
+
// Subscribe, first.
let token_events = self.token_events.subscribe();
@@ -188,13 +195,13 @@ impl<'a> Tokens<'a> {
Ok(())
}
- pub async fn logout(&self, token: &Id) -> Result<(), ValidateError> {
+ pub async fn logout(&self, token: &Token) -> Result<(), ValidateError> {
let mut tx = self.db.begin().await?;
tx.tokens().revoke(token).await?;
tx.commit().await?;
self.token_events
- .broadcast(TokenEvent::Revoked(token.clone()));
+ .broadcast(TokenEvent::Revoked(token.id.clone()));
Ok(())
}
diff --git a/src/token/extract/identity.rs b/src/token/extract/identity.rs
index 4d076d7..d01ab53 100644
--- a/src/token/extract/identity.rs
+++ b/src/token/extract/identity.rs
@@ -10,13 +10,13 @@ use crate::{
app::App,
clock::RequestedAt,
error::{Internal, Unauthorized},
- token::{self, app::ValidateError},
+ token::{Token, app::ValidateError},
user::User,
};
#[derive(Clone, Debug)]
pub struct Identity {
- pub token: token::Id,
+ pub token: Token,
pub user: User,
}
diff --git a/src/token/mod.rs b/src/token/mod.rs
index 33403ef..58ff08b 100644
--- a/src/token/mod.rs
+++ b/src/token/mod.rs
@@ -6,4 +6,36 @@ mod id;
pub mod repo;
mod secret;
+use uuid::Uuid;
+
+use crate::{
+ clock::DateTime,
+ user::{self, User},
+};
+
pub use self::{broadcaster::Broadcaster, event::Event, id::Id, secret::Secret};
+
+#[derive(Clone, Debug)]
+pub struct Token {
+ pub id: Id,
+ pub user: user::Id,
+ pub issued_at: DateTime,
+ pub last_used_at: DateTime,
+}
+
+impl Token {
+ pub fn generate(user: &User, issued_at: &DateTime) -> (Self, Secret) {
+ let id = Id::generate();
+ let secret = Uuid::new_v4().to_string().into();
+
+ (
+ Self {
+ id,
+ user: user.id.clone(),
+ issued_at: *issued_at,
+ last_used_at: *issued_at,
+ },
+ secret,
+ )
+ }
+}
diff --git a/src/token/repo/token.rs b/src/token/repo/token.rs
index 5368fee..afcde53 100644
--- a/src/token/repo/token.rs
+++ b/src/token/repo/token.rs
@@ -1,12 +1,11 @@
use sqlx::{SqliteConnection, Transaction, sqlite::Sqlite};
-use uuid::Uuid;
use crate::{
clock::DateTime,
db::NotFound,
event::{Instant, Sequence},
name::{self, Name},
- token::{Id, Secret},
+ token::{Id, Secret, Token},
user::{self, History, User},
};
@@ -23,33 +22,23 @@ impl Provider for Transaction<'_, Sqlite> {
pub struct Tokens<'t>(&'t mut SqliteConnection);
impl Tokens<'_> {
- // Issue a new token for an existing user. The issued_at timestamp will
- // determine the token's initial expiry deadline.
- pub async fn issue(
- &mut self,
- user: &History,
- issued_at: &DateTime,
- ) -> Result<Secret, sqlx::Error> {
- let id = Id::generate();
- let secret = Uuid::new_v4().to_string();
- let user = user.id();
-
- let secret = sqlx::query_scalar!(
+ pub async fn create(&mut self, token: &Token, secret: &Secret) -> Result<(), sqlx::Error> {
+ sqlx::query!(
r#"
insert
into token (id, secret, login, issued_at, last_used_at)
- values ($1, $2, $3, $4, $4)
- returning secret as "secret!: Secret"
+ values ($1, $2, $3, $4, $5)
"#,
- id,
+ token.id,
secret,
- user,
- issued_at,
+ token.user,
+ token.issued_at,
+ token.last_used_at,
)
.fetch_one(&mut *self.0)
.await?;
- Ok(secret)
+ Ok(())
}
pub async fn require(&mut self, token: &Id) -> Result<(), sqlx::Error> {
@@ -67,18 +56,15 @@ impl Tokens<'_> {
Ok(())
}
- // Revoke a token by its secret.
- pub async fn revoke(&mut self, token: &Id) -> Result<(), sqlx::Error> {
- sqlx::query_scalar!(
+ pub async fn revoke(&mut self, token: &Token) -> Result<(), sqlx::Error> {
+ sqlx::query!(
r#"
- delete
- from token
+ delete from token
where id = $1
- returning id as "id: Id"
"#,
- token,
+ token.id,
)
- .fetch_one(&mut *self.0)
+ .execute(&mut *self.0)
.await?;
Ok(())
@@ -127,24 +113,31 @@ impl Tokens<'_> {
&mut self,
secret: &Secret,
used_at: &DateTime,
- ) -> Result<(Id, History), LoadError> {
+ ) -> Result<(Token, 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, user) = sqlx::query!(
+ let token = sqlx::query!(
r#"
update token
set last_used_at = $1
where secret = $2
returning
- id as "token: Id",
- login as "login: user::Id"
+ id as "id: Id",
+ login as "login: user::Id",
+ issued_at as "issued_at: DateTime",
+ last_used_at as "last_used_at: DateTime"
"#,
used_at,
secret,
)
- .map(|row| (row.token, row.login))
+ .map(|row| Token {
+ id: row.id,
+ user: row.login,
+ issued_at: row.issued_at,
+ last_used_at: row.last_used_at,
+ })
.fetch_one(&mut *self.0)
.await?;
@@ -160,7 +153,7 @@ impl Tokens<'_> {
join login using (id)
where id = $1
"#,
- user,
+ token.user,
)
.map(|row| {
Ok::<_, name::Error>(History {