diff --git a/services/identity/src/database.rs b/services/identity/src/database.rs --- a/services/identity/src/database.rs +++ b/services/identity/src/database.rs @@ -4,14 +4,14 @@ use aws_sdk_dynamodb::model::AttributeValue; use aws_sdk_dynamodb::output::{ - GetItemOutput, PutItemOutput, UpdateItemOutput, + GetItemOutput, PutItemOutput, QueryOutput, UpdateItemOutput, }; use aws_sdk_dynamodb::types::Blob; use aws_sdk_dynamodb::{Client, Error as DynamoDBError}; use aws_types::sdk_config::SdkConfig; use chrono::{DateTime, Utc}; use opaque_ke::{errors::ProtocolError, ServerRegistration}; -use tracing::{error, info}; +use tracing::{error, info, warn}; use crate::constants::{ ACCESS_TOKEN_SORT_KEY, ACCESS_TOKEN_TABLE, @@ -19,7 +19,7 @@ ACCESS_TOKEN_TABLE_PARTITION_KEY, ACCESS_TOKEN_TABLE_TOKEN_ATTRIBUTE, ACCESS_TOKEN_TABLE_VALID_ATTRIBUTE, USERS_TABLE, USERS_TABLE_PARTITION_KEY, USERS_TABLE_REGISTRATION_ATTRIBUTE, USERS_TABLE_USERNAME_ATTRIBUTE, - USERS_TABLE_USER_PUBLIC_KEY_ATTRIBUTE, + USERS_TABLE_USERNAME_INDEX, USERS_TABLE_USER_PUBLIC_KEY_ATTRIBUTE, }; use crate::opaque::Cipher; use crate::token::{AccessTokenData, AuthType}; @@ -225,6 +225,55 @@ .await .map_err(|e| Error::AwsSdk(e.into())) } + + pub async fn get_user_id_for_username( + &self, + username: String, + ) -> Result, Error> { + match self + .client + .query() + .table_name(USERS_TABLE) + .index_name(USERS_TABLE_USERNAME_INDEX) + .key_condition_expression(format!( + "{} = :u", + USERS_TABLE_USERNAME_ATTRIBUTE + )) + .expression_attribute_values(":u", AttributeValue::S(username.clone())) + .send() + .await + { + Ok(QueryOutput { + items: Some(mut items), + .. + }) => { + let num_items = items.len(); + if num_items < 1 { + return Ok(None); + } + if num_items > 1 { + warn!( + "{} user IDs associated with username {}: {:?}", + num_items, username, items + ); + } + parse_user_id_attribute(items[0].remove(USERS_TABLE_PARTITION_KEY)) + .map(Some) + .map_err(Error::Attribute) + } + Ok(_) => { + info!("No item found for username {} in users table", username); + Ok(None) + } + Err(e) => { + error!( + "DynamoDB client failed to get user ID for user {}: {}", + username, e + ); + Err(Error::AwsSdk(e.into())) + } + } + } } #[derive(