diff --git a/service-users/src/token_db.rs b/service-users/src/token_db.rs index b94c1f1..770f510 100644 --- a/service-users/src/token_db.rs +++ b/service-users/src/token_db.rs @@ -33,6 +33,17 @@ pub async fn select_token_by_id(conn: &Object, token_id: &str) -> Result Ok(token) } +pub async fn insert_token(conn: &Object, user_id: &str) -> Result { + 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 { let new_id: Uuid = Uuid::now_v7(); let user_id = Uuid::from_str(new_user_id)?; diff --git a/service-users/src/user_service.rs b/service-users/src/user_service.rs index e2840c7..3dc39cf 100644 --- a/service-users/src/user_service.rs +++ b/service-users/src/user_service.rs @@ -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")); } @@ -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) @@ -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(),