Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
mpiorowski committed Jan 8, 2024
1 parent 74a1239 commit a4c9314
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
11 changes: 11 additions & 0 deletions service-users/src/token_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,17 @@ pub async fn select_token_by_id(conn: &Object, token_id: &str) -> Result<Token>
Ok(token)
}

pub async fn insert_token(conn: &Object, user_id: &str) -> Result<Uuid> {
let id: Uuid = Uuid::now_v7();
let user_id = Uuid::from_str(user_id)?;
conn.execute(
"insert into tokens (id, user_id) values ($1, $2)",
&[&id, &user_id],
)
.await?;
Ok(id)
}

pub async fn update_token_id(conn: &Object, old_id: &Uuid, new_user_id: &str) -> Result<Uuid> {
let new_id: Uuid = Uuid::now_v7();
let user_id = Uuid::from_str(new_user_id)?;
Expand Down
22 changes: 14 additions & 8 deletions service-users/src/user_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub async fn auth(
})?;

// check if token has expired, 7 days
if token.updated + time::Duration::days(7) < time::OffsetDateTime::now_utc() {
if token.created + time::Duration::days(7) < time::OffsetDateTime::now_utc() {
tracing::error!("Token has expired");
return Err(Status::unauthenticated("Unauthenticated"));
}
Expand All @@ -98,13 +98,12 @@ pub async fn auth(
}

// create new token
let token_id =
crate::token_db::update_token_id(&conn, &token.id, &user.id)
.await
.map_err(|e| {
tracing::error!("Failed to update token: {:?}", e);
Status::internal("Failed to update token")
})?;
let token_id = crate::token_db::insert_token(&conn, &user.id)
.await
.map_err(|e| {
tracing::error!("Failed to insert token: {:?}", e);
Status::internal("Failed to insert token")
})?;

// check if user is subscribed
let subscribed = crate::stripe_service::check_subscription(&conn, env, &user)
Expand All @@ -115,6 +114,13 @@ pub async fn auth(
})?;
user.subscription_active = subscribed;

// Delete old tokens. If this fails, it's not a big deal.
tokio::spawn(async move {
if let Err(err) = crate::token_db::delete_old_tokens(&conn).await {
tracing::error!("Failed to delete old tokens: {:?}", err);
}
});

tracing::info!("auth: {:?}", start.elapsed());
Ok(Response::new(crate::proto::AuthResponse {
user: user.into(),
Expand Down

0 comments on commit a4c9314

Please sign in to comment.